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

feat: Add download csv button to people management #1369

Merged
merged 1 commit into from
Jan 3, 2025
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
105 changes: 105 additions & 0 deletions src/components/PeopleManagement/DownloadCSVButton.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { useIntl } from '@edx/frontend-platform/i18n';

import {
Icon, Spinner, StatefulButton, Toast, useToggle,
} from '@openedx/paragon';
import { Download, Check } from '@openedx/paragon/icons';
import { logError } from '@edx/frontend-platform/logging';
import { downloadCsv, getTimeStampedFilename } from '../../utils';

const csvHeaders = ['Name', 'Email', 'Joined Organization', 'Enrollments'];

const dataEntryToRow = (entry) => {
const { enterpriseCustomerUser: { name, email, joinedOrg }, enrollments } = entry;
return [name, email, joinedOrg, enrollments];

Check warning on line 16 in src/components/PeopleManagement/DownloadCSVButton.jsx

View check run for this annotation

Codecov / codecov/patch

src/components/PeopleManagement/DownloadCSVButton.jsx#L15-L16

Added lines #L15 - L16 were not covered by tests
};

const DownloadCsvButton = ({ testId, fetchData, totalCt }) => {
const [buttonState, setButtonState] = useState('pageLoading');
const [isToastOpen, openToast, closeToast] = useToggle(false);
const intl = useIntl();

useEffect(() => {
if (fetchData) {
setButtonState('default');
}
}, [fetchData]);

const handleClick = async () => {
setButtonState('pending');
fetchData().then((response) => {
const fileName = getTimeStampedFilename('people-report.csv');
downloadCsv(fileName, response.results, csvHeaders, dataEntryToRow);
openToast();
setButtonState('complete');
}).catch((err) => {
logError(err);
});
};

const toastText = intl.formatMessage({
id: 'adminPortal.peopleManagement.dataTable.download.toast',
defaultMessage: 'Successfully downloaded',
description: 'Toast message for the people management download button.',
});
return (
<>
{ isToastOpen
&& (
<Toast onClose={closeToast} show={isToastOpen}>
{toastText}
</Toast>
)}
<StatefulButton
state={buttonState}
className="download-button"
data-testid={testId}
labels={{
default: intl.formatMessage({
id: 'adminPortal.peopleManagement.dataTable.download.button',
defaultMessage: `Download all (${totalCt})`,
description: 'Label for the people management download button',
}),
pending: intl.formatMessage({
id: 'adminPortal.peopleManagement.dataTable.download.button.pending',
defaultMessage: 'Downloading',
description: 'Label for the people management download button when the download is in progress.',
}),
complete: intl.formatMessage({
id: 'adminPortal.peopleManagement.dataTable.download.button.complete',
defaultMessage: 'Downloaded',
description: 'Label for the people management download button when the download is complete.',
}),
pageLoading: intl.formatMessage({
id: 'adminPortal.peopleManagement.dataTable.download.button.loading',
defaultMessage: 'Download module activity',
description: 'Label for the people management download button when the page is loading.',
}),
}}
icons={{
default: <Icon src={Download} />,
pending: <Spinner animation="border" variant="light" size="sm" />,
complete: <Icon src={Check} />,
pageLoading: <Icon src={Download} variant="light" />,
}}
disabledStates={['pending', 'pageLoading']}
onClick={handleClick}
/>
</>
);
};

DownloadCsvButton.defaultProps = {
testId: 'download-csv-button',
};

DownloadCsvButton.propTypes = {
// eslint-disable-next-line react/forbid-prop-types
fetchData: PropTypes.func.isRequired,
totalCt: PropTypes.number,
testId: PropTypes.string,
};

export default DownloadCsvButton;
10 changes: 9 additions & 1 deletion src/components/PeopleManagement/PeopleManagementTable.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import TableTextFilter from '../learner-credit-management/TableTextFilter';
import CustomDataTableEmptyState from '../learner-credit-management/CustomDataTableEmptyState';
import OrgMemberCard from './OrgMemberCard';
import useEnterpriseMembersTableData from './data/hooks/useEnterpriseMembersTableData';
import DownloadCsvButton from './DownloadCSVButton';

