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

Phani | A-1206828243895868 | Remove debouncing and add API cancellation for Appointment Patient Search #323

Merged
merged 4 commits into from
Mar 26, 2024
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 i18n/appointments/locale_en.json
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@
"SELECT_APPOINTMENT_PROVIDER": "Select Provider",
"INVITED_PROVIDERS": "Invitees",
"APPOINTMENT_PROVIDER_REMOVE_ACTION": "Remove",
"DROPDOWN_NO_OPTIONS_MESSAGE" : "Type to search",
"DROPDOWN_NO_OPTIONS_MESSAGE" : "No patients found",
"DROPDOWN_LOADING_MESSAGE" : "Loading...",
"RECURRENCE_THIS_APPOINTMENT": "Cancel Occurrence",
"RECURRENCE_ALL_APPOINTMENTS" : "Cancel All",
Expand Down
2 changes: 0 additions & 2 deletions src/controllers/manage/appointmentsCreateController.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ angular.module('bahmni.appointments')
var patientSearchURL = appService.getAppDescriptor().getConfigValue('patientSearchUrl');
var loginLocationUuid = sessionService.getLoginLocationUuid();
$scope.minCharLengthToTriggerPatientSearch = appService.getAppDescriptor().getConfigValue('minCharLengthToTriggerPatientSearch') || 3;
$scope.debouncePatientSearchDelayInMilliseconds = appService.getAppDescriptor().getConfigValue('debouncePatientSearchDelayInMilliseconds') || 3000;

$scope.maxAppointmentProviders = appService.getAppDescriptor().getConfigValue("maxAppointmentProviders") || 1;

