Skip to content

Commit c0a8a70

Browse files
schizophrenicmaniacEnxDevsadpandajoe
authored
fix(dashboard): stop Save As from updating the source dashboard (#45220)
Co-authored-by: Enzo Martellucci <52219496+EnxDev@users.noreply.github.com> Co-authored-by: Joe Li <joe@preset.io>
1 parent 3e9cb35 commit c0a8a70

3 files changed

Lines changed: 193 additions & 10 deletions

File tree

‎superset-frontend/src/dashboard/actions/dashboardState.test.ts‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,11 @@
1717
* under the License.
1818
*/
1919
import {
20+
Behavior,
21+
ChartMetadata,
2022
JsonResponse,
2123
SupersetClient,
24+
getChartMetadataRegistry,
2225
isFeatureEnabled,
2326
} from '@superset-ui/core';
2427
import { waitFor } from 'spec/helpers/testing-library';
@@ -55,6 +58,7 @@ import {
5558
} from 'spec/fixtures/mockSliceEntities';
5659
import { emptyFilters } from 'spec/fixtures/mockDashboardFilters';
5760
import mockDashboardData from 'spec/fixtures/mockDashboardData';
61+
import { getCrossFiltersConfiguration } from 'src/dashboard/util/crossFilters';
5862
import type { RootState } from 'src/dashboard/types';
5963
import { navigateTo, navigateWithState } from 'src/utils/navigationUtils';
6064

@@ -496,6 +500,124 @@ describe('dashboardState actions', () => {
496500
);
497501
});
498502

503+
test('Save As sends the cross-filter config with the copy and leaves the source dashboard alone', async () => {
504+
const sourceDashboardId = 1;
505+
const vizType = 'interactive_test_chart';
506+
const chartLayoutItem = (chartId: number) => ({
507+
children: [],
508+
id: `CHART-${chartId}`,
509+
meta: { chartId, width: 4, height: 50 },
510+
parents: ['ROOT_ID', 'GRID_ID'],
511+
type: 'CHART',
512+
});
513+
const chart = (id: number) => ({ id, form_data: { viz_type: vizType } });
514+
// The stored chartsInScope values are stale on purpose, so the copy
515+
// only matches if the configuration is recomputed for the current state.
516+
const state = {
517+
...mockState,
518+
dashboardInfo: {
519+
id: sourceDashboardId,
520+
metadata: {
521+
color_scheme: 'supersetColors',
522+
chart_configuration: {
523+
'1': {
524+
id: 1,
525+
crossFilters: {
526+
scope: { rootPath: ['ROOT_ID'], excluded: [2] },
527+
chartsInScope: [2],
528+
},
529+
},
530+
'2': {
531+
id: 2,
532+
crossFilters: { scope: 'global', chartsInScope: [] },
533+
},
534+
},
535+
global_chart_configuration: {
536+
scope: { rootPath: ['ROOT_ID'], excluded: [] },
537+
chartsInScope: [],
538+
},
539+
},
540+
},
541+
dashboardLayout: {
542+
past: [],
543+
present: {
544+
'CHART-1': chartLayoutItem(1),
545+
'CHART-2': chartLayoutItem(2),
546+
},
547+
future: {},
548+
},
549+
charts: { 1: chart(1), 2: chart(2) },
550+
};
551+
const getState = jest.fn(() => state) as unknown as () => any;
552+
const dispatch: jest.Mock = jest.fn(action =>
553+
typeof action === 'function' ? action(dispatch, getState) : action,
554+
);
555+
getChartMetadataRegistry().registerValue(
556+
vizType,
557+
new ChartMetadata({
558+
name: 'interactive test chart',
559+
thumbnail: '.png',
560+
behaviors: [Behavior.InteractiveChart],
561+
}),
562+
);
563+
const requestStub = jest
564+
.spyOn(SupersetClient, 'request')
565+
.mockResolvedValue({ json: { result: {} } } as any);
566+
try {
567+
postStub.mockRestore();
568+
postStub = jest.spyOn(SupersetClient, 'post').mockResolvedValue({
569+
json: { result: { id: 999, last_modified_time: 0 } },
570+
} as any);
571+
572+
await saveDashboardRequest(
573+
{ ...newDashboardData, duplicate_slices: true },
574+
sourceDashboardId,
575+
SAVE_TYPE_NEWDASHBOARD,
576+
)(dispatch, getState);
577+
578+
await waitFor(() => expect(mockNavigateTo).toHaveBeenCalled());
579+
expect(
580+
dispatch.mock.calls.some(
581+
([action]) => action?.type === 'SAVE_CHART_CONFIG_BEGIN',
582+
),
583+
).toBe(false);
584+
expect(requestStub).not.toHaveBeenCalled();
585+
expect(putStub).not.toHaveBeenCalled();
586+
const { endpoint, jsonPayload } = postStub.mock.calls[0][0];
587+
expect(endpoint).toBe(`/api/v1/dashboard/${sourceDashboardId}/copy/`);
588+
const metadata = JSON.parse(jsonPayload.json_metadata);
589+
const { chartConfiguration, globalChartConfiguration } =
590+
getCrossFiltersConfiguration(
591+
state.dashboardLayout.present as any,
592+
state.dashboardInfo.metadata as any,
593+
state.charts as any,
594+
);
595+
expect(metadata.chart_configuration).toEqual(chartConfiguration);
596+
expect(metadata.global_chart_configuration).toEqual(
597+
globalChartConfiguration,
598+
);
599+
expect(metadata.chart_configuration).toEqual({
600+
'1': {
601+
id: 1,
602+
crossFilters: {
603+
scope: { rootPath: ['ROOT_ID'], excluded: [2] },
604+
chartsInScope: [],
605+
},
606+
},
607+
'2': {
608+
id: 2,
609+
crossFilters: { scope: 'global', chartsInScope: [1] },
610+
},
611+
});
612+
expect(metadata.global_chart_configuration.chartsInScope).toEqual([
613+
1, 2,
614+
]);
615+
} finally {
616+
requestStub.mockRestore();
617+
getChartMetadataRegistry().remove(vizType);
618+
}
619+
});
620+
499621
// `navigateWithState` regression for the
500622
// dashboard-properties-changed save path. Two assertions in one shape:
501623
// (a) the emitted path is router-relative (`/dashboard/<id>/`), not

