Added logic to detect duplicated servers when importing a servers list

This commit is contained in:
Alejandro Celaya 2022-01-01 12:20:09 +01:00
parent 3cb066f5f5
commit 98398a048b
10 changed files with 128 additions and 73 deletions

View file

@ -8,7 +8,7 @@ import { StateFlagTimeout, useToggle } from '../utils/helpers/hooks';
import { ServerForm } from './helpers/ServerForm'; import { ServerForm } from './helpers/ServerForm';
import { ImportServersBtnProps } from './helpers/ImportServersBtn'; import { ImportServersBtnProps } from './helpers/ImportServersBtn';
import { ServerData, ServersMap, ServerWithId } from './data'; import { ServerData, ServersMap, ServerWithId } from './data';
import { DuplicatedServerModal } from './helpers/DuplicatedServerModal'; import { DuplicatedServersModal } from './helpers/DuplicatedServersModal';
const SHOW_IMPORT_MSG_TIME = 4000; const SHOW_IMPORT_MSG_TIME = 4000;
@ -65,10 +65,9 @@ const CreateServer = (ImportServersBtn: FC<ImportServersBtnProps>, useStateFlagT
{serversImported && <ImportResult type="success" />} {serversImported && <ImportResult type="success" />}
{errorImporting && <ImportResult type="error" />} {errorImporting && <ImportResult type="error" />}
<DuplicatedServerModal <DuplicatedServersModal
isOpen={isConfirmModalOpen} isOpen={isConfirmModalOpen}
toggle={toggleConfirmModal} duplicatedServers={serverData ? [ serverData ] : []}
serverData={serverData}
onDiscard={goBack} onDiscard={goBack}
onSave={save} onSave={save}
/> />

View file

@ -1,31 +0,0 @@
import { FC } from 'react';
import { Button, Modal, ModalBody, ModalFooter, ModalHeader } from 'reactstrap';
import { ServerData } from '../data';
interface DuplicatedServerModalProps {
serverData?: ServerData;
isOpen: boolean;
toggle: () => void;
onDiscard: () => void;
onSave: () => void;
}
export const DuplicatedServerModal: FC<DuplicatedServerModalProps> = (
{ isOpen, toggle, serverData, onDiscard, onSave },
) => (
<Modal centered isOpen={isOpen} toggle={toggle}>
<ModalHeader>Duplicated server</ModalHeader>
<ModalBody>
<p>There is already a server with:</p>
<ul>
<li>URL: <b>{serverData?.url}</b></li>
<li>API key: <b>{serverData?.apiKey}</b></li>
</ul>
Do you want to save this server anyway?
</ModalBody>
<ModalFooter>
<Button color="link" onClick={onDiscard}>Discard</Button>
<Button color="primary" onClick={onSave}>Save anyway</Button>
</ModalFooter>
</Modal>
);

View file

@ -0,0 +1,38 @@
import { FC, Fragment } from 'react';
import { Button, Modal, ModalBody, ModalFooter, ModalHeader } from 'reactstrap';
import { ServerData } from '../data';
interface DuplicatedServersModalProps {
duplicatedServers: ServerData[];
isOpen: boolean;
onDiscard: () => void;
onSave: () => void;
}
export const DuplicatedServersModal: FC<DuplicatedServersModalProps> = (
{ isOpen, duplicatedServers, onDiscard, onSave },
) => {
const hasMultipleServers = duplicatedServers.length > 1;
return (
<Modal centered isOpen={isOpen}>
<ModalHeader>Duplicated server{hasMultipleServers && 's'}</ModalHeader>
<ModalBody>
<p>{hasMultipleServers ? 'The next servers already exist:' : 'There is already a server with:'}</p>
<ul>
{duplicatedServers.map(({ url, apiKey }, index) => !hasMultipleServers ? (
<Fragment key={index}>
<li>URL: <b>{url}</b></li>
<li>API key: <b>{apiKey}</b></li>
</Fragment>
) : <li key={index}><b>{url}</b> - <b>{apiKey}</b></li>)}
</ul>
{hasMultipleServers ? 'Do you want to ignore duplicated servers?' : 'Do you want to save this server anyway?'}
</ModalBody>
<ModalFooter>
<Button color="link" onClick={onDiscard}>{hasMultipleServers ? 'Ignore duplicated' : 'Discard'}</Button>
<Button color="primary" onClick={onSave}>Save anyway</Button>
</ModalFooter>
</Modal>
);
};

View file

@ -1,10 +1,12 @@
import { useRef, RefObject, ChangeEvent, MutableRefObject, FC } from 'react'; import { useRef, RefObject, ChangeEvent, MutableRefObject, FC, useState, useEffect } from 'react';
import { Button, UncontrolledTooltip } from 'reactstrap'; import { Button, UncontrolledTooltip } from 'reactstrap';
import { pipe } from 'ramda'; import { complement, pipe } from 'ramda';
import { faFileUpload as importIcon } from '@fortawesome/free-solid-svg-icons'; import { faFileUpload as importIcon } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import ServersImporter from '../services/ServersImporter'; import { useToggle } from '../../utils/helpers/hooks';
import { ServerData } from '../data'; import { ServersImporter } from '../services/ServersImporter';
import { ServerData, ServersMap } from '../data';
import { DuplicatedServersModal } from './DuplicatedServersModal';
import './ImportServersBtn.scss'; import './ImportServersBtn.scss';
type Ref<T> = RefObject<T> | MutableRefObject<T>; type Ref<T> = RefObject<T> | MutableRefObject<T>;
@ -18,11 +20,16 @@ export interface ImportServersBtnProps {
interface ImportServersBtnConnectProps extends ImportServersBtnProps { interface ImportServersBtnConnectProps extends ImportServersBtnProps {
createServers: (servers: ServerData[]) => void; createServers: (servers: ServerData[]) => void;
servers: ServersMap;
fileRef: Ref<HTMLInputElement>; fileRef: Ref<HTMLInputElement>;
} }
const serversFiltering = (servers: ServerData[]) =>
({ url, apiKey }: ServerData) => servers.some((server) => server.url === url && server.apiKey === apiKey);
const ImportServersBtn = ({ importServersFromFile }: ServersImporter): FC<ImportServersBtnConnectProps> => ({ const ImportServersBtn = ({ importServersFromFile }: ServersImporter): FC<ImportServersBtnConnectProps> => ({
createServers, createServers,
servers,
fileRef, fileRef,
children, children,
onImport = () => {}, onImport = () => {},
@ -31,15 +38,37 @@ const ImportServersBtn = ({ importServersFromFile }: ServersImporter): FC<Import
className = '', className = '',
}) => { }) => {
const ref = fileRef ?? useRef<HTMLInputElement>(); const ref = fileRef ?? useRef<HTMLInputElement>();
const onChange = async ({ target }: ChangeEvent<HTMLInputElement>) => const [ serversToCreate, setServersToCreate ] = useState<ServerData[] | undefined>();
const [ duplicatedServers, setDuplicatedServers ] = useState<ServerData[]>([]);
const [ isModalOpen,, showModal, hideModal ] = useToggle();
const create = pipe(createServers, onImport);
const createAllServers = pipe(() => create(serversToCreate ?? []), hideModal);
const createNonDuplicatedServers = pipe(
() => create((serversToCreate ?? []).filter(complement(serversFiltering(duplicatedServers)))),
hideModal,
);
const onFile = async ({ target }: ChangeEvent<HTMLInputElement>) =>
importServersFromFile(target.files?.[0]) importServersFromFile(target.files?.[0])
.then(pipe(createServers, onImport)) .then(setServersToCreate)
.then(() => { .then(() => {
// Reset input after processing file // Reset input after processing file
(target as { value: string | null }).value = null; (target as { value: string | null }).value = null;
}) })
.catch(onImportError); .catch(onImportError);
useEffect(() => {
if (!serversToCreate) {
return;
}
const existingServers = Object.values(servers);
const duplicatedServers = serversToCreate.filter(serversFiltering(existingServers));
const hasDuplicatedServers = !!duplicatedServers.length;
!hasDuplicatedServers ? create(serversToCreate) : setDuplicatedServers(duplicatedServers);
hasDuplicatedServers && showModal();
}, [ serversToCreate ]);
return ( return (
<> <>
<Button outline id="importBtn" className={className} onClick={() => ref.current?.click()}> <Button outline id="importBtn" className={className} onClick={() => ref.current?.click()}>
@ -49,7 +78,14 @@ const ImportServersBtn = ({ importServersFromFile }: ServersImporter): FC<Import
You can create servers by importing a CSV file with columns <b>name</b>, <b>apiKey</b> and <b>url</b>. You can create servers by importing a CSV file with columns <b>name</b>, <b>apiKey</b> and <b>url</b>.
</UncontrolledTooltip> </UncontrolledTooltip>
<input type="file" accept="text/csv" className="import-servers-btn__csv-select" ref={ref} onChange={onChange} /> <input type="file" accept="text/csv" className="import-servers-btn__csv-select" ref={ref} onChange={onFile} />
<DuplicatedServersModal
isOpen={isModalOpen}
duplicatedServers={duplicatedServers}
onDiscard={createNonDuplicatedServers}
onSave={createAllServers}
/>
</> </>
); );
}; };

View file

@ -7,7 +7,7 @@ const validateServer = (server: any): server is ServerData =>
const validateServers = (servers: any): servers is ServerData[] => const validateServers = (servers: any): servers is ServerData[] =>
Array.isArray(servers) && servers.every(validateServer); Array.isArray(servers) && servers.every(validateServer);
export default class ServersImporter { export class ServersImporter {
public constructor(private readonly csvJson: CsvJson, private readonly fileReaderFactory: () => FileReader) {} public constructor(private readonly csvJson: CsvJson, private readonly fileReaderFactory: () => FileReader) {}
public readonly importServersFromFile = async (file?: File | null): Promise<ServerData[]> => { public readonly importServersFromFile = async (file?: File | null): Promise<ServerData[]> => {

View file

@ -17,7 +17,7 @@ import { Overview } from '../Overview';
import { ManageServers } from '../ManageServers'; import { ManageServers } from '../ManageServers';
import { ManageServersRow } from '../ManageServersRow'; import { ManageServersRow } from '../ManageServersRow';
import { ManageServersRowDropdown } from '../ManageServersRowDropdown'; import { ManageServersRowDropdown } from '../ManageServersRowDropdown';
import ServersImporter from './ServersImporter'; import { ServersImporter } from './ServersImporter';
import ServersExporter from './ServersExporter'; import ServersExporter from './ServersExporter';
const provideServices = (bottle: Bottle, connect: ConnectDecorator, withRouter: Decorator) => { const provideServices = (bottle: Bottle, connect: ConnectDecorator, withRouter: Decorator) => {
@ -54,7 +54,7 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator, withRouter:
bottle.serviceFactory('DeleteServerButton', DeleteServerButton, 'DeleteServerModal'); bottle.serviceFactory('DeleteServerButton', DeleteServerButton, 'DeleteServerModal');
bottle.serviceFactory('ImportServersBtn', ImportServersBtn, 'ServersImporter'); bottle.serviceFactory('ImportServersBtn', ImportServersBtn, 'ServersImporter');
bottle.decorator('ImportServersBtn', connect(null, [ 'createServers' ])); bottle.decorator('ImportServersBtn', connect([ 'servers' ], [ 'createServers' ]));
bottle.serviceFactory('ForServerVersion', () => ForServerVersion); bottle.serviceFactory('ForServerVersion', () => ForServerVersion);
bottle.decorator('ForServerVersion', connect([ 'selectedServer' ])); bottle.decorator('ForServerVersion', connect([ 'selectedServer' ]));

View file

@ -4,7 +4,7 @@ import { History } from 'history';
import createServerConstruct from '../../src/servers/CreateServer'; import createServerConstruct from '../../src/servers/CreateServer';
import { ServerForm } from '../../src/servers/helpers/ServerForm'; import { ServerForm } from '../../src/servers/helpers/ServerForm';
import { ServerWithId } from '../../src/servers/data'; import { ServerWithId } from '../../src/servers/data';
import { DuplicatedServerModal } from '../../src/servers/helpers/DuplicatedServerModal'; import { DuplicatedServersModal } from '../../src/servers/helpers/DuplicatedServersModal';
describe('<CreateServer />', () => { describe('<CreateServer />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
@ -52,20 +52,20 @@ describe('<CreateServer />', () => {
expect(result.prop('type')).toEqual('error'); expect(result.prop('type')).toEqual('error');
}); });
it('creates server data form is submitted', () => { it('creates server data when form is submitted', () => {
const wrapper = createWrapper(); const wrapper = createWrapper();
const form = wrapper.find(ServerForm); const form = wrapper.find(ServerForm);
expect(wrapper.find(DuplicatedServerModal).prop('serverData')).not.toBeDefined(); expect(wrapper.find(DuplicatedServersModal).prop('duplicatedServers')).toEqual([]);
form.simulate('submit', {}); form.simulate('submit', {});
expect(wrapper.find(DuplicatedServerModal).prop('serverData')).toEqual({}); expect(wrapper.find(DuplicatedServersModal).prop('duplicatedServers')).toEqual([{}]);
}); });
it('saves server and redirects on modal save', () => { it('saves server and redirects on modal save', () => {
const wrapper = createWrapper(); const wrapper = createWrapper();
wrapper.find(ServerForm).simulate('submit', {}); wrapper.find(ServerForm).simulate('submit', {});
wrapper.find(DuplicatedServerModal).simulate('save'); wrapper.find(DuplicatedServersModal).simulate('save');
expect(createServerMock).toHaveBeenCalledTimes(1); expect(createServerMock).toHaveBeenCalledTimes(1);
expect(push).toHaveBeenCalledTimes(1); expect(push).toHaveBeenCalledTimes(1);
@ -74,7 +74,7 @@ describe('<CreateServer />', () => {
it('goes back on modal discard', () => { it('goes back on modal discard', () => {
const wrapper = createWrapper(); const wrapper = createWrapper();
wrapper.find(DuplicatedServerModal).simulate('discard'); wrapper.find(DuplicatedServersModal).simulate('discard');
expect(goBack).toHaveBeenCalledTimes(1); expect(goBack).toHaveBeenCalledTimes(1);
}); });

View file

@ -1,16 +1,16 @@
import { shallow, ShallowWrapper } from 'enzyme'; import { shallow, ShallowWrapper } from 'enzyme';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { Button } from 'reactstrap'; import { Button } from 'reactstrap';
import { DuplicatedServerModal } from '../../../src/servers/helpers/DuplicatedServerModal'; import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal';
import { ServerData } from '../../../src/servers/data'; import { ServerData } from '../../../src/servers/data';
describe('<DuplicatedServerModal />', () => { describe('<DuplicatedServersModal />', () => {
const onDiscard = jest.fn(); const onDiscard = jest.fn();
const onSave = jest.fn(); const onSave = jest.fn();
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
const createWrapper = (serverData?: ServerData) => { const createWrapper = (duplicatedServers: ServerData[] = []) => {
wrapper = shallow( wrapper = shallow(
<DuplicatedServerModal isOpen serverData={serverData} toggle={jest.fn()} onDiscard={onDiscard} onSave={onSave} />, <DuplicatedServersModal isOpen duplicatedServers={duplicatedServers} onDiscard={onDiscard} onSave={onSave} />,
); );
return wrapper; return wrapper;
@ -20,14 +20,18 @@ describe('<DuplicatedServerModal />', () => {
afterEach(() => wrapper?.unmount()); afterEach(() => wrapper?.unmount());
it.each([ it.each([
[ undefined ], [[]],
[ Mock.of<ServerData>({ url: 'url', apiKey: 'apiKey' }) ], [[ Mock.of<ServerData>({ url: 'url', apiKey: 'apiKey' }) ]],
])('displays provided server data', (serverData) => { ])('displays provided server data', (duplicatedServers) => {
const wrapper = createWrapper(serverData); const wrapper = createWrapper(duplicatedServers);
const li = wrapper.find('li'); const li = wrapper.find('li');
expect(li.first().find('b').html()).toEqual(`<b>${serverData?.url ?? ''}</b>`); if (duplicatedServers.length === 0) {
expect(li.last().find('b').html()).toEqual(`<b>${serverData?.apiKey ?? ''}</b>`); expect(li).toHaveLength(0);
} else {
expect(li.first().find('b').html()).toEqual(`<b>${duplicatedServers[0].url}</b>`);
expect(li.last().find('b').html()).toEqual(`<b>${duplicatedServers[0].apiKey}</b>`);
}
}); });
it('invokes onDiscard when appropriate button is clicked', () => { it('invokes onDiscard when appropriate button is clicked', () => {

View file

@ -2,8 +2,9 @@ import { ReactNode } from 'react';
import { shallow, ShallowWrapper } from 'enzyme'; import { shallow, ShallowWrapper } from 'enzyme';
import { UncontrolledTooltip } from 'reactstrap'; import { UncontrolledTooltip } from 'reactstrap';
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import importServersBtnConstruct from '../../../src/servers/helpers/ImportServersBtn'; import importServersBtnConstruct, { ImportServersBtnProps } from '../../../src/servers/helpers/ImportServersBtn';
import ServersImporter from '../../../src/servers/services/ServersImporter'; import { ServersImporter } from '../../../src/servers/services/ServersImporter';
import { DuplicatedServersModal } from '../../../src/servers/helpers/DuplicatedServersModal';
describe('<ImportServersBtn />', () => { describe('<ImportServersBtn />', () => {
let wrapper: ShallowWrapper; let wrapper: ShallowWrapper;
@ -12,17 +13,15 @@ describe('<ImportServersBtn />', () => {
const importServersFromFile = jest.fn().mockResolvedValue([]); const importServersFromFile = jest.fn().mockResolvedValue([]);
const serversImporterMock = Mock.of<ServersImporter>({ importServersFromFile }); const serversImporterMock = Mock.of<ServersImporter>({ importServersFromFile });
const click = jest.fn(); const click = jest.fn();
const fileRef = { const fileRef = { current: Mock.of<HTMLInputElement>({ click }) };
current: Mock.of<HTMLInputElement>({ click }),
};
const ImportServersBtn = importServersBtnConstruct(serversImporterMock); const ImportServersBtn = importServersBtnConstruct(serversImporterMock);
const createWrapper = (className?: string, children?: ReactNode) => { const createWrapper = (props: Partial<ImportServersBtnProps & { children: ReactNode }> = {}) => {
wrapper = shallow( wrapper = shallow(
<ImportServersBtn <ImportServersBtn
createServers={createServersMock} servers={{}}
className={className} {...props}
fileRef={fileRef} fileRef={fileRef}
children={children} createServers={createServersMock}
onImport={onImportMock} onImport={onImportMock}
/>, />,
); );
@ -46,7 +45,7 @@ describe('<ImportServersBtn />', () => {
[ 'foo', 'foo' ], [ 'foo', 'foo' ],
[ 'bar', 'bar' ], [ 'bar', 'bar' ],
])('allows a class name to be provided', (providedClassName, expectedClassName) => { ])('allows a class name to be provided', (providedClassName, expectedClassName) => {
const wrapper = createWrapper(providedClassName); const wrapper = createWrapper({ className: providedClassName });
expect(wrapper.find('#importBtn').prop('className')).toEqual(expectedClassName); expect(wrapper.find('#importBtn').prop('className')).toEqual(expectedClassName);
}); });
@ -56,7 +55,7 @@ describe('<ImportServersBtn />', () => {
[ 'foo', false ], [ 'foo', false ],
[ 'bar', false ], [ 'bar', false ],
])('has expected text', (children, expectToHaveDefaultText) => { ])('has expected text', (children, expectToHaveDefaultText) => {
const wrapper = createWrapper(undefined, children); const wrapper = createWrapper({ children });
if (expectToHaveDefaultText) { if (expectToHaveDefaultText) {
expect(wrapper.find('#importBtn').html()).toContain('Import from file'); expect(wrapper.find('#importBtn').html()).toContain('Import from file');
@ -82,6 +81,16 @@ describe('<ImportServersBtn />', () => {
await file.simulate('change', { target: { files: [ '' ] } }); // eslint-disable-line @typescript-eslint/await-thenable await file.simulate('change', { target: { files: [ '' ] } }); // eslint-disable-line @typescript-eslint/await-thenable
expect(importServersFromFile).toHaveBeenCalledTimes(1); expect(importServersFromFile).toHaveBeenCalledTimes(1);
});
it.each([
[ 'discard' ],
[ 'save' ],
])('invokes callback in DuplicatedServersModal events', (event) => {
const wrapper = createWrapper();
wrapper.find(DuplicatedServersModal).simulate(event);
expect(createServersMock).toHaveBeenCalledTimes(1); expect(createServersMock).toHaveBeenCalledTimes(1);
expect(onImportMock).toHaveBeenCalledTimes(1); expect(onImportMock).toHaveBeenCalledTimes(1);
}); });

View file

@ -1,6 +1,6 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { CsvJson } from 'csvjson'; import { CsvJson } from 'csvjson';
import ServersImporter from '../../../src/servers/services/ServersImporter'; import { ServersImporter } from '../../../src/servers/services/ServersImporter';
import { RegularServer } from '../../../src/servers/data'; import { RegularServer } from '../../../src/servers/data';
describe('ServersImporter', () => { describe('ServersImporter', () => {