const FilterStatus = (rest) => <DataTable.FilterStatus showFilteredFields={false} {...rest} />;

Expand All @@ -15,10 +16,10 @@ const PeopleManagementTable = ({ enterpriseId }) => {
isLoading: isTableLoading,
enterpriseMembersTableData,
fetchEnterpriseMembersTableData,
fetchAllEnterpriseMembersData,
} = useEnterpriseMembersTableData({ enterpriseId });

const tableColumns = [{ Header: 'Name', accessor: 'name' }];

return (
<DataTable
isSortable
Expand All @@ -45,6 +46,13 @@ const PeopleManagementTable = ({ enterpriseId }) => {
itemCount={enterpriseMembersTableData.itemCount}
pageCount={enterpriseMembersTableData.pageCount}
EmptyTableComponent={CustomDataTableEmptyState}
tableActions={[
<DownloadCsvButton
fetchData={fetchAllEnterpriseMembersData}
totalCt={enterpriseMembersTableData.itemCount}
testId="people-report-download"
/>,
]}
>
<DataTable.TableControlBar />
<CardView
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@
pageCount: 0,
results: [],
});

const fetchAllEnterpriseMembersData = useCallback(async () => {
const { options, itemCount } = enterpriseMembersTableData;

Check warning on line 19 in src/components/PeopleManagement/data/hooks/useEnterpriseMembersTableData.js

View check run for this annotation

Codecov / codecov/patch

src/components/PeopleManagement/data/hooks/useEnterpriseMembersTableData.js#L19

Added line #L19 was not covered by tests
// Take the existing filters but specify we're taking all results on one page
const fetchAllOptions = { ...options, page: 1, page_size: itemCount };
const response = await LmsApiService.fetchEnterpriseCustomerMembers(enterpriseId, fetchAllOptions);
return camelCaseObject(response.data);

Check warning on line 23 in src/components/PeopleManagement/data/hooks/useEnterpriseMembersTableData.js

View check run for this annotation

Codecov / codecov/patch

src/components/PeopleManagement/data/hooks/useEnterpriseMembersTableData.js#L21-L23

Added lines #L21 - L23 were not covered by tests
}, [enterpriseId, enterpriseMembersTableData]);

const fetchEnterpriseMembersData = useCallback((args) => {
const fetch = async () => {
try {
Expand All @@ -33,6 +42,7 @@
itemCount: data.count,
pageCount: data.numPages ?? Math.floor(data.count / options.pageSize),
results: data.results,
options,
});
} catch (error) {
logError(error);
Expand All @@ -56,6 +66,7 @@
isLoading,
enterpriseMembersTableData,
fetchEnterpriseMembersTableData: debouncedFetchEnterpriseMembersData,
fetchAllEnterpriseMembersData,
};
};

Expand Down
98 changes: 98 additions & 0 deletions src/components/PeopleManagement/tests/DownloadCsvButton.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import React from 'react';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { logError } from '@edx/frontend-platform/logging';
import { act, render, screen } from '@testing-library/react';

import '@testing-library/jest-dom/extend-expect';

import userEvent from '@testing-library/user-event';
import DownloadCsvButton from '../DownloadCSVButton';
import { downloadCsv } from '../../../utils';

jest.mock('file-saver', () => ({
...jest.requireActual('file-saver'),
saveAs: jest.fn(),
}));

jest.mock('../../../utils', () => ({
downloadCsv: jest.fn(),
getTimeStampedFilename: (suffix) => `2024-01-20-${suffix}`,
}));

jest.mock('@edx/frontend-platform/logging', () => ({
...jest.requireActual('@edx/frontend-platform/logging'),
logError: jest.fn(),
}));

const mockData = {
results: [
{
enterprise_customer_user: {
email: '[email protected]',
joined_org: 'Apr 07, 2024',
name: 'A',
},
enrollments: 3,
},
{
enterprise_customer_user: {
email: '[email protected]',
joined_org: 'Apr 08, 2024',
name: 'B',
},
enrollments: 4,
},
],
};

const testId = 'test-id-1';
const DEFAULT_PROPS = {
totalCt: mockData.results.length,
fetchData: jest.fn(() => Promise.resolve(mockData)),
testId,
};

