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

(feat) O3-2117: Save orders on a new encounter if there is no encounter #1727

Merged
merged 17 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
56 changes: 53 additions & 3 deletions packages/esm-patient-common-lib/src/orders/postOrders.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,58 @@
import { openmrsFetch, restBaseUrl } from '@openmrs/esm-framework';
import { openmrsFetch, type OpenmrsResource, parseDate, restBaseUrl, type Visit } from '@openmrs/esm-framework';
import { getPatientUuidFromUrl } from '../get-patient-uuid-from-url';
import { type OrderBasketStore, orderBasketStore } from './store';
import { type ExtractedOrderErrorObject, type OrderBasketItem, type OrderPost } from './types';
import { type OrderErrorObject } from './types';
import { type ExtractedOrderErrorObject, type OrderBasketItem, type OrderErrorObject, type OrderPost } from './types';

export async function postOrdersOnNewEncounter(
patientUuid: string,
orderEncounterType: string,
activeVisit: Visit | null,
sessionLocationUuid: string,
abortController?: AbortController,
) {
const now = new Date();
const visitStartDate = parseDate(activeVisit?.startDatetime);
const visitEndDate = parseDate(activeVisit?.stopDatetime);
let encounterDate: Date;
if (!activeVisit || (visitStartDate < now && (!visitEndDate || visitEndDate > now))) {
encounterDate = now;
} else {
console.warn(
'create Encounter received an active visit that is not currently active. This is a programming error. Attempting to place the order using the visit start date.',
);
usamaidrsk marked this conversation as resolved.
Show resolved Hide resolved
encounterDate = visitStartDate;
}

const { items, postDataPrepFunctions }: OrderBasketStore = orderBasketStore.getState();
const patientItems = items[patientUuid];

const orders: Array<OrderPost> = [];

Object.entries(patientItems).forEach(([grouping, groupOrders]) => {
groupOrders.forEach((order) => {
orders.push(postDataPrepFunctions[grouping](order, patientUuid, null));
});
});

const encounterPostData = {
patient: patientUuid,
location: sessionLocationUuid,
encounterType: orderEncounterType,
encounterDatetime: encounterDate,
visit: activeVisit?.uuid,
obs: [],
orders,
};

return openmrsFetch<OpenmrsResource>(`${restBaseUrl}/encounter`, {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: encounterPostData,
signal: abortController?.signal,
}).then((res) => res?.data?.uuid);
}

