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

OHRI-1838 Add support for capturing drugs as observations #121

Merged
merged 3 commits into from
Sep 29, 2023
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
2 changes: 1 addition & 1 deletion src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export interface OHRIFormQuestionOptions {
};
isDateTime?: { labelTrue: boolean; labelFalse: boolean };
usePreviousValueDisabled?: boolean;
datasource?: { id: string; config?: Record<string, any> };
datasource?: { name: string; config?: Record<string, any> };
isSearchable?: boolean;
}

Expand Down
2 changes: 1 addition & 1 deletion src/components/inputs/select/ohri-dropdown.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const renderForm = intialValues => {
fields: [question],
isFieldInitializationComplete: true,
isSubmitting: false,
formFieldHandlers: { 'obs': ObsSubmissionHandler }
formFieldHandlers: { obs: ObsSubmissionHandler },
}}>
<OHRIDropdown question={question} onChange={jest.fn()} handler={ObsSubmissionHandler} />
</OHRIFormContext.Provider>
Expand Down
165 changes: 165 additions & 0 deletions src/components/inputs/ui-select-extended/ui-select-extended.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import React from 'react';
import { render, fireEvent, waitFor, act, screen } from '@testing-library/react';
import UISelectExtended from './ui-select-extended';
import { OHRIFormField } from '../../../api/types';
import { EncounterContext, OHRIFormContext } from '../../../ohri-form-context';
import { Form, Formik } from 'formik';
import { ObsSubmissionHandler } from '../../../submission-handlers/base-handlers';

const question: OHRIFormField = {
label: 'Transfer Location',
type: 'obs',
questionOptions: {
rendering: 'ui-select-extended',
concept: '160540AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
datasource: {
name: 'location_datasource',
},
},
value: null,
id: 'patient_transfer_location',
};

const encounterContext: EncounterContext = {
patient: {
id: '833db896-c1f0-11eb-8529-0242ac130003',
},
location: {
uuid: '41e6e516-c1f0-11eb-8529-0242ac130003',
},
encounter: {
uuid: '873455da-3ec4-453c-b565-7c1fe35426be',
obs: [],
},
sessionMode: 'enter',
encounterDate: new Date(2023, 8, 29),
setEncounterDate: value => {},
};

const renderForm = intialValues => {
render(
<Formik initialValues={intialValues} onSubmit={null}>
{props => (
<Form>
<OHRIFormContext.Provider
value={{
values: props.values,
setFieldValue: props.setFieldValue,
setEncounterLocation: jest.fn(),
obsGroupsToVoid: [],
setObsGroupsToVoid: jest.fn(),
encounterContext: encounterContext,
fields: [question],
isFieldInitializationComplete: true,
isSubmitting: false,
formFieldHandlers: { obs: ObsSubmissionHandler },
}}>
<UISelectExtended question={question} onChange={jest.fn()} handler={ObsSubmissionHandler} />
</OHRIFormContext.Provider>
</Form>
)}
</Formik>,
);
};

// Mock the data source fetch behavior
jest.mock('../../../registry/registry', () => ({
getRegisteredDataSource: jest.fn().mockResolvedValue({
fetchData: jest.fn().mockResolvedValue([
{
uuid: 'aaa-1',
display: 'Kololo',
},
{
uuid: 'aaa-2',
display: 'Naguru',
},
{
uuid: 'aaa-3',
display: 'Muyenga',
},
]),
toUuidAndDisplay: data => data,
}),
}));

