Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Aggregate region and grid map tooltips when the mapped dimensions are not unique (#80027)

Anderson723aebae0868
diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx
index 5dc189f5a97..15c110b49b8 100644
--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx
+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx
@@ -2,7 +2,7 @@ import cx from "classnames";
import * as d3 from "d3";
import type { Feature, FeatureCollection } from "geojson";
import type L from "leaflet";
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { jt, t } from "ttag";
import _ from "underscore";
@@ -21,6 +21,7 @@ import {
} from "metabase/visualizations/lib/choropleth";
import { MinColumnsError } from "metabase/visualizations/lib/errors";
import { getCanonicalRowKey } from "metabase/visualizations/lib/mapping";
+import { unaggregatedDataWarningMap } from "metabase/visualizations/lib/warnings";
import {
getDefaultSize,
getMinSize,
@@ -230,19 +231,6 @@ function getMapProjection(region: string | undefined): MapProjection {
return { projection: null, projectionFrame: null };
}
-function buildValuesMap(
- rows: RowValue[][],
- getRowKey: (row: RowValue[]) => string,
- getRowValue: (row: RowValue[]) => number,
-): Record<string, number> {
- const valuesMap: Record<string, number> = {};
- for (const row of rows) {
- const key = getRowKey(row);
- valuesMap[key] = (valuesMap[key] || 0) + getRowValue(row);
- }
- return valuesMap;
-}
-
function computeAspectRatio(
projection: Projection,
projectionFrame: ProjectionFrame | null,
@@ -278,6 +266,7 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {
isDashboard,
isDocument,
isMetricsViewer,
+ onRender,
onRenderError,
} = props;
@@ -285,13 +274,47 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {
const geoJsonPath = details ? getMapUrl(details, props) : null;
const { geoJson, minimalBounds } = useGeoJson(geoJsonPath);
+ const [
+ {
+ data: { cols, rows },
+ card,
+ },
+ ] = series;
+ const region = settings["map.region"];
+ const dimensionIndex = _.findIndex(
+ cols,
+ (col) => col.name === settings["map.dimension"],
+ );
+ const metricIndex = _.findIndex(
+ cols,
+ (col) => col.name === settings["map.metric"],
+ );
+ const dimensionColumn = cols[dimensionIndex];
+
+ const rowsByFeatureKey = useMemo(
+ () =>
+ _.groupBy(rows, (row) => getCanonicalRowKey(row[dimensionIndex], region)),
+ [rows, dimensionIndex, region],
+ );
+
+ const warnings = useMemo(() => {
+ const hasRowsToAggregate = Object.values(rowsByFeatureKey).some(
+ (featureRows) => featureRows.length > 1,
+ );
+ return hasRowsToAggregate && dimensionColumn
+ ? [unaggregatedDataWarningMap([dimensionColumn]).text]
+ : [];
+ }, [rowsByFeatureKey, dimensionColumn]);
+
+ useEffect(() => {
+ onRender({ warnings });
+ }, [onRender, warnings]);
+
if (!details) {
return <MapNotFound />;
}
- const { projection, projectionFrame } = getMapProjection(
- settings["map.region"],
- );
+ const { projection, projectionFrame } = getMapProjection(region);
if (!geoJson) {
return (
@@ -304,23 +327,6 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {
const nameProperty = details.region_name;
const keyProperty = details.region_key;
- const [
- {
- data: { cols, rows },
- card,
- },
- ] = series;
- const dimensionIndex = _.findIndex(
- cols,
- (col) => col.name === settings["map.dimension"],
- );
- const metricIndex = _.findIndex(
- cols,
- (col) => col.name === settings["map.metric"],
- );
-
- const getRowKey = (row: RowValue[]): string =>
- getCanonicalRowKey(row[dimensionIndex], settings["map.region"]);
const getRowValue = (row: RowValue[]): number => {
const value = row[metricIndex];
return typeof value === "number" ? value : 0;
@@ -336,14 +342,12 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {
return lowerCase ? key.toLowerCase() : key;
};
- const valuesMap = buildValuesMap(rows, getRowKey, getRowValue);
+ const valuesMap = _.mapObject(rowsByFeatureKey, (featureRows) =>
+ featureRows.reduce((sum, row) => sum + getRowValue(row), 0),
+ );
const getFeatureValue = (feature: Feature): number | undefined =>
valuesMap[getFeatureKey(feature)];
- const rowByFeatureKey = new Map<string, RowValue[]>(
- rows.map((row) => [getRowKey(row), row]),
- );
-
const clickContext: FeatureClickContext = {
cols,
dimensionIndex,
@@ -357,9 +361,13 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {
const onClickFeature =
onVisualizationClick != null
? (click: FeatureInteraction) => {
- const row = rowByFeatureKey.get(getFeatureKey(click.feature));
+ const featureRows = rowsByFeatureKey[getFeatureKey(click.feature)];
const clickData = {
- ...buildFeatureClickObject(row, click.feature, clickContext),
+ ...buildFeatureClickObject(
+ featureRows,
+ click.feature,
+ clickContext,
+ ),
event: click.event,
};
if (visualizationIsClickable(clickData)) {
@@ -370,10 +378,15 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {
const onHoverFeature = onHoverChange
? (hover: FeatureInteraction | null) => {
- const row = hover && rowByFeatureKey.get(getFeatureKey(hover.feature));
- if (row && hover) {
+ const featureRows =
+ hover && rowsByFeatureKey[getFeatureKey(hover.feature)];
+ if (featureRows && hover) {
onHoverChange({
- ...buildFeatureClickObject(row, hover.feature, clickContext),
+ ...buildFeatureClickObject(
+ featureRows,
+ hover.feature,
+ clickContext,
+ ),
event: hover.event,
});
} else {
@@ -397,13 +410,12 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {
};
const isSeriesHighlighted = card.id === highlighted?.cardId;
- const dimensionColumn = cols[dimensionIndex];
const highlightedDimension = highlighted?.dimensions?.find(
(d) => d.columnName === dimensionColumn?.name,
);
const highlightedKey =
isSeriesHighlighted && highlightedDimension
- ? getCanonicalRowKey(highlightedDimension.value, settings["map.region"])
+ ? getCanonicalRowKey(highlightedDimension.value, region)
: null;
const isFeatureHighlighted = (feature: Feature): boolean | null => {
diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.ts b/frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.tsx
similarity index 50%
rename from frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.ts
rename to frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.tsx
index 4a165d36597..f138b86e9f9 100644
--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.tsx
@@ -1,9 +1,21 @@
+import fetchMock from "fetch-mock";
+
+import { renderWithProviders, waitFor } from "__support__/ui";
import { mockIsEmbeddingSdk } from "metabase/embedding-sdk/mocks/config-mock";
-import { getMapUrl } from "metabase/visualizations/components/ChoroplethMap";
+import MetabaseSettings from "metabase/utils/settings";
+import {
+ ChoroplethMap,
+ getMapUrl,
+} from "metabase/visualizations/components/ChoroplethMap";
import { buildFeatureClickObject } from "metabase/visualizations/components/ChoroplethMap.utils";
import { getLegendTitles } from "metabase/visualizations/lib/choropleth";
-import type { ColumnSettings } from "metabase-types/api";
-import { createMockColumn } from "metabase-types/api/mocks";
+import { createMockVisualizationProps } from "metabase/visualizations/types/mocks";
+import type { ColumnSettings, RowValue } from "metabase-types/api";
+import {
+ createMockColumn,
+ createMockDatasetData,
+ createMockSingleSeries,
+} from "metabase-types/api/mocks";
const currencyColumnSettings: ColumnSettings = {
column: { base_type: "type/Float" },
@@ -36,7 +48,7 @@ describe("buildFeatureClickObject", () => {
it("includes cardId and the row dimension for populated regions", () => {
expect(
- buildFeatureClickObject(["CA", 10], null, clickContext),
+ buildFeatureClickObject([["CA", 10]], null, clickContext),
).toMatchObject({
cardId: 42,
value: 10,
@@ -45,6 +57,38 @@ describe("buildFeatureClickObject", () => {
});
});
+ it("sums the metric of all rows mapped to the same region (metabase#69659)", () => {
+ const idColumn = createMockColumn({
+ name: "ID",
+ display_name: "ID",
+ source: "breakout",
+ });
+ const clickObject = buildFeatureClickObject(
+ [
+ ["CA", 1, 10],
+ ["CA", 2, 20],
+ ["ca", 3, 5],
+ ],
+ null,
+ {
+ ...clickContext,
+ cols: [stateColumn, idColumn, countColumn],
+ metricIndex: 2,
+ },
+ );
+
+ expect(clickObject).toMatchObject({
+ cardId: 42,
+ value: 35,
+ column: countColumn,
+ dimensions: [{ value: "CA", column: stateColumn }],
+ data: [
+ { key: "State", value: "CA", col: stateColumn },
+ { key: "Count", value: 35, col: countColumn },
+ ],
+ });
+ });
+
it("returns an empty-dimension click object for empty regions", () => {
expect(
buildFeatureClickObject(
@@ -64,6 +108,105 @@ describe("buildFeatureClickObject", () => {
});
});
+describe("ChoroplethMap", () => {
+ const WORLD_GEOJSON_URL = "app/assets/geojson/world.json";
+
+ const setup = (rows: RowValue[][]) => {
+ jest.spyOn(MetabaseSettings, "get").mockImplementation((key: string) => {
+ if (key === "custom-geojson") {
+ return {
+ world_countries: {
+ name: "World",
+ url: WORLD_GEOJSON_URL,
+ region_key: "ISO_A2",
+ region_name: "NAME",
+ builtin: true,
+ },
+ };
+ }
+ return null;
+ });
+ fetchMock.get(`end:${WORLD_GEOJSON_URL}`, {
+ type: "FeatureCollection",
+ features: [],
+ });
+
+ const onRender = jest.fn();
+ const series = [
+ createMockSingleSeries(
+ {},
+ {
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({
+ name: "COUNTRY",
+ display_name: "Country",
+ semantic_type: "type/Country",
+ }),
+ createMockColumn({ name: "ID", display_name: "ID" }),
+ createMockColumn({ name: "count", display_name: "Count" }),
+ ],
+ rows,
+ }),
+ },
+ ),
+ ];
+ const props = createMockVisualizationProps({
+ series,
+ rawSeries: series,
+ data: series[0].data,
+ card: series[0].card,
+ settings: {
+ "map.type": "region",
+ "map.region": "world_countries",
+ "map.dimension": "COUNTRY",
+ "map.metric": "count",
+ },
+ onRender,
+ });
+
+ renderWithProviders(<ChoroplethMap {...props} />);
+
+ return { onRender };
+ };
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("should report the unaggregated data warning when several rows map to the same region (metabase#69659)", async () => {
+ const { onRender } = setup([
+ ["DZ", 1, 1],
+ ["DZ", 2, 1],
+ ["US", 3, 1],
+ ]);
+
+ await waitFor(() => {
+ expect(onRender).toHaveBeenCalledWith({
+ warnings: [
+ '"Country" is an unaggregated field: if it has more than one row with the same value, their measure values will be summed.',
+ ],
+ });
+ });
+ });
+
+ it("should not report the unaggregated data warning when regions are unique", async () => {
+ const { onRender } = setup([
+ ["DZ", 1, 1],
+ ["US", 3, 1],
+ ]);
+
+ await waitFor(() => {
+ expect(onRender).toHaveBeenCalledWith({ warnings: [] });
+ });
+ expect(onRender).not.toHaveBeenCalledWith({
+ warnings: expect.arrayContaining([
+ expect.stringContaining("unaggregated"),
+ ]),
+ });
+ });
+});
+
describe("getLegendTitles", () => {
it("should not format short values compactly", () => {
const groups = [
diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.utils.ts b/frontend/src/metabase/visualizations/components/ChoroplethMap.utils.ts
index e569e6ece0a..62a3af8ec05 100644
--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.utils.ts
+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.utils.ts
@@ -1,5 +1,6 @@
import type { Feature } from "geojson";
+import { sumMetric } from "metabase/visualizations/lib/dataset";
import type {
CardId,
DatasetColumn,
@@ -18,7 +19,7 @@ export type FeatureClickContext = {
};
export function buildFeatureClickObject(
- row: RowValue[] | undefined,
+ rows: RowValue[][] | undefined,
feature: Feature | null,
ctx: FeatureClickContext,
) {
@@ -33,7 +34,7 @@ export function buildFeatureClickObject(
} = ctx;
// This branch lets you click on empty regions. We use in dashboard cross-filtering.
- if (row == null) {
+ if (rows == null || rows.length === 0) {
return {
value: null,
column: cols[metricIndex],
@@ -52,27 +53,48 @@ export function buildFeatureClickObject(
};
}
+ const [row] = rows;
+ const getDataPoint = (value: RowValue, index: number) => ({
+ key: cols[index].display_name,
+ value:
+ index === dimensionIndex && feature != null
+ ? getFeatureName(feature)
+ : value,
+ // We set clickBehaviorValue to the raw data value for use in a filter via crossfiltering.
+ // `value` above is used in the tool tips so it needs to use `getFeatureName`
+ clickBehaviorValue: value,
+ col: cols[index],
+ });
+ const dimensions = [
+ { value: row[dimensionIndex], column: cols[dimensionIndex] },
+ ];
+
+ if (rows.length === 1) {
+ return {
+ value: row[metricIndex],
+ column: cols[metricIndex],
+ dimensions,
+ data: row.map(getDataPoint),
+ origin: { row, cols },
+ settings,
+ cardId,
+ };
+ }
+
+ // Multiple rows map to this feature (e.g. an extra breakout), so we sum the
+ // metric and expose only the dimension and metric columns.
+ const value = rows.reduce<RowValue>(
+ (sum, row) => sumMetric(sum, row[metricIndex]),
+ null,
+ );
return {
- value: row[metricIndex],
+ value,
column: cols[metricIndex],
- dimensions: [
- {
- value: row[dimensionIndex],
- column: cols[dimensionIndex],
- },
+ dimensions,
+ data: [
+ getDataPoint(row[dimensionIndex], dimensionIndex),
+ getDataPoint(value, metricIndex),
],
- data: row.map((value, index) => ({
- key: cols[index].display_name,
- value:
- index === dimensionIndex && feature != null
- ? getFeatureName(feature)
- : value,
- // We set clickBehaviorValue to the raw data value for use in a filter via crossfiltering.
- // `value` above is used in the tool tips so it needs to use `getFeatureName`
- clickBehaviorValue: value,
- col: cols[index],
- })),
- origin: { row, cols },
settings,
cardId,
};
diff --git a/frontend/src/metabase/visualizations/components/PinMap.tsx b/frontend/src/metabase/visualizations/components/PinMap.tsx
index d1494860cac..3284a1ac360 100644
--- a/frontend/src/metabase/visualizations/components/PinMap.tsx
+++ b/frontend/src/metabase/visualizations/components/PinMap.tsx
@@ -3,10 +3,13 @@ import * as d3 from "d3";
import L from "leaflet";
import { type ComponentClass, useCallback, useEffect, useState } from "react";
import { t } from "ttag";
+import _ from "underscore";
import ButtonsS from "metabase/css/components/buttons.module.css";
import CS from "metabase/css/core/index.css";
import DashboardS from "metabase/css/dashboard.module.css";
+import { sumMetric } from "metabase/visualizations/lib/dataset";
+import { unaggregatedDataWarningMap } from "metabase/visualizations/lib/warnings";
import type { VisualizationProps } from "metabase/visualizations/types";
import type {
DatasetData,
@@ -55,6 +58,33 @@ interface GetPointsParams {
longitudeColumnName?: string;
metricColumnName?: string;
isPinMap?: boolean;
+ isGridMap?: boolean;
+}
+
+// Grid maps draw one cell per point, so rows sharing the same cell (e.g. an
+// extra breakout) are folded into a single point with the summed metric.
+function aggregatePointsByCoordinates(
+ points: PinMapPoint[],
+ rows: RowValues[],
+) {
+ const cells = Object.values(
+ _.groupBy(
+ points.map((point, index) => ({ point, row: rows[index] })),
+ ({ point: [latitude, longitude] }) => `${latitude},${longitude}`,
+ ),
+ );
+
+ return {
+ points: cells.map((cell): PinMapPoint => {
+ const [latitude, longitude] = cell[0].point;
+ const metric = cell.reduce<number | null>(
+ (sum, { point }) => sumMetric(sum, point[2]),
+ null,
+ );
+ return [latitude, longitude, metric];
+ }),
+ rows: cells.map((cell) => cell[0].row),
+ };
}
export function getPoints({
@@ -63,6 +93,7 @@ export function getPoints({
longitudeColumnName,
metricColumnName,
isPinMap = false,
+ isGridMap = false,
}: GetPointsParams): GetPointsResult {
const latitudeIndex = cols.findIndex(
(col) => col.name === latitudeColumnName,
@@ -86,18 +117,29 @@ export function getPoints({
return lat != null && lng != null && metric != null;
});
- const points = allPoints.filter(
+ const validRowPoints = allPoints.filter(
(_point, i): _point is PinMapPoint => validPoints[i],
);
- const updatedRows = rows.filter((_row, i) => validPoints[i]);
+ const validRows = rows.filter((_row, i) => validPoints[i]);
+
+ const { points, rows: updatedRows } = isGridMap
+ ? aggregatePointsByCoordinates(validRowPoints, validRows)
+ : { points: validRowPoints, rows: validRows };
const warnings: string[] = [];
- const filteredRows = allPoints.length - points.length;
+ const filteredRows = allPoints.length - validRowPoints.length;
if (filteredRows > 0) {
warnings.push(
t`We filtered out ${filteredRows} row(s) containing null values.`,
);
}
+ const hasAggregatedPoints = points.length < validRowPoints.length;
+ if (hasAggregatedPoints && metricIndex >= 0) {
+ warnings.push(
+ unaggregatedDataWarningMap([cols[latitudeIndex], cols[longitudeIndex]])
+ .text,
+ );
+ }
const boundsPoints: L.LatLngTuple[] =
points.length > 0
@@ -159,13 +201,15 @@ export function PinMap(props: PinMapProps) {
latitudeColumnName: settings["map.latitude_column"],
longitudeColumnName: settings["map.longitude_column"],
metricColumnName: settings["map.metric_column"],
+ isGridMap: settings["map.pin_type"] === "grid",
};
const isPinMap = settings["map.type"] === "pin";
// A new points identity makes LeafletMap refit the viewport to the data
- // bounds, so points must be recomputed only when the data or the mapped
- // columns change; `map.type` is read at recompute time but must not trigger
- // one, hence state adjusted during render instead of useMemo.
+ // bounds, so points must be recomputed only when the data, the mapped
+ // columns or the grid aggregation change; `map.type` is read at recompute
+ // time but must not trigger one, hence state adjusted during render instead
+ // of useMemo.
const [pointsCache, setPointsCache] = useState(() => ({
inputs: pointsInputs,
result: getPoints({ ...pointsInputs, isPinMap }),
@@ -175,7 +219,8 @@ export function PinMap(props: PinMapProps) {
inputs.data !== pointsInputs.data ||
inputs.latitudeColumnName !== pointsInputs.latitudeColumnName ||
inputs.longitudeColumnName !== pointsInputs.longitudeColumnName ||
- inputs.metricColumnName !== pointsInputs.metricColumnName
+ inputs.metricColumnName !== pointsInputs.metricColumnName ||
+ inputs.isGridMap !== pointsInputs.isGridMap
) {
setPointsCache({
inputs: pointsInputs,
diff --git a/frontend/src/metabase/visualizations/components/PinMap.unit.spec.tsx b/frontend/src/metabase/visualizations/components/PinMap.unit.spec.tsx
index c042c791f26..abcd912a041 100644
--- a/frontend/src/metabase/visualizations/components/PinMap.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/components/PinMap.unit.spec.tsx
@@ -4,7 +4,11 @@ import userEvent from "@testing-library/user-event";
import { createMockMetadata } from "__support__/metadata";
import MetabaseSettings from "metabase/utils/settings";
import { createMockVisualizationProps } from "metabase/visualizations/types/mocks";
-import type { RowValue } from "metabase-types/api";
+import type {
+ DatasetData,
+ RowValue,
+ VisualizationSettings,
+} from "metabase-types/api";
import {
createMockColumn,
createMockDatasetData,
@@ -117,6 +121,95 @@ describe("getPoints", () => {
]);
});
+ it("should sum the metric of rows sharing the same grid cell (metabase#69659)", () => {
+ const { points, rows, min, max, warnings } = getPoints({
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({
+ name: "lat",
+ display_name: "Latitude",
+ binning_info: { bin_width: 10 },
+ }),
+ createMockColumn({
+ name: "lng",
+ display_name: "Longitude",
+ binning_info: { bin_width: 10 },
+ }),
+ createMockColumn({ name: "id" }),
+ createMockColumn({ name: "count", display_name: "Count" }),
+ ],
+ rows: [
+ [40, -80, 1, 1],
+ [40, -80, 2, 1],
+ [50, -70, 3, 4],
+ [40, -80, 4, 1],
+ ],
+ }),
+ latitudeColumnName: "lat",
+ longitudeColumnName: "lng",
+ metricColumnName: "count",
+ isGridMap: true,
+ });
+
+ expect(points).toEqual([
+ [40, -80, 3],
+ [50, -70, 4],
+ ]);
+ expect(rows).toEqual([
+ [40, -80, 1, 1],
+ [50, -70, 3, 4],
+ ]);
+ expect(min).toBe(3);
+ expect(max).toBe(4);
+ expect(warnings).toEqual([
+ '"Latitude", "Longitude" are unaggregated fields: if there is more than one row with the same values, their measure values will be summed.',
+ ]);
+ });
+
+ it("should not warn or aggregate when grid cells are unique", () => {
+ const { points, warnings } = getPoints({
+ data: createData(
+ ["lat", "lng", "metric"],
+ [
+ [40, -80, 1],
+ [50, -70, 4],
+ ],
+ ),
+ latitudeColumnName: "lat",
+ longitudeColumnName: "lng",
+ metricColumnName: "metric",
+ isGridMap: true,
+ });
+
+ expect(points).toEqual([
+ [40, -80, 1],
+ [50, -70, 4],
+ ]);
+ expect(warnings).toEqual([]);
+ });
+
+ it("should not aggregate points that share coordinates outside grid maps", () => {
+ const { points, warnings } = getPoints({
+ data: createData(
+ ["lat", "lng", "metric"],
+ [
+ [40, -80, 1],
+ [40, -80, 1],
+ ],
+ ),
+ latitudeColumnName: "lat",
+ longitudeColumnName: "lng",
+ metricColumnName: "metric",
+ isPinMap: true,
+ });
+
+ expect(points).toEqual([
+ [40, -80, 1],
+ [40, -80, 1],
+ ]);
+ expect(warnings).toEqual([]);
+ });
+
it("should extend the bounds by one bin to the north/east for binned coordinates", () => {
const { bounds } = getPoints({
data: createMockDatasetData({
@@ -145,7 +238,25 @@ describe("PinMap", () => {
const setup = ({
isDashboard = false,
token,
- }: { isDashboard?: boolean; token?: string } = {}) => {
+ data = createData(
+ ["lat", "lng"],
+ [
+ [10, 20],
+ [null, 30],
+ ],
+ ),
+ settings = {
+ "map.type": "pin",
+ "map.pin_type": "markers",
+ "map.latitude_column": "lat",
+ "map.longitude_column": "lng",
+ },
+ }: {
+ isDashboard?: boolean;
+ token?: string;
+ data?: DatasetData;
+ settings?: VisualizationSettings;
+ } = {}) => {
const onRender = jest.fn();
const series = [
@@ -156,15 +267,7 @@ describe("PinMap", () => {
query: { "source-table": ORDERS_ID },
}),
},
- {
- data: createData(
- ["lat", "lng"],
- [
- [10, 20],
- [null, 30],
- ],
- ),
- },
+ { data },
),
];
@@ -173,12 +276,7 @@ describe("PinMap", () => {
rawSeries: series,
data: series[0].data,
card: series[0].card,
- settings: {
- "map.type": "pin",
- "map.pin_type": "markers",
- "map.latitude_column": "lat",
- "map.longitude_column": "lng",
- },
+ settings,
metadata: createMockMetadata({ databases: [createSampleDatabase()] }),
isDashboard,
height: 300,
@@ -225,6 +323,43 @@ describe("PinMap", () => {
});
});
+ it("should report the unaggregated data warning for grid maps with duplicated cells (metabase#69659)", () => {
+ const { onRender } = setup({
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({
+ name: "lat",
+ display_name: "Latitude",
+ binning_info: { bin_width: 10 },
+ }),
+ createMockColumn({
+ name: "lng",
+ display_name: "Longitude",
+ binning_info: { bin_width: 10 },
+ }),
+ createMockColumn({ name: "count", display_name: "Count" }),
+ ],
+ rows: [
+ [40, -80, 1],
+ [40, -80, 1],
+ ],
+ }),
+ settings: {
+ "map.type": "grid",
+ "map.pin_type": "grid",
+ "map.latitude_column": "lat",
+ "map.longitude_column": "lng",
+ "map.metric_column": "count",
+ },
+ });
+
+ expect(onRender).toHaveBeenCalledWith({
+ warnings: [
+ '"Latitude", "Longitude" are unaggregated fields: if there is more than one row with the same values, their measure values will be summed.',
+ ],
+ });
+ });
+
it("should not render the 'Set as default view' button for static embedding", () => {
setup({ token: "token" });
diff --git a/frontend/src/metabase/visualizations/lib/warnings.ts b/frontend/src/metabase/visualizations/lib/warnings.ts
index 19ab694a69c..c6ef55a9d0c 100644
--- a/frontend/src/metabase/visualizations/lib/warnings.ts
+++ b/frontend/src/metabase/visualizations/lib/warnings.ts
@@ -6,6 +6,7 @@ const NULL_DIMENSION_WARNING = "NULL_DIMENSION_WARNING";
const INVALID_DATE_WARNING = "INVALID_DATE_WARNING";
const UNAGGREGATED_DATA_WARNING = "UNAGGREGATED_DATA_WARNING";
const UNAGGREGATED_DATA_WARNING_PIE = "UNAGGREGATED_DATA_WARNING_PIE";
+const UNAGGREGATED_DATA_WARNING_MAP = "UNAGGREGATED_DATA_WARNING_MAP";
const UNEXPECTED_QUERY_TIMEZONE = "UNEXPECTED_QUERY_TIMEZONE";
const MULTIPLE_TIMEZONES = "MULTIPLE_TIMEZONES";
const PIE_NEGATIVES = "PIE_NEGATIVES";
@@ -16,6 +17,7 @@ type VisualizationWarningKey =
| typeof INVALID_DATE_WARNING
| typeof UNAGGREGATED_DATA_WARNING
| typeof UNAGGREGATED_DATA_WARNING_PIE
+ | typeof UNAGGREGATED_DATA_WARNING_MAP
| typeof UNEXPECTED_QUERY_TIMEZONE
| typeof MULTIPLE_TIMEZONES
| typeof PIE_NEGATIVES
@@ -63,6 +65,25 @@ export function unaggregatedDataWarningPie(
};
}
+export function unaggregatedDataWarningMap(
+ columns: DatasetColumn[],
+): VisualizationWarning {
+ if (columns.length === 1) {
+ return {
+ key: UNAGGREGATED_DATA_WARNING_MAP,
+ text: t`"${
+ columns[0].display_name
+ }" is an unaggregated field: if it has more than one row with the same value, their measure values will be summed.`,
+ };
+ }
+
+ const fields = columns.map((column) => `"${column.display_name}"`).join(", ");
+ return {
+ key: UNAGGREGATED_DATA_WARNING_MAP,
+ text: t`${fields} are unaggregated fields: if there is more than one row with the same values, their measure values will be summed.`,
+ };
+}
+
export function unexpectedTimezoneWarning({
results_timezone,
requested_timezone,