export async function postOrders(encounterUuid: string, abortController: AbortController) {
const patientUuid = getPatientUuidFromUrl();
Expand Down
6 changes: 5 additions & 1 deletion packages/esm-patient-common-lib/src/orders/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,11 @@ export interface Drug {
display: string;
}

export type PostDataPrepFunction = (order: OrderBasketItem, patientUuid: string, encounterUuid: string) => OrderPost;
export type PostDataPrepFunction = (
order: OrderBasketItem,
patientUuid: string,
encounterUuid: string | null,
) => OrderPost;

// Adopted from @openmrs/esm-patient-medications-app package. We should consider maintaining a single shared types file
export interface DrugOrderBasketItem extends OrderBasketItem {
Expand Down
49 changes: 2 additions & 47 deletions packages/esm-patient-orders-app/src/api/api.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import { useCallback, useMemo } from 'react';
import useSWR, { useSWRConfig } from 'swr';
import {
type FetchResponse,
openmrsFetch,
type OpenmrsResource,
parseDate,
type Visit,
restBaseUrl,
} from '@openmrs/esm-framework';
import { type OrderPost, useVisitOrOfflineVisit, useSystemVisitSetting } from '@openmrs/esm-patient-common-lib';
import { type FetchResponse, openmrsFetch, type OpenmrsResource, restBaseUrl } from '@openmrs/esm-framework';
import { type OrderPost, useSystemVisitSetting, useVisitOrOfflineVisit } from '@openmrs/esm-patient-common-lib';

export const careSettingUuid = '6f0c9a92-6f24-11e3-af88-005056821db0';

Expand Down Expand Up @@ -48,44 +41,6 @@ export function getMedicationByUuid(abortController: AbortController, orderUuid:
);
}

export function createEmptyEncounter(
patientUuid: string,
orderEncounterType: string,
activeVisit: Visit | null,
sessionLocationUuid: string,
abortController?: AbortController,
) {
const now = new Date();
const visitStartDate = parseDate(activeVisit?.startDatetime);
const visitEndDate = parseDate(activeVisit?.stopDatetime);
let encounterDate: Date;
if (!activeVisit || (visitStartDate < now && (!visitEndDate || visitEndDate > now))) {
now;
} else {
console.warn(
'createEmptyEncounter received an active visit that is not currently active. This is a programming error. Attempting to place the order using the visit start date.',
);
visitStartDate;
}
const emptyEncounter = {
patient: patientUuid,
location: sessionLocationUuid,
encounterType: orderEncounterType,
encounterDatetime: encounterDate,
visit: activeVisit?.uuid,
obs: [],
};

return openmrsFetch<OpenmrsResource>(`${restBaseUrl}/encounter`, {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: emptyEncounter,
signal: abortController?.signal,
}).then((res) => res?.data?.uuid);
}

export function postOrder(body: OrderPost, abortController?: AbortController) {
usamaidrsk marked this conversation as resolved.
Show resolved Hide resolved
return openmrsFetch(`${restBaseUrl}/order`, {
method: 'POST',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import { ActionableNotification, Button, ButtonSet, InlineNotification } from '@
import { ExtensionSlot, showModal, showSnackbar, useConfig, useLayoutType, useSession } from '@openmrs/esm-framework';
import {
type DefaultPatientWorkspaceProps,
type OrderBasketItem,
postOrders,
postOrdersOnNewEncounter,
useOrderBasket,
useVisitOrOfflineVisit,
type OrderBasketItem,
} from '@openmrs/esm-patient-common-lib';
import { type ConfigObject } from '../config-schema';
import { createEmptyEncounter, useOrderEncounter, useMutatePatientOrders } from '../api/api';
import { useMutatePatientOrders, useOrderEncounter } from '../api/api';
import styles from './order-basket.scss';

const OrderBasket: React.FC<DefaultPatientWorkspaceProps> = ({
Expand All @@ -34,6 +35,7 @@ const OrderBasket: React.FC<DefaultPatientWorkspaceProps> = ({
error: errorFetchingEncounterUuid,
mutate: mutateEncounterUuid,
} = useOrderEncounter(patientUuid);
const [isSavingOrders, setIsSavingOrders] = useState(false);
const [creatingEncounterError, setCreatingEncounterError] = useState('');
const { mutate: mutateOrders } = useMutatePatientOrders(patientUuid);

Expand All @@ -52,34 +54,41 @@ const OrderBasket: React.FC<DefaultPatientWorkspaceProps> = ({
const abortController = new AbortController();
setCreatingEncounterError('');
let orderEncounterUuid = encounterUuid;
// If there's no encounter present, create an encounter for the order.
setIsSavingOrders(true);
// If there's no encounter present, create an encounter along with the orders.
if (!orderEncounterUuid) {
try {
orderEncounterUuid = await createEmptyEncounter(
await postOrdersOnNewEncounter(
patientUuid,
config?.orderEncounterType,
activeVisitRequired ? activeVisit : null,
session?.sessionLocation?.uuid,
abortController,
);
mutateEncounterUuid();
clearOrders();
await mutateOrders();
closeWorkspaceWithSavedChanges();
showOrderSuccessToast(t, orders);
} catch (e) {
setCreatingEncounterError(e);
console.error(e);
return; // don't try to create the orders if we couldn't create the encounter
setCreatingEncounterError(
e.responseBody.error.message ||
brandones marked this conversation as resolved.
Show resolved Hide resolved
t('tryReopeningTheWorkspaceAgain', 'Please try launching the workspace again'),
);
}
}

const erroredItems = await postOrders(orderEncounterUuid, abortController);
clearOrders({ exceptThoseMatching: (item) => erroredItems.map((e) => e.display).includes(item.display) });
mutateOrders();
if (erroredItems.length == 0) {
closeWorkspaceWithSavedChanges();
showOrderSuccessToast(t, orders);
} else {
setOrdersWithErrors(erroredItems);
const erroredItems = await postOrders(orderEncounterUuid, abortController);
clearOrders({ exceptThoseMatching: (item) => erroredItems.map((e) => e.display).includes(item.display) });
await mutateOrders();
if (erroredItems.length == 0) {
closeWorkspaceWithSavedChanges();
showOrderSuccessToast(t, orders);
} else {
setOrdersWithErrors(erroredItems);
}
}

setIsSavingOrders(false);
return () => abortController.abort();
}, [
activeVisit,
Expand Down Expand Up @@ -116,8 +125,8 @@ const OrderBasket: React.FC<DefaultPatientWorkspaceProps> = ({
{(creatingEncounterError || errorFetchingEncounterUuid) && (
<InlineNotification
kind="error"
title={t('errorCreatingAnEncounter', 'Error when creating an encounter')}
subtitle={t('tryReopeningTheWorkspaceAgain', 'Please try launching the workspace again')}
Copy link
Member

Choose a reason for hiding this comment

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

I think it's best to show the original message here instead of the error message from the backend, which we're already logging to the console on line 67.

Copy link
Member Author

Choose a reason for hiding this comment

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

I think that's right.
Just what I thought that given on creating the encounter we're adding orders too, then if the error was from the orders, showing the exact message might be helpful to the user what exactly is the issue.

Copy link
Contributor

Choose a reason for hiding this comment

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

Dennis may be the leading authority on UI copy; I would defer to him @usamaidrsk .

title={t('errorCreatingAnEncounter', 'Error creating an encounter')}
subtitle={creatingEncounterError}
lowContrast={true}
className={styles.inlineNotification}
/>
Expand All @@ -132,14 +141,15 @@ const OrderBasket: React.FC<DefaultPatientWorkspaceProps> = ({
/>
))}
<ButtonSet className={styles.buttonSet}>
<Button className={styles.bottomButton} kind="secondary" onClick={handleCancel}>
<Button className={styles.bottomButton} disabled={isSavingOrders} kind="secondary" onClick={handleCancel}>
{t('cancel', 'Cancel')}
</Button>
<Button
className={styles.bottomButton}
kind="primary"
onClick={handleSave}
disabled={
isSavingOrders ||
!orders?.length ||
isLoadingEncounterUuid ||
(activeVisitRequired && !activeVisit) ||
Expand Down
Loading