describe('UISelectExtended Component', () => {
it('renders with items from the datasource', async () => {
await act(async () => {
await renderForm({});
});

// setup
const uiSelectExtendedWidget = screen.getByLabelText('Transfer Location');

// assert initial values
await act(async () => {
expect(question.value).toBe(null);
});

//Click on the UISelectExtendedWidget to open the dropdown
fireEvent.click(uiSelectExtendedWidget);

// Assert that all three items are displayed
expect(screen.getByText('Kololo')).toBeInTheDocument();
expect(screen.getByText('Naguru')).toBeInTheDocument();
expect(screen.getByText('Muyenga')).toBeInTheDocument();
});

it('Selects a value from the list', async () => {
await act(async () => {
await renderForm({});
});

// setup
const uiSelectExtendedWidget = screen.getByLabelText('Transfer Location');

//Click on the UISelectExtendedWidget to open the dropdown
fireEvent.click(uiSelectExtendedWidget);

// Find the list item for 'Naguru' and click it to select
const naguruOption = screen.getByText('Naguru');
fireEvent.click(naguruOption);

// verify
await act(async () => {
expect(question.value).toEqual({
person: '833db896-c1f0-11eb-8529-0242ac130003',
obsDatetime: new Date(2023, 8, 29),
concept: '160540AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
location: { uuid: '41e6e516-c1f0-11eb-8529-0242ac130003' },
formFieldNamespace: 'ohri-forms',
formFieldPath: 'ohri-forms-patient_transfer_location',
order: null,
groupMembers: [],
voided: false,
value: 'aaa-2',
});
});
});

it('Filters items based on user input', async () => {
await act(async () => {
await renderForm({});
});

// setup
const uiSelectExtendedWidget = screen.getByLabelText('Transfer Location');

//Click on the UISelectExtendedWidget to open the dropdown
fireEvent.click(uiSelectExtendedWidget);

// Type 'Nag' in the input field to filter items
fireEvent.change(uiSelectExtendedWidget, { target: { value: 'Nag' } });

// Wait for the filtered items to appear in the dropdown
await waitFor(() => {
// Verify that 'Naguru' is in the filtered items
expect(screen.getByText('Naguru')).toBeInTheDocument();

// Verify that 'Kololo' and 'Muyenga' are not in the filtered items
expect(screen.queryByText('Kololo')).not.toBeInTheDocument();
expect(screen.queryByText('Muyenga')).not.toBeInTheDocument();
});
});
});
26 changes: 17 additions & 9 deletions src/components/inputs/ui-select-extended/ui-select-extended.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ import { PreviousValueReview } from '../../previous-value-review/previous-value-
import debounce from 'lodash-es/debounce';
import { useTranslation } from 'react-i18next';
import { getRegisteredDataSource } from '../../../registry/registry';
import { getControlTemplate } from '../../../registry/inbuilt-components/control-templates';

