-
Notifications
You must be signed in to change notification settings - Fork 206
/
patient-registration.component.tsx
242 lines (227 loc) · 9.92 KB
/
patient-registration.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
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import classNames from 'classnames';
import { Button, InlineLoading, Link } from '@carbon/react';
import { XAxis } from '@carbon/react/icons';
import { useLocation, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Form, Formik, type FormikHelpers } from 'formik';
import {
createErrorHandler,
interpolateUrl,
showSnackbar,
useConfig,
usePatient,
usePatientPhoto,
} from '@openmrs/esm-framework';
import { getValidationSchema } from './validation/patient-registration-validation';
import { type CapturePhotoProps, type FormValues } from './patient-registration.types';
import { PatientRegistrationContext } from './patient-registration-context';
import { type SavePatientForm, SavePatientTransactionManager } from './form-manager';
import { DummyDataInput } from './input/dummy-data/dummy-data-input.component';
import { cancelRegistration, filterOutUndefinedPatientIdentifiers, scrollIntoView } from './patient-registration-utils';
import { useInitialAddressFieldValues, useInitialFormValues, usePatientUuidMap } from './patient-registration-hooks';
import { ResourcesContext } from '../offline.resources';
import { builtInSections, type RegistrationConfig, type SectionDefinition } from '../config-schema';
import { SectionWrapper } from './section/section-wrapper.component';
import BeforeSavePrompt from './before-save-prompt';
import styles from './patient-registration.scss';
let exportedInitialFormValuesForTesting = {} as FormValues;
export interface PatientRegistrationProps {
savePatientForm: SavePatientForm;
isOffline: boolean;
}
export const PatientRegistration: React.FC<PatientRegistrationProps> = ({ savePatientForm, isOffline }) => {
const { currentSession, identifierTypes } = useContext(ResourcesContext);
const { search } = useLocation();
const config = useConfig() as RegistrationConfig;
const [target, setTarget] = useState<undefined | string>();
const { patientUuid: uuidOfPatientToEdit } = useParams();
const { isLoading: isLoadingPatientToEdit, patient: patientToEdit } = usePatient(uuidOfPatientToEdit);
const { t } = useTranslation();
const [capturePhotoProps, setCapturePhotoProps] = useState<CapturePhotoProps | null>(null);
const [initialFormValues, setInitialFormValues] = useInitialFormValues(uuidOfPatientToEdit);
const [initialAddressFieldValues] = useInitialAddressFieldValues(uuidOfPatientToEdit);
const [patientUuidMap] = usePatientUuidMap(uuidOfPatientToEdit);
const location = currentSession?.sessionLocation?.uuid;
const inEditMode = isLoadingPatientToEdit ? undefined : !!(uuidOfPatientToEdit && patientToEdit);
const showDummyData = useMemo(() => localStorage.getItem('openmrs:devtools') === 'true' && !inEditMode, [inEditMode]);
const { data: photo } = usePatientPhoto(patientToEdit?.id);
const savePatientTransactionManager = useRef(new SavePatientTransactionManager());
const fieldDefinition = config?.fieldDefinitions?.filter((def) => def.type === 'address');
const validationSchema = getValidationSchema(config);
useEffect(() => {
exportedInitialFormValuesForTesting = initialFormValues;
}, [initialFormValues]);
const sections: Array<SectionDefinition> = useMemo(() => {
return config.sections
.map(
(sectionName) =>
config.sectionDefinitions.filter((s) => s.id == sectionName)[0] ??
builtInSections.filter((s) => s.id == sectionName)[0],
)
.filter((s) => s);
}, [config.sections, config.sectionDefinitions]);
const onFormSubmit = async (values: FormValues, helpers: FormikHelpers<FormValues>) => {
const abortController = new AbortController();
helpers.setSubmitting(true);
const updatedFormValues = { ...values, identifiers: filterOutUndefinedPatientIdentifiers(values.identifiers) };
try {
await savePatientForm(
!inEditMode,
updatedFormValues,
patientUuidMap,
initialAddressFieldValues,
capturePhotoProps,
location,
initialFormValues['identifiers'],
currentSession,
config,
savePatientTransactionManager.current,
abortController,
);
showSnackbar({
subtitle: inEditMode
? t('updatePatientSuccessSnackbarSubtitle', "The patient's information has been successfully updated")
: t(
'registerPatientSuccessSnackbarSubtitle',
'The patient can now be found by searching for them using their name or ID number',
),
title: inEditMode
? t('updatePatientSuccessSnackbarTitle', 'Patient Details Updated')
: t('registerPatientSuccessSnackbarTitle', 'New Patient Created'),
kind: 'success',
isLowContrast: true,
});
const afterUrl = new URLSearchParams(search).get('afterUrl');
const redirectUrl = interpolateUrl(afterUrl || config.links.submitButton, { patientUuid: values.patientUuid });
setTarget(redirectUrl);
} catch (error) {
if (error.responseBody?.error?.globalErrors) {
error.responseBody.error.globalErrors.forEach((error) => {
showSnackbar({
title: inEditMode
? t('updatePatientErrorSnackbarTitle', 'Patient Details Update Failed')
: t('registrationErrorSnackbarTitle', 'Patient Registration Failed'),
subtitle: error.message,
kind: 'error',
});
});
} else if (error.responseBody?.error?.message) {
showSnackbar({
title: inEditMode
? t('updatePatientErrorSnackbarTitle', 'Patient Details Update Failed')
: t('registrationErrorSnackbarTitle', 'Patient Registration Failed'),
subtitle: error.responseBody.error.message,
kind: 'error',
});
} else {
createErrorHandler()(error);
}
helpers.setSubmitting(false);
}
};
const getDescription = (errors) => {
return (
<ul style={{ listStyle: 'inside' }}>
{Object.keys(errors).map((error, index) => {
return <li key={index}>{t(`${error}LabelText`, error)}</li>;
})}
</ul>
);
};
const displayErrors = (errors) => {
if (errors && typeof errors === 'object' && !!Object.keys(errors).length) {
showSnackbar({
isLowContrast: true,
kind: 'warning',
title: t('fieldsWithErrors', 'The following fields have errors:'),
subtitle: <>{getDescription(errors)}</>,
});
}
};
return (
<Formik
enableReinitialize
initialValues={initialFormValues}
validationSchema={validationSchema}
onSubmit={onFormSubmit}>
{(props) => (
<Form className={styles.form}>
<BeforeSavePrompt when={props.dirty} redirect={target} />
<div className={styles.formContainer}>
<div>
<div className={styles.stickyColumn}>
<h4>
{inEditMode
? t('editPatientDetails', 'Edit patient details')
: t('createNewPatient', 'Create new patient')}
</h4>
{showDummyData && <DummyDataInput setValues={props.setValues} />}
<p className={styles.label01}>{t('jumpTo', 'Jump to')}</p>
{sections.map((section) => (
<div className={classNames(styles.space05, styles.touchTarget)} key={section.name}>
<Link className={styles.linkName} onClick={() => scrollIntoView(section.id)}>
<XAxis size={16} /> {t(`${section.id}Section`, section.name)}
</Link>
</div>
))}
<Button
className={styles.submitButton}
type="submit"
onClick={() => props.validateForm().then((errors) => displayErrors(errors))}
// Current session and identifiers are required for patient registration.
// If currentSession or identifierTypes are not available, then the
// user should be blocked to register the patient.
disabled={!currentSession || !identifierTypes || props.isSubmitting}>
{props.isSubmitting ? (
<InlineLoading
className={styles.spinner}
description={`${t('submitting', 'Submitting')} ...`}
iconDescription="submitting"
/>
) : inEditMode ? (
t('updatePatient', 'Update patient')
) : (
t('registerPatient', 'Register patient')
)}
</Button>
<Button className={styles.cancelButton} kind="tertiary" onClick={cancelRegistration}>
{t('cancel', 'Cancel')}
</Button>
</div>
</div>
<div className={styles.infoGrid}>
<PatientRegistrationContext.Provider
value={{
identifierTypes: identifierTypes,
validationSchema,
values: props.values,
inEditMode,
setFieldValue: props.setFieldValue,
setFieldTouched: props.setFieldTouched,
setCapturePhotoProps,
currentPhoto: photo?.imageSrc,
isOffline,
initialFormValues: props.initialValues,
setInitialFormValues,
}}>
{sections.map((section, index) => (
<SectionWrapper
key={`registration-section-${section.id}`}
sectionDefinition={section}
index={index}
/>
))}
</PatientRegistrationContext.Provider>
</div>
</div>
</Form>
)}
</Formik>
);
};
/**
* @internal
* Just exported for testing
*/
export { exportedInitialFormValuesForTesting as initialFormValues };