-
Notifications
You must be signed in to change notification settings - Fork 198
/
add-patient.component.tsx
271 lines (249 loc) · 9.18 KB
/
add-patient.component.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import classNames from 'classnames';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
import useSWR from 'swr';
import { Button, Checkbox, Pagination, Search, CheckboxSkeleton } from '@carbon/react';
import {
getDynamicOfflineDataEntries,
putDynamicOfflineData,
syncDynamicOfflineData,
showSnackbar,
toOmrsIsoString,
usePagination,
navigate,
useConfig,
} from '@openmrs/esm-framework';
import { addPatientToList, getAllPatientLists, getPatientListIdsForPatient } from '../api/api-remote';
import { type ConfigSchema } from '../config-schema';
import styles from './add-patient.scss';
interface AddPatientProps {
closeModal: () => void;
patientUuid: string;
}
interface AddablePatientListViewModel {
addPatient(): Promise<void>;
displayName: string;
checked?: boolean;
id: string;
}
const AddPatient: React.FC<AddPatientProps> = ({ closeModal, patientUuid }) => {
const { t } = useTranslation();
const [searchValue, setSearchValue] = useState('');
const [selected, setSelected] = useState<Array<string>>([]);
const { data, isLoading } = useAddablePatientLists(patientUuid);
const handleCreateNewList = () => {
navigate({
to: window.getOpenmrsSpaBase() + 'home/patient-lists?new_cohort=true',
});
closeModal();
};
const handleSelectionChanged = useCallback((patientListId: string, listSelected: boolean) => {
if (listSelected) {
setSelected((prev) => [...prev, patientListId]);
} else {
setSelected((prev) => prev.filter((x) => x !== patientListId));
}
}, []);
const handleSubmit = useCallback(() => {
for (const selectedId of selected) {
const patientList = data.find((list) => list.id === selectedId);
if (!patientList) {
continue;
}
patientList
.addPatient()
.then(() =>
showSnackbar({
title: t('successfullyAdded', 'Successfully added'),
kind: 'success',
isLowContrast: true,
subtitle: `${t('successAddPatientToList', 'Patient added to list')}: ${patientList.displayName}`,
}),
)
.catch(() =>
showSnackbar({
title: t('error', 'Error'),
kind: 'error',
subtitle: `${t('errorAddPatientToList', 'Patient not added to list')}: ${patientList.displayName}`,
}),
);
}
closeModal();
}, [data, selected, closeModal, t]);
const searchResults = useMemo(() => {
if (!data) {
return [];
}
if (searchValue?.trim().length > 0) {
const search = searchValue.toLowerCase();
return data.filter((patientList) => patientList.displayName.toLowerCase().includes(search));
}
return data;
}, [searchValue, data]);
const { results, goTo, currentPage, paginated } = usePagination(searchResults, 5);
useEffect(() => {
if (currentPage !== 1) {
goTo(1);
}
}, [searchValue]);
return (
<div className={styles.modalContent}>
<div className={styles.modalHeader}>
<h1 className={styles.productiveHeading03}>{t('addPatientToList', 'Add patient to list')}</h1>
<h3 className={styles.bodyLong01} style={{ margin: '1rem 0' }}>
{t('searchForAListToAddThisPatientTo', 'Search for a list to add this patient to.')}
</h3>
</div>
<div style={{ marginBottom: '0.875rem' }}>
<Search
style={{ backgroundColor: 'white', borderBottom: '1px solid #e0e0e0' }}
labelText={t('searchForList', 'Search for a list')}
placeholder="Filter list"
onChange={({ target }) => {
setSearchValue(target.value);
}}
value={searchValue}
/>
</div>
<div className={styles.patientListList}>
<fieldset className="cds--fieldset">
<p className="cds--label">{t('patientLists', 'Patient lists')}</p>
{!isLoading && results ? (
results.length > 0 ? (
results.map((patientList) => (
<div key={patientList.id} className={styles.checkbox}>
<Checkbox
key={patientList.id}
onChange={(e) => handleSelectionChanged(patientList.id, e.target.checked)}
checked={patientList.checked || selected.includes(patientList.id)}
disabled={patientList.checked}
labelText={patientList.displayName}
id={patientList.id}
/>
</div>
))
) : (
<p className={styles.bodyLong01}>{t('noPatientListFound', 'No patient list found')}</p>
)
) : (
<>
<div className={styles.checkbox}>
<CheckboxSkeleton />
</div>
<div className={styles.checkbox}>
<CheckboxSkeleton />
</div>
<div className={styles.checkbox}>
<CheckboxSkeleton />
</div>
<div className={styles.checkbox}>
<CheckboxSkeleton />
</div>
<div className={styles.checkbox}>
<CheckboxSkeleton />
</div>
</>
)}
</fieldset>
</div>
{paginated && (
<div className={styles.paginationContainer}>
<span className={classNames(styles.itemsCountDisplay, styles.bodyLong01)}>
{results.length * currentPage} / {searchResults.length} {t('items', 'items')}
</span>
<Pagination
className={styles.pagination}
forwardText=""
backwardText=""
page={currentPage}
pageSize={5}
pageSizes={[5]}
totalItems={searchResults.length}
onChange={({ page }) => goTo(page)}
/>
</div>
)}
<div className={styles.buttonSet}>
<Button kind="ghost" size="xl" onClick={handleCreateNewList}>
{t('createNewPatientList', 'Create new patient list')}
</Button>
<div>
<Button kind="secondary" size="xl" onClick={closeModal}>
{t('cancel', 'Cancel')}
</Button>
<Button onClick={handleSubmit} size="xl">
{t('addToList', 'Add to list')}
</Button>
</div>
</div>
</div>
);
};
// This entire modal is a little bit special since it not only displays the "real" patient lists (i.e. data from
// the cohorts/backend), but also a fake patient list which doesn't really exist in the backend:
// The offline patient list.
// When a patient is added to the offline list, that patient should become available offline, i.e.
// a dynamic offline data entry must be created.
// This is why the following abstracts away the differences between the real and the fake patient lists.
// The component doesn't really care about which is which - the only thing that matters is that the
// data can be fetched and that there is an "add patient" function.
export function useAddablePatientLists(patientUuid: string) {
const { t } = useTranslation();
const config = useConfig() as ConfigSchema;
return useSWR(['addablePatientLists', patientUuid], async () => {
// Using Promise.allSettled instead of Promise.all here because some distros might not have the
// cohort module installed, leading to the real patient list call failing.
// In that case we still want to show fake lists and *not* error out here.
const [fakeLists, realLists] = await Promise.allSettled([
findFakePatientListsWithoutPatient(patientUuid, t),
findRealPatientListsWithoutPatient(patientUuid, config.myListCohortTypeUUID, config.systemListCohortTypeUUID),
]);
return [
...(fakeLists.status === 'fulfilled' ? fakeLists.value : []),
...(realLists.status === 'fulfilled' ? realLists.value : []),
];
});
}
async function findRealPatientListsWithoutPatient(
patientUuid: string,
myListCohortUUID,
systemListCohortType,
): Promise<Array<AddablePatientListViewModel>> {
const [allLists, listsIdsOfThisPatient] = await Promise.all([
getAllPatientLists({}, myListCohortUUID, systemListCohortType),
getPatientListIdsForPatient(patientUuid),
]);
return allLists.map((list) => ({
id: list.id,
displayName: list.display,
checked: listsIdsOfThisPatient.includes(list.id),
async addPatient() {
await addPatientToList({
cohort: list.id,
patient: patientUuid,
startDate: toOmrsIsoString(new Date()),
});
},
}));
}
async function findFakePatientListsWithoutPatient(
patientUuid: string,
t: TFunction,
): Promise<Array<AddablePatientListViewModel>> {
const offlinePatients = await getDynamicOfflineDataEntries('patient');
const isPatientOnOfflineList = offlinePatients.some((x) => x.identifier === patientUuid);
return isPatientOnOfflineList
? []
: [
{
id: 'fake-offline-patient-list',
displayName: t('offlinePatients', 'Offline patients'),
async addPatient() {
await putDynamicOfflineData('patient', patientUuid);
await syncDynamicOfflineData('patient', patientUuid);
},
},
];
}
export default AddPatient;