const DownloadCSVButtonWrapper = props => (
<IntlProvider locale="en">
<DownloadCsvButton {...props} />
</IntlProvider>
);

describe('DownloadCSVButton', () => {
const flushPromises = () => new Promise(setImmediate);

it('renders download csv button correctly.', async () => {
render(<DownloadCSVButtonWrapper {...DEFAULT_PROPS} />);
expect(screen.getByTestId(testId)).toBeInTheDocument();

// Validate button text
expect(screen.getByText('Download all (2)')).toBeInTheDocument();

// Click the download button.
screen.getByTestId(testId).click();
await flushPromises();

expect(DEFAULT_PROPS.fetchData).toHaveBeenCalled();
const expectedFileName = '2024-01-20-people-report.csv';
const expectedHeaders = ['Name', 'Email', 'Joined Organization', 'Enrollments'];
expect(downloadCsv).toHaveBeenCalledWith(expectedFileName, mockData.results, expectedHeaders, expect.any(Function));
});
it('download button should handle error returned by the API endpoint.', async () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add in a test for filtered results?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point! The DownloadCsvButton component doesn't have awareness of filters, and this would have to be tested at the level of the PeopleManagementPage. As of right now there are no unit tests for the table part of the PeopleManagementPage, and adding that I feel is a substantial enough task outside the scope of this change to address it as a separate ticket.

const props = {
...DEFAULT_PROPS,
fetchData: jest.fn(() => Promise.reject(new Error('Error fetching data'))),
};
render(<DownloadCSVButtonWrapper {...props} />);
expect(screen.getByTestId(testId)).toBeInTheDocument();

act(() => {
// Click the download button.
userEvent.click(screen.getByTestId(testId));
});

await flushPromises();

expect(DEFAULT_PROPS.fetchData).toHaveBeenCalled();
expect(logError).toHaveBeenCalled();
});
});
45 changes: 45 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import dayjs from 'dayjs';
import { saveAs } from 'file-saver';
import camelCase from 'lodash/camelCase';
import snakeCase from 'lodash/snakeCase';
import isArray from 'lodash/isArray';
Expand Down Expand Up @@ -609,6 +610,48 @@ function isTodayBetweenDates({ startDate, endDate }) {
*/
const isFalsy = (value) => value == null || value === '';

/**
* Generate filename with current timestamp prepended to given suffix
*
* @param {string} suffix
* @returns {string}
*/
function getTimeStampedFilename(suffix) {
const padTwoZeros = (num) => num.toString().padStart(2, '0');
const currentDate = new Date();
const year = currentDate.getUTCFullYear();
const month = padTwoZeros(currentDate.getUTCMonth() + 1);
const day = padTwoZeros(currentDate.getUTCDate());
return `${year}-${month}-${day}-${suffix}`;
}

/**
* Transform data to csv format and save to file
*
* @param {string} fileName
* Name of the file to save to
* @param {Array<object>} data
* Data to transform to csv format
* @param {Array<string>} headers
* Text headers for the file
* @param {(object) => Array<string|number>} dataEntryToRow
* Transform function, taking a single data entry and converting it to array of string or numeric values
* that will represent a row of data in the csv document
* Note: Enclosing quotes will be added to any string fields containing commas
*/
function downloadCsv(fileName, data, headers, dataEntryToRow) {
// If a cell in a csv document contains commas, we need to enclose cell in quotes
const escapeCommas = (cell) => (isString(cell) && cell.includes(',') ? `"${cell}"` : cell);
const generateCsvRow = (entry) => dataEntryToRow(entry).map(escapeCommas);

const body = data.map(generateCsvRow).join('\n');
const csvText = `${headers}\n${body}`;
const blob = new Blob([csvText], {
type: 'text/csv',
});
saveAs(blob, fileName);
}

export {
camelCaseDict,
camelCaseDictArray,
Expand Down Expand Up @@ -656,4 +699,6 @@ export {
isTodayWithinDateThreshold,
isTodayBetweenDates,
isFalsy,
getTimeStampedFilename,
downloadCsv,
};
Loading
Loading