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

Preset io ch28954 refactor reports #19129

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
615dffd
pexdax refactor (#16333)
AAfghahi Aug 18, 2021
6d78318
refactor progress (#16339)
lyndsiWilliams Aug 19, 2021
6d89d8c
fix: Header Actions test refactor (#16336)
AAfghahi Aug 19, 2021
5a35f4c
code dry (#16358)
AAfghahi Aug 20, 2021
d25c841
Fetch bug fixed (#16376)
lyndsiWilliams Aug 20, 2021
80c936e
continued refactoring (#16377)
AAfghahi Aug 20, 2021
18a04cd
pexdax refactor (#16333)
AAfghahi Aug 18, 2021
3fb8eec
refactor progress (#16339)
lyndsiWilliams Aug 19, 2021
3c8fda4
fix: Header Actions test refactor (#16336)
AAfghahi Aug 19, 2021
39f6f8a
code dry (#16358)
AAfghahi Aug 20, 2021
9ee469d
Fetch bug fixed (#16376)
lyndsiWilliams Aug 20, 2021
4387935
continued refactoring (#16377)
AAfghahi Aug 20, 2021
82004da
refactor: Arash/new state report (#16987)
AAfghahi Oct 28, 2021
d8f4733
refactor: Reports code clean 10-29 (#17424)
lyndsiWilliams Nov 19, 2021
a17d5ca
fix(Explore): Remove changes to the properties on cancel (#17184)
geido Nov 2, 2021
98bb7f9
fix(dashboard): don't show report modal for anonymous user (#17106)
mayurnewase Nov 11, 2021
2908169
fix(explore): Metric control breaks when saved metric deleted from da…
kgabryje Nov 24, 2021
20e54c0
Add functionality is now working (#17578)
lyndsiWilliams Dec 7, 2021
fd66de2
refactoring reports
AAfghahi Jan 21, 2022
e0b9268
ready for review
AAfghahi Jan 24, 2022
9abc803
added testing
AAfghahi Feb 9, 2022
af5d00d
removed user reducer
AAfghahi Feb 10, 2022
1e8b10f
elizabeth suggestions
AAfghahi Feb 18, 2022
66f328f
merge conflicts
AAfghahi Mar 11, 2022
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
@@ -0,0 +1,167 @@
/**
* 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 * as React from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen, act } from 'spec/helpers/testing-library';
import * as featureFlags from 'src/featureFlags';
import { FeatureFlag } from '@superset-ui/core';
import HeaderReportDropdown, { HeaderReportProps } from '.';

let isFeatureEnabledMock: jest.MockInstance<boolean, [string]>;

const createProps = () => ({
toggleActive: jest.fn(),
deleteActiveReport: jest.fn(),
dashboardId: 1,
});

const stateWithOnlyUser = {
explore: {
user: {
email: 'admin@test.com',
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: 'admin@test.com',
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: {
1: {
id: 1,
result: {
active: true,
creation_method: 'dashboards',
crontab: '0 12 * * 1',
dashboard: 1,
name: 'Weekly Report',
owners: [1],
recipients: [
{
recipient_config_json: {
target: 'admin@test.com',
},
type: 'Email',
},
],
type: 'Report',
},
},
},
},
};

function setup(props: HeaderReportProps, initialState = {}) {
render(
<div>
<HeaderReportDropdown {...props} />
</div>,
{ useRedux: true, initialState },
);
}

describe('Header Report Dropdown', () => {
beforeAll(() => {
isFeatureEnabledMock = jest
.spyOn(featureFlags, 'isFeatureEnabled')
.mockImplementation(
(featureFlag: FeatureFlag) => featureFlag === FeatureFlag.ALERT_REPORTS,
);
});

afterAll(() => {
// @ts-ignore
isFeatureEnabledMock.restore();
});

it('renders correctly', () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithUserAndReport);
});
expect(screen.getByRole('button')).toBeInTheDocument();
});

it('renders the dropdown correctly', () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithUserAndReport);
});
const emailReportModalButton = screen.getByRole('button');
userEvent.click(emailReportModalButton);
expect(screen.getByText('Email reports active')).toBeInTheDocument();
expect(screen.getByText('Edit email report')).toBeInTheDocument();
expect(screen.getByText('Delete email report')).toBeInTheDocument();
});

it('opens an edit modal', () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithUserAndReport);
});
const emailReportModalButton = screen.getByRole('button');
userEvent.click(emailReportModalButton);
const editModal = screen.getByText('Edit email report');
userEvent.click(editModal);
expect(screen.getByText('Edit Email Report')).toBeInTheDocument();
});

it('opens a delete modal', () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithUserAndReport);
});
const emailReportModalButton = screen.getByRole('button');
userEvent.click(emailReportModalButton);
const deleteModal = screen.getByText('Delete email report');
userEvent.click(deleteModal);
expect(screen.getByText('Delete Report?')).toBeInTheDocument();
});

it('renders a new report modal if there is no report', () => {
const mockedProps = createProps();
act(() => {
setup(mockedProps, stateWithOnlyUser);
});
const emailReportModalButton = screen.getByRole('button');
userEvent.click(emailReportModalButton);
expect(screen.getByText('New Email Report')).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/**
* 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 React, { useState, useEffect } from 'react';
import { usePrevious } from 'src/hooks/usePrevious';
import { useSelector, useDispatch } from 'react-redux';
import { t, SupersetTheme, css, useTheme } from '@superset-ui/core';
import Icons from 'src/components/Icons';
import { Switch } from 'src/components/Switch';
import { AlertObject } from 'src/views/CRUD/alert/types';
import { Menu, NoAnimationDropdown } from 'src/common/components';
import { isFeatureEnabled, FeatureFlag } from 'src/featureFlags';
import DeleteModal from 'src/components/DeleteModal';
import ReportModal from 'src/components/ReportModal';
import { ChartState } from 'src/explore/types';
import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes';
import { fetchUISpecificReport } from 'src/reports/actions/reports';
import { reportSelector } from 'src/views/CRUD/hooks';
import { ReportType } from 'src/dashboard/util/constants';

const deleteColor = (theme: SupersetTheme) => css`
color: ${theme.colors.error.base};
`;

export interface HeaderReportProps {
toggleActive: (data: AlertObject, isActive: boolean) => void;
deleteActiveReport: (data: AlertObject) => void;
dashboardId?: number;
chart?: ChartState;
}

export default function HeaderReportDropDown({
toggleActive,
deleteActiveReport,
dashboardId,
chart,
}: HeaderReportProps) {
const dispatch = useDispatch();

const report = useSelector<any, AlertObject>(state => {
const resourceType = dashboardId
? ReportType.DASHBOARDS
: ReportType.CHARTS;
return reportSelector(state, resourceType, dashboardId || chart?.id);
});
const user: UserWithPermissionsAndRoles = useSelector<
any,
UserWithPermissionsAndRoles
>(state => state.user || state.explore?.user);
const [currentReportDeleting, setCurrentReportDeleting] =
useState<AlertObject | null>(null);
const theme = useTheme();
const prevDashboard = usePrevious(dashboardId);
const [showModal, setShowModal] = useState<boolean>(false);
const toggleActiveKey = async (data: AlertObject, checked: boolean) => {
if (data?.id) {
toggleActive(data, checked);
}
};

const handleReportDelete = (report: AlertObject) => {
deleteActiveReport(report);
setCurrentReportDeleting(null);
};

const canAddReports = () => {
if (!isFeatureEnabled(FeatureFlag.ALERT_REPORTS)) {
return false;
}

if (!user?.userId) {
// this is in the case that there is an anonymous user.
return false;
}
const roles = Object.keys(user.roles || []);
const permissions = roles.map(key =>
user.roles[key].filter(
perms => perms[0] === 'menu_access' && perms[1] === 'Manage',
),
);
return permissions[0].length > 0;
};
const shouldFetch =
canAddReports() &&
!!((dashboardId && prevDashboard !== dashboardId) || chart?.id);

useEffect(() => {
if (shouldFetch) {
dispatch(
fetchUISpecificReport({
userId: user.userId,
filterField: dashboardId ? 'dashboard_id' : 'chart_id',
creationMethod: dashboardId ? 'dashboards' : 'charts',
resourceId: dashboardId || chart?.id,
}),
);
}
}, []);

const menu = () => (
<Menu selectable={false} css={{ width: '200px' }}>
<Menu.Item>
{t('Email reports active')}
<Switch
data-test="toggle-active"
checked={report?.active}
onClick={(checked: boolean) => toggleActiveKey(report, checked)}
size="small"
css={{ marginLeft: theme.gridUnit * 2 }}
/>
</Menu.Item>
<Menu.Item onClick={() => setShowModal(true)}>
{t('Edit email report')}
</Menu.Item>
<Menu.Item
onClick={() => setCurrentReportDeleting(report)}
css={deleteColor}
>
{t('Delete email report')}
</Menu.Item>
</Menu>
);
return (
<>
{canAddReports() && (
<>
<ReportModal
userId={user.userId}
showModal={showModal}
onHide={() => setShowModal(false)}
userEmail={user.email}
dashboardId={dashboardId}
chart={chart}
/>
{report ? (
<>
<NoAnimationDropdown
overlay={menu()}
trigger={['click']}
getPopupContainer={(triggerNode: any) =>
triggerNode.closest('.action-button')
}
>
<span role="button" className="action-button" tabIndex={0}>
<Icons.Calendar />
</span>
</NoAnimationDropdown>
{currentReportDeleting && (
<DeleteModal
description={t(
'This action will permanently delete %s.',
currentReportDeleting.name,
)}
onConfirm={() => {
if (currentReportDeleting) {
handleReportDelete(currentReportDeleting);
}
}}
onHide={() => setCurrentReportDeleting(null)}
open
title={t('Delete Report?')}
/>
)}
</>
) : (
<span
role="button"
title={t('Schedule email report')}
tabIndex={0}
className="action-button"
onClick={() => setShowModal(true)}
>
<Icons.Calendar />
</span>
)}
</>
)}
</>
);
}
Loading