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

JN-479: adding download of mailing list #492

Merged
merged 4 commits into from
Aug 4, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
73 changes: 17 additions & 56 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"e2e-tests"
],
"devDependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.58",
Expand Down
6 changes: 3 additions & 3 deletions ui-admin/src/components/forms/InfoPopup.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { render, screen, waitForElementToBeRemoved } from '@testing-library/react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import React from 'react'

Expand All @@ -18,7 +18,7 @@ describe('InfoPopup', () => {
expect(await screen.findByText('blah blah')).toBeTruthy()
await userEvent.click(button)
// tooltip disappears on second click
await waitForElementToBeRemoved(() => screen.queryByText('blah blah'))
expect(screen.queryByText('blah blah')).toBeNull()
})

it('disappears on clicks outside', async () => {
Expand All @@ -33,6 +33,6 @@ describe('InfoPopup', () => {

// tooltip disappears on click of outside thing
await userEvent.click(screen.getByText('Something complicated'))
await waitForElementToBeRemoved(() => screen.queryByText('blah blah'))
expect(screen.queryByText('blah blah')).toBeNull()
})
})
54 changes: 54 additions & 0 deletions ui-admin/src/portal/MailingListView.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import React from 'react'
import { render, screen, waitFor } from '@testing-library/react'

import { MailingListContact } from 'api/api'
import { mockPortalContext } from 'test-utils/mocking-utils'
import { setupRouterTest } from 'test-utils/router-testing-utils'
import userEvent from '@testing-library/user-event'
import MailingListView from './MailingListView'

jest.mock('api/api', () => ({
fetchMailingList: () => {
const contacts: MailingListContact[] = [{
name: 'person1',
email: '[email protected]',
createdAt: 0
}, {
name: 'person2',
email: '[email protected]',
createdAt: 0
}]
return Promise.resolve(contacts)
}
}))

test('renders a mailing list', async () => {
const portalContext = mockPortalContext()
const portalEnv = portalContext.portal.portalEnvironments[0]
const { RoutedComponent } =
setupRouterTest(<MailingListView portalContext={portalContext} portalEnv={portalEnv}/>)
render(RoutedComponent)
await waitFor(() => {
expect(screen.getByText('person1')).toBeInTheDocument()
})
expect(screen.getByText('[email protected]')).toBeInTheDocument()
expect(screen.getByText('person2')).toBeInTheDocument()
})

test('download is toggled depending on contacts selected', async () => {
const portalContext = mockPortalContext()
const portalEnv = portalContext.portal.portalEnvironments[0]
const { RoutedComponent } =
setupRouterTest(<MailingListView portalContext={portalContext} portalEnv={portalEnv}/>)
render(RoutedComponent)
await waitFor(() => {
expect(screen.getByText('person1')).toBeInTheDocument()
})
const downloadLink = screen.getByText('Download')
expect(downloadLink).toHaveAttribute('aria-disabled', 'true')

// click on the 'select all' checkbox
await userEvent.click(screen.getAllByRole('checkbox')[0])
expect(screen.getByText('2 of 2 selected')).toBeInTheDocument()
expect(downloadLink).toHaveAttribute('aria-disabled', 'false')
})
39 changes: 34 additions & 5 deletions ui-admin/src/portal/MailingListView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import {
SortingState,
useReactTable
} from '@tanstack/react-table'
import { basicTableLayout, IndeterminateCheckbox } from '../util/tableUtils'
import { instantToDefaultString } from '../util/timeUtils'
import { basicTableLayout, IndeterminateCheckbox } from 'util/tableUtils'
import { currentIsoDate, instantToDateString, instantToDefaultString } from 'util/timeUtils'
import { Button } from 'components/forms/Button'
import { escapeCsvValue, saveBlobAsDownload } from 'util/downloadUtils'

