-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add download csv button to people management
test: Add DownloadCsvButton unit test
- Loading branch information
1 parent
383989c
commit 2524094
Showing
6 changed files
with
297 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
import React, { useState, useEffect } from 'react'; | ||
import PropTypes from 'prop-types'; | ||
import { useIntl } from '@edx/frontend-platform/i18n'; | ||
|
||
import { | ||
Toast, StatefulButton, Icon, Spinner, useToggle, | ||
} from '@openedx/paragon'; | ||
import { Download, Check } from '@openedx/paragon/icons'; | ||
import { logError } from '@edx/frontend-platform/logging'; | ||
import { downloadCsv } from '../../utils'; | ||
|
||
const csvHeaders = ['Name', 'Email', 'Joined Organization', 'Enrollments']; | ||
|
||
const dataEntryToRow = (entry) => { | ||
const { enterpriseCustomerUser: { name, email, joinedOrg }, enrollments } = entry; | ||
return [name, email, joinedOrg, enrollments]; | ||
}; | ||
|
||
const getCsvFileName = () => { | ||
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}-people-report.csv`; | ||
}; | ||
|
||
const DownloadCsvButton = ({ testId, fetchData, totalCt }) => { | ||
const [buttonState, setButtonState] = useState('pageLoading'); | ||
const [isOpen, open, close] = useToggle(false); | ||
const intl = useIntl(); | ||
|
||
useEffect(() => { | ||
if (fetchData) { | ||
setButtonState('default'); | ||
} | ||
}, [fetchData]); | ||
|
||
const handleClick = async () => { | ||
setButtonState('pending'); | ||
fetchData().then((response) => { | ||
downloadCsv(getCsvFileName(), response.results, csvHeaders, dataEntryToRow); | ||
open(); | ||
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 ( | ||
<> | ||
{ isOpen | ||
&& ( | ||
<Toast onClose={close} show={isOpen}> | ||
{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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
99 changes: 99 additions & 0 deletions
99
src/components/PeopleManagement/tests/DownloadCsvButton.test.jsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
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(), | ||
})); | ||
|
||
jest.mock('@edx/frontend-platform/logging', () => ({ | ||
...jest.requireActual('@edx/frontend-platform/logging'), | ||
logError: jest.fn(), | ||
})); | ||
|
||
jest.useFakeTimers({ advanceTimers: true }).setSystemTime(new Date('2024-01-20')); | ||
|
||
const mockData = { | ||
results: [ | ||
{ | ||
enterprise_customer_user: { | ||
email: 'a@letter.com', | ||
joined_org: 'Apr 07, 2024', | ||
name: 'A', | ||
}, | ||
enrollments: 3, | ||
}, | ||
{ | ||
enterprise_customer_user: { | ||
email: 'b@letter.com', | ||
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 () => { | ||
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(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters