Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Restructure explore redux state #20448

Merged
merged 11 commits into from
Jun 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export interface Dataset {
granularity_sqla?: string;
datasource_name: string | null;
description: string | null;
uid?: string;
}

export interface ControlPanelState {
Expand Down
9 changes: 8 additions & 1 deletion superset-frontend/spec/helpers/reducerIndex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ const impressionId = (state = '') => state;
const container = document.getElementById('app');
const bootstrap = JSON.parse(container?.getAttribute('data-bootstrap') ?? '{}');
const common = { ...bootstrap.common };
const user = { ...bootstrap.user };

const noopReducer =
(initialState: unknown) =>
(state = initialState) =>
state;

export default {
charts,
Expand All @@ -55,5 +61,6 @@ export default {
sqlLab,
localStorageUsageInKilobytes,
reports,
common: () => common,
common: noopReducer(common),
user: noopReducer(user),
};
2 changes: 1 addition & 1 deletion superset-frontend/src/addSlice/AddSliceContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { Tooltip } from 'src/components/Tooltip';
import VizTypeGallery, {
MAX_ADVISABLE_VIZ_GALLERY_WIDTH,
} from 'src/explore/components/controls/VizTypeControl/VizTypeGallery';
import findPermission from 'src/dashboard/util/findPermission';
import { findPermission } from 'src/utils/findPermission';
import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes';

type Dataset = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,35 +33,31 @@ const createProps = () => ({
});

const stateWithOnlyUser = {
explore: {
user: {
email: '[email protected]',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
createdOn: '2022-01-12T10:17:37.801361',
roles: { Admin: [['menu_access', 'Manage']] },
userId: 1,
username: 'admin',
},
user: {
email: '[email protected]',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
createdOn: '2022-01-12T10:17:37.801361',
roles: { Admin: [['menu_access', 'Manage']] },
userId: 1,
username: 'admin',
},
reports: {},
};

const stateWithUserAndReport = {
explore: {
user: {
email: '[email protected]',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
createdOn: '2022-01-12T10:17:37.801361',
roles: { Admin: [['menu_access', 'Manage']] },
userId: 1,
username: 'admin',
},
user: {
email: '[email protected]',
firstName: 'admin',
isActive: true,
lastName: 'admin',
permissions: {},
createdOn: '2022-01-12T10:17:37.801361',
roles: { Admin: [['menu_access', 'Manage']] },
userId: 1,
username: 'admin',
},
reports: {
dashboards: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export default function HeaderReportDropDown({
const user: UserWithPermissionsAndRoles = useSelector<
any,
UserWithPermissionsAndRoles
>(state => state.user || state.explore?.user);
>(state => state.user);
const canAddReports = () => {
if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) {
return false;
Expand Down
5 changes: 2 additions & 3 deletions superset-frontend/src/dashboard/actions/hydrate.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@ import { initSliceEntities } from 'src/dashboard/reducers/sliceEntities';
import { getInitialState as getInitialNativeFilterState } from 'src/dashboard/reducers/nativeFilters';
import { applyDefaultFormData } from 'src/explore/store';
import { buildActiveFilters } from 'src/dashboard/util/activeDashboardFilters';
import findPermission, {
canUserEditDashboard,
} from 'src/dashboard/util/findPermission';
import { findPermission } from 'src/utils/findPermission';
import { canUserEditDashboard } from 'src/dashboard/util/permissionUtils';
import {
DASHBOARD_FILTER_SCOPE_GLOBAL,
dashboardFilter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
import Icons from 'src/components/Icons';
import Button from 'src/components/Button';
import { AntdButton } from 'src/components/';
import { findPermission } from 'src/utils/findPermission';
michael-s-molina marked this conversation as resolved.
Show resolved Hide resolved
import { Tooltip } from 'src/components/Tooltip';
import { safeStringify } from 'src/utils/safeStringify';
import HeaderActionsDropdown from 'src/dashboard/components/Header/HeaderActionsDropdown';
Expand All @@ -48,7 +49,6 @@ import setPeriodicRunner, {
stopPeriodicRender,
} from 'src/dashboard/util/setPeriodicRunner';
import { options as PeriodicRefreshOptions } from 'src/dashboard/components/RefreshIntervalModal';
import findPermission from 'src/dashboard/util/findPermission';
import { FILTER_BOX_MIGRATION_STATES } from 'src/explore/constants';
import { PageHeaderWithActions } from 'src/components/PageHeaderWithActions';
import { DashboardEmbedModal } from '../DashboardEmbedControls';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ import {
} from 'src/explore/constants';
import { URL_PARAMS } from 'src/constants';
import { getUrlParam } from 'src/utils/urlUtils';
import { canUserEditDashboard } from 'src/dashboard/util/findPermission';
import { canUserEditDashboard } from 'src/dashboard/util/permissionUtils';
import { getFilterSets } from '../actions/nativeFilters';
import { setDatasetsStatus } from '../actions/dashboardState';
import {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,7 @@ import {
} from 'src/types/bootstrapTypes';
import Dashboard from 'src/types/Dashboard';
import Owner from 'src/types/Owner';
import findPermission, {
canUserEditDashboard,
isUserAdmin,
} from './findPermission';
import { canUserEditDashboard, isUserAdmin } from './permissionUtils';

const ownerUser: UserWithPermissionsAndRoles = {
createdOn: '2021-05-12T16:56:22.116839',
Expand Down Expand Up @@ -65,54 +62,6 @@ const owner: Owner = {

const undefinedUser: UndefinedUser = {};

describe('findPermission', () => {
it('findPermission for single role', () => {
expect(findPermission('abc', 'def', { role: [['abc', 'def']] })).toEqual(
true,
);

expect(findPermission('abc', 'def', { role: [['abc', 'de']] })).toEqual(
false,
);

expect(findPermission('abc', 'def', { role: [] })).toEqual(false);
});

it('findPermission for multiple roles', () => {
expect(
findPermission('abc', 'def', {
role1: [
['ccc', 'aaa'],
['abc', 'def'],
],
role2: [['abc', 'def']],
}),
).toEqual(true);

expect(
findPermission('abc', 'def', {
role1: [['abc', 'def']],
role2: [['abc', 'dd']],
}),
).toEqual(true);

expect(
findPermission('abc', 'def', {
role1: [['ccc', 'aaa']],
role2: [['aaa', 'ddd']],
}),
).toEqual(false);

expect(findPermission('abc', 'def', { role1: [], role2: [] })).toEqual(
false,
);
});

it('handles nonexistent roles', () => {
expect(findPermission('abc', 'def', null)).toEqual(false);
});
});

describe('canUserEditDashboard', () => {
const dashboard: Dashboard = {
id: 1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
import memoizeOne from 'memoize-one';
import {
UserRoles,
isUserWithPermissionsAndRoles,
UndefinedUser,
UserWithPermissionsAndRoles,
} from 'src/types/bootstrapTypes';
import Dashboard from 'src/types/Dashboard';

const findPermission = memoizeOne(
(perm: string, view: string, roles?: UserRoles | null) =>
!!roles &&
Object.values(roles).some(permissions =>
permissions.some(([perm_, view_]) => perm_ === perm && view_ === view),
),
);

export default findPermission;
import { findPermission } from 'src/utils/findPermission';

// this should really be a config value,
// but is hardcoded in backend logic already, so...
Expand Down
85 changes: 85 additions & 0 deletions superset-frontend/src/explore/actions/datasourcesActions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* 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 { DatasourceType } from '@superset-ui/core';
import {
setDatasource,
changeDatasource,
} from 'src/explore/actions/datasourcesActions';
import datasourcesReducer from '../reducers/datasourcesReducer';
import { updateFormDataByDatasource } from './exploreActions';

const CURRENT_DATASOURCE = {
id: 1,
uid: '1__table',
type: DatasourceType.Table,
columns: [],
metrics: [],
column_format: {},
verbose_map: {},
main_dttm_col: '__timestamp',
// eg. ['["ds", true]', 'ds [asc]']
datasource_name: 'test datasource',
description: null,
};

const NEW_DATASOURCE = {
id: 2,
type: DatasourceType.Table,
columns: [],
metrics: [],
column_format: {},
verbose_map: {},
main_dttm_col: '__timestamp',
// eg. ['["ds", true]', 'ds [asc]']
datasource_name: 'test datasource',
description: null,
};

const defaultDatasourcesReducerState = {
[CURRENT_DATASOURCE.uid]: CURRENT_DATASOURCE,
};

test('sets new datasource', () => {
const newState = datasourcesReducer(
defaultDatasourcesReducerState,
setDatasource(NEW_DATASOURCE),
);
expect(newState).toEqual({
...defaultDatasourcesReducerState,
'2__table': NEW_DATASOURCE,
});
});

test('change datasource action', () => {
const dispatch = jest.fn();
const getState = jest.fn(() => ({
explore: {
datasource: CURRENT_DATASOURCE,
},
}));
// ignore getState type check - we dont need explore.datasource field for this test
// @ts-ignore
changeDatasource(NEW_DATASOURCE)(dispatch, getState);
expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, setDatasource(NEW_DATASOURCE));
expect(dispatch).toHaveBeenNthCalledWith(
2,
updateFormDataByDatasource(CURRENT_DATASOURCE, NEW_DATASOURCE),
);
});
49 changes: 49 additions & 0 deletions superset-frontend/src/explore/actions/datasourcesActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* 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 { Dispatch } from 'redux';
import { Dataset } from '@superset-ui/chart-controls';
import { updateFormDataByDatasource } from './exploreActions';
import { ExplorePageState } from '../reducers/getInitialState';

export const SET_DATASOURCE = 'SET_DATASOURCE';
export interface SetDatasource {
type: string;
datasource: Dataset;
}
export function setDatasource(datasource: Dataset) {
return { type: SET_DATASOURCE, datasource };
}

export function changeDatasource(newDatasource: Dataset) {
return function (dispatch: Dispatch, getState: () => ExplorePageState) {
const {
explore: { datasource: prevDatasource },
} = getState();
dispatch(setDatasource(newDatasource));
dispatch(updateFormDataByDatasource(prevDatasource, newDatasource));
};
}

export const datasourcesActions = {
setDatasource,
changeDatasource,
};

export type AnyDatasourcesAction = SetDatasource;
Loading