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

UISACQCOMP-166: view list of donors #724

Merged
merged 17 commits into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from 11 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

* Sort the list of countries based on the current locale. Refs UISACQCOMP-164.
* Add `inputType` prop to `<SingleSearchForm>`. Refs UISACQCOMP-165.
* View the list of donors. Refs UISACQCOMP-166.

## [5.0.0](https://github.com/folio-org/stripes-acq-components/tree/v5.0.0) (2023-10-12)
[Full Changelog](https://github.com/folio-org/stripes-acq-components/compare/v4.0.2...v5.0.0)
Expand Down
60 changes: 60 additions & 0 deletions lib/DonorsList/AddDonorButton.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { map } from 'lodash';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';

import { Pluggable } from '@folio/stripes/core';

import {
initialFilters,
modalLabel,
pluginVisibleColumns,
resultsPaneTitle,
searchableIndexes,
visibleFilters,
} from './constants';

const AddDonorButton = ({ fetchDonors, fields, stripes, name }) => {
const addDonors = (donors = []) => {
const addedDonorIds = new Set(fields.value);
const newDonorsIds = map(donors.filter(({ id }) => !addedDonorIds.has(id)), 'id');

if (newDonorsIds.length) {
fetchDonors([...addedDonorIds, ...newDonorsIds]);
Copy link
Contributor

Choose a reason for hiding this comment

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

the fetchDonors should be called smth like onAddDonor, btn doesn't fetch anything

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated

newDonorsIds.forEach(contactId => fields.push(contactId));
}
};

return (
<Pluggable
id={`${name}-plugin`}
aria-haspopup="true"
type="find-organization"
dataKey="organization"
searchLabel={<FormattedMessage id="stripes-acq-components.donors.button.addDonor" />}
searchButtonStyle="default"
disableRecordCreation
stripes={stripes}
selectVendor={addDonors}
modalLabel={modalLabel}
resultsPaneTitle={resultsPaneTitle}
visibleColumns={pluginVisibleColumns}
initialFilters={initialFilters}
searchableIndexes={searchableIndexes}
visibleFilters={visibleFilters}
isMultiSelect
>
<span data-test-add-donor>
<FormattedMessage id="stripes-acq-components.donors.noFindOrganizationPlugin" />
</span>
</Pluggable>
);
};

AddDonorButton.propTypes = {
fetchDonors: PropTypes.func.isRequired,
fields: PropTypes.object,
stripes: PropTypes.object,
name: PropTypes.string.isRequired,
};

export default AddDonorButton;
56 changes: 56 additions & 0 deletions lib/DonorsList/DonorsContainer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import React, { useCallback, useState } from 'react';
import PropTypes from 'prop-types';
import { FieldArray } from 'react-final-form-arrays';

import {
Col,
Loading,
Row,
} from '@folio/stripes/components';

import DonorsList from './DonorsList';
import { useFetchDonors } from './hooks';

function DonorsContainer({ name, donorOrganizationIds }) {
const [donorIds, setDonorIds] = useState(() => donorOrganizationIds);

Choose a reason for hiding this comment

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

Why is lazy initialization needed here?

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. We can remove it. Initial implementation I had a function to get the ids.

const { donors, isLoading } = useFetchDonors(donorIds);

const handleFetchDonors = useCallback(ids => {
setDonorIds(ids);
}, []);

const donorsMap = donors.reduce((acc, contact) => {
acc[contact.id] = contact;

return acc;
}, {});

if (isLoading) {
return <Loading />;
}

return (
<Row>
<Col xs={12}>
<FieldArray
name={name}
id={name}
component={DonorsList}
fetchDonors={handleFetchDonors}
Copy link
Contributor

Choose a reason for hiding this comment

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

should be called like setDonorIds and accept setDonorIds, because now the callback does not fetch anything

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated

donorsMap={donorsMap}
/>
</Col>
</Row>
);
}

DonorsContainer.propTypes = {
name: PropTypes.string.isRequired,
donorOrganizationIds: PropTypes.arrayOf(PropTypes.string),
};

DonorsContainer.defaultProps = {
donorOrganizationIds: [],
};

export default DonorsContainer;
89 changes: 89 additions & 0 deletions lib/DonorsList/DonorsContainer.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';

import stripesFinalForm from '@folio/stripes/final-form';

import DonorsContainer from './DonorsContainer';
import { useFetchDonors } from './hooks';

jest.mock('@folio/stripes/components', () => ({
...jest.requireActual('@folio/stripes/components'),
Loading: jest.fn(() => 'Loading'),
}));

jest.mock('./DonorsList', () => jest.fn(({ donorsMap }) => {
if (!Object.values(donorsMap).length) {
return 'stripes-components.tableEmpty';
}

return Object.values(donorsMap).map(({ name }) => <div key={name}>{name}</div>);
}));

jest.mock('./hooks', () => ({
useFetchDonors: jest.fn().mockReturnValue({
donors: [],
isLoading: false,
}),
}));

const defaultProps = {
name: 'donors',
donorOrganizationIds: [],
};

const renderForm = (props = {}) => (
<form>
<DonorsContainer
{...defaultProps}
{...props}
/>
<button type="submit">Submit</button>
</form>
);

const FormCmpt = stripesFinalForm({})(renderForm);

const renderComponent = (props = {}) => (render(
<MemoryRouter>
<FormCmpt onSubmit={() => { }} {...props} />
</MemoryRouter>,
));

describe('DonorsContainer', () => {
beforeEach(() => {
useFetchDonors.mockClear().mockReturnValue({
donors: [],
isLoading: false,
});
});

it('should render component', () => {
renderComponent();

expect(screen.getByText('stripes-components.tableEmpty')).toBeDefined();
});

it('should render Loading component', () => {
useFetchDonors.mockClear().mockReturnValue({
donors: [],
isLoading: true,
});

renderComponent();

expect(screen.getByText('Loading')).toBeDefined();
});

it('should call `useFetchDonors` with `donorOrganizationIds`', () => {
const mockData = [{ name: 'Amazon', code: 'AMAZ', id: '1' }];

useFetchDonors.mockClear().mockReturnValue({
donors: mockData,
isLoading: false,
});

renderComponent({ donorOrganizationIds: ['1'] });

expect(screen.getByText(mockData[0].name)).toBeDefined();
});
});
101 changes: 101 additions & 0 deletions lib/DonorsList/DonorsList.js
usavkov-epam marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import React, { useMemo } from 'react';
import { sortBy } from 'lodash';
import PropTypes from 'prop-types';
import { useIntl } from 'react-intl';

import {
Button,
Icon,
MultiColumnList,
TextLink,
} from '@folio/stripes/components';
import { useStripes } from '@folio/stripes/core';

import AddDonorButton from './AddDonorButton';
import {
alignRowProps,
columnMapping,
columnWidths,
visibleColumns,
} from './constants';

const getDonorUrl = (orgId) => {
if (orgId) {
return `/organizations/view/${orgId}`;
}

return undefined;
};

const getResultsFormatter = ({
canViewOrganizations,
fields,
intl,
}) => ({
name: donor => <TextLink to={getDonorUrl(canViewOrganizations && donor.id)}>{donor.name}</TextLink>,
code: donor => donor.code,
unassignDonor: donor => (
<Button
align="end"
aria-label={intl.formatMessage({ id: 'stripes-acq-components.donors.button.unassign' })}
buttonStyle="fieldControl"
type="button"
onClick={(e) => {
e.preventDefault();
fields.remove(donor._index);
}}
>
<Icon icon="times-circle" />
</Button>
),
});

const DonorsList = ({ fetchDonors, fields, donorsMap, id }) => {
const intl = useIntl();
const stripes = useStripes();
const canViewOrganizations = stripes.hasPerm('ui-organizations.view');
const donors = (fields.value || [])
.map((contactId, _index) => {
const contact = donorsMap?.[contactId];

return {
...(contact || { isDeleted: true }),
_index,
};
});
const contentData = useMemo(() => sortBy(donors, [({ lastName }) => lastName?.toLowerCase()]), [donors]);
usavkov-epam marked this conversation as resolved.
Show resolved Hide resolved

const resultsFormatter = useMemo(() => {
return getResultsFormatter({ intl, fields, canViewOrganizations });
}, [canViewOrganizations, fields, intl]);

return (
<>
<MultiColumnList
alisher-epam marked this conversation as resolved.
Show resolved Hide resolved
usavkov-epam marked this conversation as resolved.
Show resolved Hide resolved
id={id}
columnMapping={columnMapping}
contentData={contentData}
formatter={resultsFormatter}
rowProps={alignRowProps}
visibleColumns={visibleColumns}
columnWidths={columnWidths}
/>
<br />
<AddDonorButton
fetchDonors={fetchDonors}
fields={fields}
stripes={stripes}
name={id}
/>
</>
);
};

DonorsList.propTypes = {
fetchDonors: PropTypes.func.isRequired,
fields: PropTypes.object,
donorsMap: PropTypes.object,
id: PropTypes.string.isRequired,
};

export default DonorsList;
53 changes: 53 additions & 0 deletions lib/DonorsList/DonorsList.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';

import DonorsList from './DonorsList';

const mockFetchDonors = jest.fn();

const defaultProps = {
fetchDonors: mockFetchDonors,
fields: {},
donorsMap: {},
id: 'donors',
};

const wrapper = ({ children }) => (
<MemoryRouter>
{children}
</MemoryRouter>
);

const renderComponent = (props = {}) => (render(
<DonorsList
{...defaultProps}
{...props}
/>,
{ wrapper },
));

describe('DonorsList', () => {
it('should render component', () => {
renderComponent();

expect(screen.getByText('stripes-components.tableEmpty')).toBeDefined();
});

it('should render the list of donor organizations', () => {
renderComponent({
fields: {
value: [
'1',
'2',
],
},
donorsMap: {
1: { id: '1', name: 'Amazon' },
2: { id: '2', name: 'Google' },
},
});

expect(screen.getByText('Amazon')).toBeDefined();
expect(screen.getByText('Google')).toBeDefined();
});
});
Loading
Loading