‎superset-frontend/src/dashboard/actions/dashboardState.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,6 @@ import type { DashboardChartStates } from 'src/dashboard/types/chartState';
7070
import { nanoid } from 'nanoid';
7171
import { UPDATE_COMPONENTS_PARENTS_LIST } from './dashboardLayout';
7272
import {
73-
saveChartConfiguration,
7473
dashboardInfoChanged,
7574
SAVE_CHART_CONFIG_COMPLETE,
7675
provenSemanticDatasets,
@@ -577,14 +576,6 @@ export function saveDashboardRequest(
577576
if (lastModifiedTime) {
578577
dispatch(saveDashboardRequestSuccess(lastModifiedTime));
579578
}
580-
const { chartConfiguration, globalChartConfiguration } =
581-
handleChartConfiguration();
582-
dispatch(
583-
saveChartConfiguration({
584-
chartConfiguration,
585-
globalChartConfiguration,
586-
}),
587-
);
588579
dispatch(saveDashboardFinished());
589580
navigateTo(`/dashboard/${(response.json as JsonObject).result?.id}/`);
590581
dispatch(addSuccessToast(t('This dashboard was saved successfully.')));
@@ -768,6 +759,15 @@ export function saveDashboardRequest(
768759
(cleanedData.metadata as JsonObject).default_filters =
769760
safeStringify(serializedFilters);
770761
(cleanedData.metadata as JsonObject).filter_scopes = serializedFilterScopes;
762+
// Send the cross-filter configuration with the copy itself. Saving it
763+
// after the copy would write to the source dashboard, since that is
764+
// still the one held in dashboardInfo, and bump its changed_on/changed_by.
765+
const { chartConfiguration, globalChartConfiguration } =
766+
handleChartConfiguration();
767+
(cleanedData.metadata as JsonObject).chart_configuration =
768+
chartConfiguration;
769+
(cleanedData.metadata as JsonObject).global_chart_configuration =
770+
globalChartConfiguration;
771771
const copyPayload = {
772772
dashboard_title: cleanedData.dashboard_title,
773773
css: cleanedData.css,

‎tests/unit_tests/dao/dashboard_test.py‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
# under the License.
1717
from datetime import datetime, timezone
1818
from typing import Any
19-
from unittest.mock import patch
19+
from unittest.mock import MagicMock, patch
2020

2121
import pytest
2222
from sqlalchemy import event, inspect, select
@@ -34,6 +34,7 @@
3434
SqlMetric,
3535
TableColumn,
3636
)
37+
from superset.daos import dashboard as dashboard_dao
3738
from superset.daos.dashboard import (
3839
_install_membership_baseline,
3940
_layout_chart_id,
@@ -1195,6 +1196,66 @@ def narrow_like_the_get() -> None:
11951196
assert n == 0, f"the GET access loop issued {n} statements after the prefetch"
11961197

11971198

1199+
@pytest.mark.parametrize("duplicate_slices", [False, True])
1200+
def test_copy_dashboard_leaves_source_audit_fields_alone(
1201+
session: Session, duplicate_slices: bool
1202+
) -> None:
1203+
"""Save As must not write to the source dashboard (#45218).
1204+
1205+
Only the copy (and, with ``duplicate_slices``, the cloned charts) is new;
1206+
the source row must not be updated, so its ``changed_on`` and
1207+
``changed_by_fk`` keep pointing at the last real edit.
1208+
"""
1209+
Dashboard.metadata.create_all(session.get_bind())
1210+
1211+
source = _make_dashboard("copy-source", 2)
1212+
positions = {
1213+
f"CHART-{slc.id}": {
1214+
"type": "CHART",
1215+
"id": f"CHART-{slc.id}",
1216+
"children": [],
1217+
"meta": {"chartId": slc.id, "width": 4, "height": 50},
1218+
}
1219+
for slc in source.slices
1220+
}
1221+
source.position_json = json.dumps(positions)
1222+
session.commit()
1223+
changed_on, changed_by_fk = source.changed_on, source.changed_by_fk
1224+
1225+
updates: list[Any] = []
1226+
1227+
def before(conn, cursor, statement, params, ctx, many): # noqa: PLR0913
1228+
if statement.startswith("UPDATE dashboards "):
1229+
updates.append(params)
1230+
1231+
bind = session.get_bind()
1232+
event.listen(bind, "before_cursor_execute", before)
1233+
try:
1234+
with (
1235+
patch.object(security_manager, "is_editor", return_value=True),
1236+
patch.object(security_manager, "can_access_chart", return_value=True),
1237+
patch.object(security_manager, "is_admin", return_value=False),
1238+
patch.object(dashboard_dao, "g", MagicMock(user=None)),
1239+
):
1240+
new_dashboard = DashboardDAO.copy_dashboard(
1241+
source,
1242+
{
1243+
"dashboard_title": "copy",
1244+
"json_metadata": json.dumps({"positions": positions}),
1245+
"duplicate_slices": duplicate_slices,
1246+
},
1247+
)
1248+
session.commit()
1249+
finally:
1250+
event.remove(bind, "before_cursor_execute", before)
1251+
1252+
assert all(params[-1] == new_dashboard.id for params in updates)
1253+
session.expire_all()
1254+
source = session.query(Dashboard).filter_by(slug="copy-source").one()
1255+
assert source.changed_on == changed_on
1256+
assert source.changed_by_fk == changed_by_fk
1257+
1258+
11981259
def _make_dataset_dashboard(slug: str, n_datasets: int) -> Dashboard:
11991260
"""A dashboard with one chart on each of n_datasets datasets.
12001261

0 commit comments

Comments
 (0)