export const UISelectExtended: React.FC<OHRIFormFieldProps> = ({ question, handler, onChange }) => {
const UISelectExtended: React.FC<OHRIFormFieldProps> = ({ question, handler, onChange }) => {
const { t } = useTranslation();
const [field, meta] = useField(question.id);
const { setFieldValue, encounterContext, fields } = React.useContext(OHRIFormContext);
Expand All @@ -28,9 +29,18 @@ export const UISelectExtended: React.FC<OHRIFormFieldProps> = ({ question, handl
const [inputValue, setInputValue] = useState('');
const isProcessingSelection = useRef(false);
const [dataSource, setDataSource] = useState(null);
const [config, setConfig] = useState({});

useEffect(() => {
getRegisteredDataSource(question.questionOptions?.datasource?.id).then(ds => setDataSource(ds));
const datasourceName = question.questionOptions?.datasource?.name;
setConfig(
datasourceName
? question.questionOptions.datasource?.config
: getControlTemplate(question.questionOptions.rendering)?.datasource?.config,
);
getRegisteredDataSource(datasourceName ? datasourceName : question.questionOptions.rendering).then(ds =>
setDataSource(ds),
);
}, [question.questionOptions?.datasource]);

useEffect(() => {
Expand All @@ -48,7 +58,7 @@ export const UISelectExtended: React.FC<OHRIFormFieldProps> = ({ question, handl

const debouncedSearch = debounce((searchterm, dataSource) => {
setIsLoading(true);
dataSource.fetchData(searchterm, question.questionOptions?.datasource?.config).then(dataItems => {
dataSource.fetchData(searchterm, config).then(dataItems => {
setItems(dataItems.map(dataSource.toUuidAndDisplay));
setIsLoading(false);
});
Expand All @@ -58,15 +68,14 @@ export const UISelectExtended: React.FC<OHRIFormFieldProps> = ({ question, handl
// If not searchable, preload the items
if (dataSource && !isTrue(question.questionOptions.isSearchable)) {
setIsLoading(true);
dataSource.fetchData(null, question.questionOptions?.datasource?.config).then(dataItems => {
dataSource.fetchData(null, config).then(dataItems => {
setItems(dataItems.map(dataSource.toUuidAndDisplay));
setIsLoading(false);
});
}
}, [dataSource]);

useEffect(() => {
// get the data source
if (dataSource && isTrue(question.questionOptions.isSearchable) && !isEmpty(searchTerm)) {
debouncedSearch(searchTerm, dataSource);
}
Expand Down Expand Up @@ -114,8 +123,6 @@ export const UISelectExtended: React.FC<OHRIFormFieldProps> = ({ question, handl
id={question.id}
titleText={question.label}
items={items}
isLoading={isLoading}
loadingMessage="loading..."
itemToString={item => item?.display}
selectedItem={items.find(item => item.uuid == field.value)}
shouldFilterItem={({ item, inputValue }) => {
Expand All @@ -139,8 +146,7 @@ export const UISelectExtended: React.FC<OHRIFormFieldProps> = ({ question, handl
isProcessingSelection.current = false;
return;
}
setInputValue('');
setFieldValue(question.id, '');
setInputValue(value);
if (question.questionOptions['isSearchable']) {
setSearchTerm(value);
}
Expand All @@ -162,3 +168,5 @@ export const UISelectExtended: React.FC<OHRIFormFieldProps> = ({ question, handl
)
);
};

export default UISelectExtended;
18 changes: 18 additions & 0 deletions src/datasources/concept-data-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { openmrsFetch } from '@openmrs/esm-framework';
import { BaseOpenMRSDataSource } from './data-source';

export class ConceptDataSource extends BaseOpenMRSDataSource {
constructor() {
super('/ws/rest/v1/concept?name=&searchType=fuzzy&v=custom:(uuid,display)');
}

fetchData(searchTerm: string, config?: Record<string, any>): Promise<any[]> {
if (config?.class) {
let urlParts = this.url.split('name=');
this.url = `${urlParts[0]}&name=&class=${config.class}&${urlParts[1]}`;
}
return openmrsFetch(searchTerm ? `${this.url}&q=${searchTerm}` : this.url).then(({ data }) => {
return data.results;
});
}
}
5 changes: 2 additions & 3 deletions src/datasources/location-data-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { openmrsFetch } from '@openmrs/esm-framework';
import { BaseOpenMRSDataSource } from './data-source';

export class LocationDataSource extends BaseOpenMRSDataSource {
constructor(){
super("/ws/rest/v1/location?v=custom:(uuid,display)");
constructor() {
super('/ws/rest/v1/location?v=custom:(uuid,display)');
}

fetchData(searchTerm: string, config?: Record<string, any>): Promise<any[]> {
Expand All @@ -15,5 +15,4 @@ export class LocationDataSource extends BaseOpenMRSDataSource {
return data.results;
});
}

}
15 changes: 15 additions & 0 deletions src/registry/inbuilt-components/control-templates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export const controlTemplates = [
{
name: 'drug',
datasource: {
name: 'drug_datasource',
config: {
class: '8d490dfc-c2cc-11de-8d13-0010c6dffd0f',
},
},
},
];

export const getControlTemplate = (name: string) => {
return controlTemplates.find(template => template.name === name);
};
10 changes: 9 additions & 1 deletion src/registry/inbuilt-components/inbuiltControls.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { OHRIFormFieldProps } from '../../api/types';
import OHRIExtensionParcel from '../../components/extension/ohri-extension-parcel.component';
import UISelectExtended from '../../components/inputs/ui-select-extended/ui-select-extended';
import { OHRIObsGroup } from '../../components/group/ohri-obs-group.component';
import { OHRIContentSwitcher } from '../../components/inputs/content-switcher/ohri-content-switcher.component';
import OHRIDate from '../../components/inputs/date/ohri-date.component';
Expand All @@ -13,13 +14,15 @@ import OHRIDropdown from '../../components/inputs/select/ohri-dropdown.component
import OHRITextArea from '../../components/inputs/text-area/ohri-text-area.component';
import OHRIText from '../../components/inputs/text/ohri-text.component';
import OHRIToggle from '../../components/inputs/toggle/ohri-toggle.component';
import { UISelectExtended } from '../../components/inputs/ui-select-extended/ui-select-extended';
import { OHRIRepeat } from '../../components/repeat/ohri-repeat.component';
import { RegistryItem } from '../registry';
import { controlTemplates } from './control-templates';
import { templateToComponentMap } from './template-component-map';

/**
* @internal
*/

export const inbuiltControls: Array<RegistryItem<React.ComponentType<OHRIFormFieldProps>>> = [
{
name: 'OHRIText',
Expand Down Expand Up @@ -108,4 +111,9 @@ export const inbuiltControls: Array<RegistryItem<React.ComponentType<OHRIFormFie
component: UISelectExtended,
type: 'ui-select-extended',
},
...controlTemplates.map(template => ({
name: `${template.name}Control`,
component: templateToComponentMap.find(component => component.name === template.name).baseControlComponent,
type: template.name.toLowerCase(),
})),
];
11 changes: 10 additions & 1 deletion src/registry/inbuilt-components/inbuiltDataSources.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { DataSource } from '../../api/types';
import { ConceptDataSource } from '../../datasources/concept-data-source';
import { LocationDataSource } from '../../datasources/location-data-source';
import { RegistryItem } from '../registry';

Expand All @@ -7,7 +8,15 @@ import { RegistryItem } from '../registry';
*/
export const inbuiltDataSources: Array<RegistryItem<DataSource<any>>> = [
{
name: 'concept_location',
name: 'location_datasource',
component: new LocationDataSource(),
},
{
name: 'drug_datasource',
component: new ConceptDataSource(),
},
];

export const validateInbuiltDatasource = (name: string) => {
return inbuiltDataSources.some(datasource => datasource.name === name);
};
8 changes: 8 additions & 0 deletions src/registry/inbuilt-components/template-component-map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import UISelectExtended from '../../components/inputs/ui-select-extended/ui-select-extended';

export const templateToComponentMap = [
{
name: 'drug',
baseControlComponent: UISelectExtended,
},
];
Loading
Loading