var isProviderNotAvailableForAppointments = function (selectedProvider) {
Expand Down
19 changes: 15 additions & 4 deletions ui/react-components/api/patientApi.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import axios from 'axios';
import {patientUrl, searchPatientUrl, personUrl} from '../config';

export const getPatientsByLocation = async (locationUuid, searchQuery, startIndex = 0) => {
export const getPatientsByLocation = async (locationUuid, searchQuery, cancelToken, startIndex = 0) => {
try {
const response = await axios.get(`${searchPatientUrl}?loginLocationUuid=${locationUuid}&filterOnAllIdentifiers=true&identifier=${searchQuery}&q=${searchQuery}&startIndex=${startIndex}`);
const response = await axios.get(searchPatientUrl, {
params: {
loginLocationUuid: locationUuid,
filterOnAllIdentifiers: true,
identifier: searchQuery,
q: searchQuery,
startIndex: startIndex
},
cancelToken: cancelToken
});
return response.data.pageOfResults;
} catch (error) {
console.error(error);
if (!axios.isCancel(error)) {
console.error(error);
}
return error.response;
}
};
Expand All @@ -25,7 +36,7 @@ export const getPersonAttribute = async (uuid, attribute) => {
try {
const response = await axios.get(`${personUrl}/${uuid}/attribute`);
for (let i = 0; i < response.data.results.length; i++) {
if(response.data.results[i].attributeType.display == attribute)
if (response.data.results[i].attributeType.display == attribute)
return response.data.results[i].value;
}
return null;
Expand Down
34 changes: 27 additions & 7 deletions ui/react-components/api/patientApi.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,20 @@ afterEach(() => {
});

describe('Patient Api', () => {
it('should take location uuid and search query to return list of patients', async () =>{
it('should take location uuid and search query and cancel Token to return list of patients', async () =>{
let locationUuid = "locationUuid";
let searchQuery = "searchquery";
let cancelToken = "CancelToken";
let expectedParams = {
cancelToken: cancelToken,
params: {
filterOnAllIdentifiers: true,
identifier: searchQuery,
loginLocationUuid: locationUuid,
q: searchQuery,
startIndex: 0
}
}
let mockResponse = {
"totalCount": null,
"pageOfResults": [
Expand Down Expand Up @@ -41,18 +52,28 @@ describe('Patient Api', () => {
})
);

let patientsByLocation = await getPatientsByLocation(locationUuid, searchQuery);
let patientsByLocation = await getPatientsByLocation(locationUuid, searchQuery, cancelToken);

expect(mockAxios.get)
.toHaveBeenCalledWith(
`${searchPatientUrl}?loginLocationUuid=${locationUuid}&filterOnAllIdentifiers=true&identifier=${searchQuery}&q=${searchQuery}&startIndex=0`);
.toHaveBeenCalledWith(searchPatientUrl, expectedParams);
expect(patientsByLocation).toEqual(mockResponse.pageOfResults);
});

it('should take location uuid and search query and start index to return list of patients', async () => {
let locationUuid = "locationUuid";
let searchQuery = "searchquery";
let startIndex = 6;
let cancelToken = "CancelToken";
let expectedParams = {
cancelToken: cancelToken,
params: {
filterOnAllIdentifiers: true,
identifier: searchQuery,
loginLocationUuid: locationUuid,
q: searchQuery,
startIndex: startIndex
}
}
let mockResponse = {
"totalCount": null,
"pageOfResults": [
Expand Down Expand Up @@ -82,11 +103,10 @@ describe('Patient Api', () => {
})
);

await getPatientsByLocation(locationUuid, searchQuery, startIndex);
await getPatientsByLocation(locationUuid, searchQuery, cancelToken, startIndex);

expect(mockAxios.get)
.toHaveBeenCalledWith(
`${searchPatientUrl}?loginLocationUuid=${locationUuid}&filterOnAllIdentifiers=true&identifier=${searchQuery}&q=${searchQuery}&startIndex=${startIndex}`);
.toHaveBeenCalledWith(searchPatientUrl, expectedParams);
});

it('should fetch patient by given uuid', async () =>{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -586,8 +586,8 @@ const AddAppointment = props => {
updateAppointmentDetails({ appointmentType: e.name });
}
}}>
<Switch name="Regular" >Regular Appointment</Switch>
<Switch name="Recurring">Recurring Appointment</Switch>
<Switch name="Regular" text={intl.formatMessage({id: 'REGULAR_APPOINTMENT_LABEL', defaultMessage: "Regular Appointment"})}/>
<Switch name="Recurring" text={intl.formatMessage({id: 'RECURRING_APPOINTMENT_LABEL', defaultMessage: "Recurring Appointment"})}/>
</ContentSwitcher>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ const AppointmentEditorCommonFieldsWrapper = props => {
<PatientSearch
value={appointmentDetails.patient}
minCharLengthToTriggerPatientSearch={appConfig && appConfig.minCharLengthToTriggerPatientSearch}
debouncePatientSearchDelayInMilliseconds={appConfig && appConfig.debouncePatientSearchDelayInMilliseconds}
onChange={(optionSelected) => {
const newValue = optionSelected ? optionSelected : null;
updateAppointmentDetails({patient: newValue});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -629,8 +629,8 @@ const EditAppointment = props => {
<div data-testid="recurring-plan-checkbox">
<div className={classNames(appointmentPlanContainer)}>
<ContentSwitcher selectedIndex={recurring? 1 : 0} >
<Switch name="Regular" disabled={recurring}>Regular Appointment</Switch>
<Switch name="Recurring" disabled={!recurring}>Recurring Appointment</Switch>
<Switch name="Regular" disabled={recurring}text={intl.formatMessage({id: 'REGULAR_APPOINTMENT_LABEL', defaultMessage: "Regular Appointment"})}/>
<Switch name="Recurring" disabled={!recurring}text={intl.formatMessage({id: 'RECURRING_APPOINTMENT_LABEL', defaultMessage: "Recurring Appointment"})}/>
</ContentSwitcher>
</div>
</div>
Expand Down
67 changes: 35 additions & 32 deletions ui/react-components/components/PatientSearch/PatientSearch.jsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import React, {useCallback, useEffect, useState} from "react";
import React, { useEffect, useState} from "react";
import PropTypes from "prop-types";
import { injectIntl } from "react-intl";
import { DEBOUNCE_PATIENT_SEARCH_DELAY_IN_MILLISECONDS, MINIMUM_CHAR_LENGTH_FOR_PATIENT_SEARCH } from "../../constants";
import { MINIMUM_CHAR_LENGTH_FOR_PATIENT_SEARCH } from "../../constants";
import { ComboBox } from "carbon-components-react";
import { getPatientsByLocation } from "../../api/patientApi";
import { currentLocation } from "../../utils/CookieUtil";
import { getPatientForDropdown } from "../../mapper/patientMapper";
import { debounce } from "lodash";
import Title from "../Title/Title.jsx";
import axios from "axios";

export const PatientSearch = (props) => {
const {
Expand All @@ -16,57 +16,60 @@ export const PatientSearch = (props) => {
value,
isDisabled,
minCharLengthToTriggerPatientSearch = MINIMUM_CHAR_LENGTH_FOR_PATIENT_SEARCH,
debouncePatientSearchDelayInMilliseconds,
autoFocus
} = props;
const [items, setItems] = useState([]);
const [userInput, setUserInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const debouncePatientSearchDelay = debouncePatientSearchDelayInMilliseconds || DEBOUNCE_PATIENT_SEARCH_DELAY_IN_MILLISECONDS;
const [cancelToken, setCancelToken] = useState(null);

const setDisabledItems = ( translationKey, defaultMessage) => {
setItems([{
label: intl.formatMessage({id: translationKey, defaultMessage: defaultMessage}),
disabled: true
}])
}
const loadPatients = async (searchString) => {
if (searchString.length >= (minCharLengthToTriggerPatientSearch || 3)) {
setIsLoading(true);
const patients = await getPatientsByLocation(currentLocation().uuid, searchString);
setIsLoading(false);
if (patients.length === 0) {
setItems([{
label: intl.formatMessage({id: 'DROPDOWN_NO_OPTIONS_MESSAGE', defaultMessage: 'No patients found'}),
disabled: true
}])
} else {
setItems(patients.map(getPatientForDropdown));
if (searchString.length >= minCharLengthToTriggerPatientSearch) {
try{
setIsLoading(true);
if(cancelToken){
cancelToken.cancel('New Request made');
}
const source = axios.CancelToken.source();
setCancelToken(source);
const patients = await getPatientsByLocation(currentLocation().uuid, searchString, source.token);
if (patients.length === 0) {
setDisabledItems('DROPDOWN_NO_OPTIONS_MESSAGE', 'No patients found');
} else {
setItems(patients.map(getPatientForDropdown));
}
} catch (e) {
setDisabledItems('DROPDOWN_NO_OPTIONS_MESSAGE', 'No patients found')
}
finally {
setIsLoading(false);
}
}
};
const debouncedLoadPatients = useCallback(
debounce(loadPatients, debouncePatientSearchDelay, {
leading: true,
}),
[],
);

useEffect(() => {
if (userInput.length > 1) {
debouncedLoadPatients(userInput);
if (userInput.length >= MINIMUM_CHAR_LENGTH_FOR_PATIENT_SEARCH) {
loadPatients(userInput);
}
}, [userInput])

const handleInputChange = async (searchString) => {
setUserInput(searchString);
if (searchString.length < 3) {
setItems([{
label: intl.formatMessage({id: 'DROPDOWN_TYPE_TO_SEARCH_MESSAGE', defaultMessage: 'Type to search'}),
disabled: true
}]);
setDisabledItems('DROPDOWN_TYPE_TO_SEARCH_MESSAGE', 'Type to search');
} else{
setDisabledItems('DROPDOWN_LOADING_MESSAGE', 'Loading...');
}
}
useEffect(() => {
if (isLoading) {
setItems([{
label: intl.formatMessage({id: 'DROPDOWN_LOADING_MESSAGE', defaultMessage: 'Loading...'}),
disabled: true
}])
setDisabledItems('DROPDOWN_LOADING_MESSAGE', 'Loading...');
}
}, [isLoading])
const label = <Title
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@ jest.mock('../../utils/CookieUtil');
const patientApi = require('../../api/patientApi');
let getPatientByLocationSpy;

jest.mock('lodash.debounce', () => ({
__esModule: true,
default: jest.fn(c => c),
}));

describe('Patient Search', () => {
beforeEach(() => {
getPatientByLocationSpy = jest.spyOn(patientApi, 'getPatientsByLocation');
Expand Down Expand Up @@ -55,44 +50,7 @@ describe('Patient Search', () => {
);
expect(getPatientByLocationSpy).not.toHaveBeenCalled();
fireEvent.change(inputBox, { target: { value: "abcd" } });

setTimeout(() => {
expect(getPatientByLocationSpy).toHaveBeenCalled();
}, 3000);

});

it('should not make a second search for patients call when the user enters new characters within 3 seconds', async () => {
const {container} = renderWithReactIntl(<PatientSearch onChange={jest.fn()}
minCharLengthToTriggerPatientSearch={4}/>);
const inputBox = container.querySelector('.bx--text-input');
fireEvent.change(inputBox, { target: { value: "abcd" } });
await waitForElement(
() => (container.querySelector('.bx--list-box__menu-item__option'))
);
expect(getPatientByLocationSpy).toHaveBeenCalled();
fireEvent.change(inputBox, { target: { value: "abcde" } });

setTimeout(() => {
expect(getPatientByLocationSpy).not.toHaveBeenCalled();
}, 2000);

});

it('should make a second search for patients call when the user enters new characters after 3 seconds', async () => {
const {container} = renderWithReactIntl(<PatientSearch onChange={jest.fn()}/>);
const inputBox = container.querySelector('.bx--text-input');
fireEvent.change(inputBox, { target: { value: "abcd" } });
await waitForElement(
() => (container.querySelector('.bx--list-box__menu-item__option'))
);
expect(getPatientByLocationSpy).toHaveBeenCalled();
fireEvent.change(inputBox, { target: { value: "abcde" } });

setTimeout(() => {
expect(getPatientByLocationSpy).toHaveBeenCalled();
}, 3000);

});

it('should display placeholder as "Patient ID"', async () => {
Expand All @@ -115,4 +73,3 @@ describe('Patient Search', () => {
expect(onChangeSpy).toHaveBeenCalledTimes(1);
});
});

1 change: 0 additions & 1 deletion ui/react-components/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ export const appName = 'appointments';
export const availableForAppointments = "Available for appointments";
export const minDurationForAppointment = 30;
export const MINIMUM_CHAR_LENGTH_FOR_PATIENT_SEARCH = 3;
export const DEBOUNCE_PATIENT_SEARCH_DELAY_IN_MILLISECONDS = 3000;
export const DEFAULT_MAX_APPOINTMENT_PROVIDERS = 1;
export const PROVIDER_ERROR_MESSAGE_TIME_OUT_INTERVAL = 5000;
export const SERVICE_ERROR_MESSAGE_TIME_OUT_INTERVAL = 5000;
Expand Down
Loading