const columns: ColumnDef<MailingListContact>[] = [{
id: 'select',
Expand Down Expand Up @@ -59,6 +61,24 @@ export default function MailingListView({ portalContext, portalEnv }:
debugTable: true
})

/** download selected contacts as a csv */
const download = () => {
const contactsSelected = Object.keys(rowSelection)
.filter(key => rowSelection[key])
.map(key => contacts[parseInt(key)])
const csvDataString = contactsSelected.map(contact => {
return `${escapeCsvValue(contact.email)}, ${escapeCsvValue(contact.name)},
${instantToDateString(contact.createdAt)}`
}).join('\n')
const csvString = `email, name, date joined\n${ csvDataString}`
const blob = new Blob([csvString], {
type: 'text/plain'
})
saveBlobAsDownload(blob, `${portalContext.portal.shortcode}-MailingList-${currentIsoDate()}.csv`)
}
const numSelected = Object.keys(rowSelection).length


useEffect(() => {
Api.fetchMailingList(portalContext.portal.shortcode, portalEnv.environmentName).then(result => {
setContacts(result)
Expand All @@ -71,10 +91,19 @@ export default function MailingListView({ portalContext, portalEnv }:
return <div className="container p-3">
<h1 className="h4">Mailing list </h1>
<LoadingSpinner isLoading={isLoading}>
<div>
{Object.keys(rowSelection).length} of{' '}
{table.getPreFilteredRowModel().rows.length} selected
<div className="d-flex align-items-center">
<div>
{numSelected} of {table.getPreFilteredRowModel().rows.length} selected
</div>
<div>
<Button onClick={download}
variant="link" disabled={!numSelected}
tooltip={numSelected ? 'Download selected contacts' : 'you must select contacts to download'}>
Download
</Button>
</div>
</div>

{basicTableLayout(table)}
</LoadingSpinner>
</div>
Expand Down
7 changes: 2 additions & 5 deletions ui-admin/src/study/participants/export/ExportDataControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { currentIsoDate } from 'util/timeUtils'
import { failureNotification } from 'util/notifications'
import { Store } from 'react-notifications-component'
import { Link } from 'react-router-dom'
import { saveBlobAsDownload } from '../../../util/downloadUtils'

const FILE_FORMATS = [{
label: 'Tab-delimted (.tsv)',
Expand Down Expand Up @@ -43,11 +44,7 @@ const ExportDataControl = ({ studyEnvContext, show, setShow }: {studyEnvContext:
return
}
const blob = await response.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = fileName
a.click()
saveBlobAsDownload(blob, fileName)
setIsLoading(false)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import AdHocEmailModal from '../AdHocEmailModal'
import EnrolleeSearchFacets, {} from './facets/EnrolleeSearchFacets'
import { facetValuesFromString, facetValuesToString, SAMPLE_FACETS, FacetValue }
from 'api/enrolleeSearch'
import { Button } from 'components/forms/Button'

/** Shows a list of (for now) enrollees */
function ParticipantList({ studyEnvContext }: {studyEnvContext: StudyEnvContextT}) {
Expand Down Expand Up @@ -185,11 +186,11 @@ function ParticipantList({ studyEnvContext }: {studyEnvContext: StudyEnvContextT
{table.getPreFilteredRowModel().rows.length} selected ({table.getFilteredRowModel().rows.length} shown)
</span>
<span className="me-2">
<button onClick={() => setShowEmailModal(allowSendEmail)}
aria-disabled={!allowSendEmail} className="btn btn-secondary"
title={allowSendEmail ? 'Send email' : 'Select at least one participant'}>
<Button onClick={() => setShowEmailModal(allowSendEmail)}
variant="link" disabled={!allowSendEmail}
tooltip={allowSendEmail ? 'Send email' : 'Select at least one participant'}>
Send email
</button>
</Button>
</span>
{ showEmailModal && <AdHocEmailModal enrolleeShortcodes={enrolleesSelected}
studyEnvContext={studyEnvContext}
Expand Down
15 changes: 15 additions & 0 deletions ui-admin/src/util/downloadUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { escapeCsvValue } from './downloadUtils'

describe('downloadUtils escapeCsvValue', () => {
it('handles boring strings', () => {
expect(escapeCsvValue('foobar')).toEqual('foobar')
expect(escapeCsvValue('foobar')).toEqual('foobar')
expect(escapeCsvValue(' space test ')).toEqual(' space test ')
})

it('quotes strings with special characters', () => {
expect(escapeCsvValue('line1\nline2')).toEqual('"line1\nline2"')
expect(escapeCsvValue('1,2')).toEqual('"1,2"')
expect(escapeCsvValue('foo "quote" bar')).toEqual('"foo ""quote"" bar"')
})
})
17 changes: 17 additions & 0 deletions ui-admin/src/util/downloadUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/** escapes double quotes with an extra ", and adds double quotes around any values that contain commas or newlines */
export const escapeCsvValue = (value: string) => {
value = value.replaceAll('"', '""')
if (value && (value.includes(',') || value.includes('\n') || value.includes('"'))) {
return `"${value}"`
}
return value
}

/** takes a blob and saves it to the users computer as a download */
export const saveBlobAsDownload = (blob: Blob, fileName: string) => {
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = fileName
a.click()
}
Loading