-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathencounter-form-processor.ts
More file actions
382 lines (365 loc) · 13.9 KB
/
encounter-form-processor.ts
File metadata and controls
382 lines (365 loc) · 13.9 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import { useEffect, useState } from 'react';
import { type OpenmrsResource, showSnackbar, translateFrom } from '@openmrs/esm-framework';
import {
getMutableSessionProps,
hydrateRepeatField,
inferInitialValueFromDefaultFieldValue,
prepareEncounter,
preparePatientIdentifiers,
preparePatientPrograms,
saveAttachments,
savePatientIdentifiers,
savePatientPrograms,
} from './encounter-processor-helper';
import {
type Appointment,
type FormField,
type FormPage,
type FormProcessorContextProps,
type FormSchema,
type FormSection,
type ValueAndDisplay,
} from '../../types';
import { evaluateAsyncExpression, type FormNode } from '../../utils/expression-runner';
import { extractErrorMessagesFromResponse } from '../../utils/error-utils';
import { extractObsValueAndDisplay } from '../../utils/form-helper';
import { FormProcessor } from '../form-processor';
import { addFulfillingEncounters, getPreviousEncounter, saveEncounter } from '../../api';
import { hasRendering } from '../../utils/common-utils';
import { isEmpty } from '../../validators/form-validator';
import { formEngineAppName } from '../../globals';
import { type FormContextProps } from '../../provider/form-provider';
import { useEncounter } from '../../hooks/useEncounter';
import { useEncounterRole } from '../../hooks/useEncounterRole';
import { usePatientPrograms } from '../../hooks/usePatientPrograms';
function useCustomHooks(context: Partial<FormProcessorContextProps>) {
const [isLoading, setIsLoading] = useState(true);
const { encounter, isLoading: isLoadingEncounter } = useEncounter(context.formJson);
const { encounterRole, isLoading: isLoadingEncounterRole } = useEncounterRole();
const { isLoadingPatientPrograms, patientPrograms } = usePatientPrograms(context.patient?.id, context.formJson);
useEffect(() => {
setIsLoading(isLoadingPatientPrograms || isLoadingEncounter || isLoadingEncounterRole);
}, [isLoadingPatientPrograms, isLoadingEncounter, isLoadingEncounterRole]);
return {
data: { encounter, patientPrograms, encounterRole },
isLoading,
error: null,
updateContext: (setContext: React.Dispatch<React.SetStateAction<FormProcessorContextProps>>) => {
setContext((context) => {
context.processor.domainObjectValue = encounter as OpenmrsResource;
return {
...context,
domainObjectValue: encounter as OpenmrsResource,
customDependencies: {
...context.customDependencies,
patientPrograms: patientPrograms,
defaultEncounterRole: encounterRole,
},
};
});
},
};
}
const emptyValues = {
checkbox: [],
toggle: false,
text: '',
};
const contextInitializableTypes = [
'encounterProvider',
'encounterDatetime',
'encounterLocation',
'patientIdentifier',
'encounterRole',
'programState',
];
export class EncounterFormProcessor extends FormProcessor {
prepareFormSchema(schema: FormSchema) {
schema.pages.forEach((page) => {
page.sections.forEach((section) => {
section.questions.forEach((question) => {
prepareFormField(question, section, page, schema);
});
});
});
function prepareFormField(field: FormField, section: FormSection, page: FormPage, schema: FormSchema) {
// inherit inlineRendering and readonly from parent section and page if not set
field.inlineRendering =
field.inlineRendering ?? section.inlineRendering ?? page.inlineRendering ?? schema.inlineRendering;
field.readonly = field.readonly ?? section.readonly ?? page.readonly ?? schema.readonly;
if (field.questionOptions?.rendering == 'fixed-value' && !field.meta.fixedValue) {
field.meta.fixedValue = field.value;
delete field.value;
}
if (field.questionOptions?.rendering == 'group' || field.type === 'obsGroup') {
field.questions?.forEach((child) => {
child.readonly = child.readonly ?? field.readonly;
return prepareFormField(child, section, page, schema);
});
}
}
return schema;
}
async processSubmission(context: FormContextProps, appointments: Array<Appointment>, abortController: AbortController) {
const { encounterRole, encounterProvider, encounterDate, encounterLocation } = getMutableSessionProps(context);
const translateFn = (key, defaultValue?) => translateFrom(formEngineAppName, key, defaultValue);
const patientIdentifiers = preparePatientIdentifiers(context.formFields, encounterLocation);
const encounter = prepareEncounter(context, encounterDate, encounterRole, encounterProvider, encounterLocation);
// save patient identifiers
try {
await Promise.all(savePatientIdentifiers(context.patient, patientIdentifiers));
if (patientIdentifiers?.length) {
showSnackbar({
title: translateFn('patientIdentifiersSaved', 'Patient identifier(s) saved successfully'),
kind: 'success',
isLowContrast: true,
});
}
} catch (error) {
const errorMessages = extractErrorMessagesFromResponse(error);
return Promise.reject({
title: translateFn('errorSavingPatientIdentifiers', 'Error saving patient identifiers'),
description: errorMessages.join(', '),
kind: 'error',
critical: true,
});
}
// save patient programs
try {
const programs = preparePatientPrograms(
context.formFields,
context.patient,
context.customDependencies.patientPrograms,
);
const savedPrograms = await await savePatientPrograms(programs);
if (savedPrograms?.length) {
showSnackbar({
title: translateFn('patientProgramsSaved', 'Patient program(s) saved successfully'),
kind: 'success',
isLowContrast: true,
});
}
} catch (error) {
const errorMessages = extractErrorMessagesFromResponse(error);
return Promise.reject({
title: translateFn('errorSavingPatientPrograms', 'Error saving patient program(s)'),
description: errorMessages.join(', '),
kind: 'error',
critical: true,
});
}
// save encounter
try {
const { data: savedEncounter } = await saveEncounter(abortController, encounter, encounter.uuid);
const savedOrders = savedEncounter.orders.map((order) => order.orderNumber);
const savedDiagnoses = savedEncounter.diagnoses.map((diagnosis) => diagnosis.display);
if (savedOrders.length) {
showSnackbar({
title: translateFn('ordersSaved', 'Order(s) saved successfully'),
subtitle: savedOrders.join(', '),
kind: 'success',
isLowContrast: true,
});
}
// handle diagnoses
if (savedDiagnoses.length) {
showSnackbar({
title: translateFn('diagnosisSaved', 'Diagnosis(es) saved successfully'),
subtitle: savedDiagnoses.join(', '),
kind: 'success',
isLowContrast: true,
});
}
// handle attachments
try {
const attachmentsResponse = await Promise.all(
saveAttachments(context.formFields, savedEncounter, abortController),
);
if (attachmentsResponse?.length) {
showSnackbar({
title: translateFn('attachmentsSaved', 'Attachment(s) saved successfully'),
kind: 'success',
isLowContrast: true,
});
}
} catch (error) {
const errorMessages = extractErrorMessagesFromResponse(error);
return Promise.reject({
title: translateFn('errorSavingAttachments', 'Error saving attachment(s)'),
description: errorMessages.join(', '),
kind: 'error',
critical: true,
});
}
// handle appointments
try {
const {appointments: myAppointments} = context
const appointmentsResponse = await Promise.all(addFulfillingEncounters(abortController, appointments, savedEncounter.uuid));
if (appointmentsResponse?.length) {
showSnackbar({
title: translateFn('appointmentsSaved', 'Appointment(s) saved successfully'),
kind: 'success',
isLowContrast: true,
});
}
} catch (error) {
const errorMessages = Array.isArray(error) ? error.map((err) => err.message) : [error.message];
return Promise.reject({
title: translateFn('errorSavingAppointments', 'Error saving appointment(s)'),
description: errorMessages.join(', '),
kind: 'error',
critical: true,
});
}
return savedEncounter;
} catch (error) {
const errorMessages = extractErrorMessagesFromResponse(error);
return Promise.reject({
title: translateFn('errorSavingEncounter', 'Error saving encounter'),
description: errorMessages.join(', '),
kind: 'error',
critical: true,
});
}
}
getCustomHooks() {
return { useCustomHooks };
}
async getInitialValues(context: FormProcessorContextProps) {
const { domainObjectValue: encounter, formFields, formFieldAdapters } = context;
const initialValues = {};
const repeatableFields = [];
if (encounter) {
await Promise.all(
formFields.map(async (field) => {
const adapter = formFieldAdapters[field.type];
if (field.meta.initialValue?.omrsObject && !isEmpty(field.meta.initialValue.refinedValue)) {
initialValues[field.id] = field.meta.initialValue.refinedValue;
return;
}
if (adapter) {
if (hasRendering(field, 'repeating') && !field.meta?.repeat?.isClone) {
repeatableFields.push(field);
}
let value = null;
try {
value = await adapter.getInitialValue(field, encounter, context);
field.meta.initialValue.refinedValue = value;
} catch (error) {
console.error(error);
}
if (field.type === 'obsGroup') {
return;
}
if (!isEmpty(value)) {
initialValues[field.id] = value;
} else if (!isEmpty(field.questionOptions.defaultValue)) {
initialValues[field.id] = inferInitialValueFromDefaultFieldValue(field);
} else {
initialValues[field.id] = emptyValues[field.questionOptions.rendering] ?? '';
}
if (field.questionOptions.calculate?.calculateExpression) {
try {
await evaluateCalculateExpression(field, initialValues, context);
} catch (error) {
console.error(error);
}
}
} else {
console.warn(`No adapter found for field type ${field.type}`);
}
}),
);
const flattenedRepeatableFields = await Promise.all(
repeatableFields.flatMap((field) => hydrateRepeatField(field, encounter, initialValues, context)),
).then((results) => results.flat());
formFields.push(...flattenedRepeatableFields);
} else {
const filteredFields = formFields.filter(
(field) => field.questionOptions.rendering !== 'group' && field.type !== 'obsGroup',
);
const fieldsWithCalculateExpressions = [];
await Promise.all(
filteredFields.map(async (field) => {
const adapter = formFieldAdapters[field.type];
initialValues[field.id] = emptyValues[field.questionOptions.rendering] ?? null;
if (isEmpty(initialValues[field.id]) && contextInitializableTypes.includes(field.type)) {
try {
initialValues[field.id] = await adapter.getInitialValue(field, null, context);
} catch (error) {
console.error(error);
}
}
if (field.questionOptions.calculate?.calculateExpression) {
fieldsWithCalculateExpressions.push(field);
}
}),
);
await Promise.all(
fieldsWithCalculateExpressions.map(async (field) => {
try {
await evaluateCalculateExpression(field, initialValues, context);
} catch (error) {
console.error(error);
}
}),
);
}
return initialValues;
}
async loadDependencies(
context: FormContextProps,
setContext: React.Dispatch<React.SetStateAction<FormProcessorContextProps>>,
) {
const { patient, formJson } = context;
const encounter = await getPreviousEncounter(patient?.id, formJson.encounterType);
setContext((context) => {
return {
...context,
previousDomainObjectValue: encounter,
};
});
return context;
}
async getHistoricalValue(field: FormField, context: FormContextProps): Promise<ValueAndDisplay> {
const {
formFields,
sessionMode,
patient,
methods: { getValues },
formFieldAdapters,
previousDomainObjectValue,
} = context;
const node: FormNode = { value: field, type: 'field' };
const adapter = formFieldAdapters[field.type];
if (field.historicalExpression) {
const value = await evaluateAsyncExpression(field.historicalExpression, node, formFields, getValues(), {
mode: sessionMode,
patient: patient,
previousEncounter: previousDomainObjectValue,
});
return value ? extractObsValueAndDisplay(field, value) : null;
}
if (previousDomainObjectValue && field.questionOptions.enablePreviousValue) {
return await adapter.getPreviousValue(field, previousDomainObjectValue, context);
}
return null;
}
}
async function evaluateCalculateExpression(
field: FormField,
values: Record<string, any>,
formContext: FormProcessorContextProps,
) {
const { formFields, sessionMode, patient } = formContext;
const expression = field.questionOptions.calculate.calculateExpression;
const node: FormNode = { value: field, type: 'field' };
const context = {
mode: sessionMode,
patient: patient,
};
const value = await evaluateAsyncExpression(expression, node, formFields, values, context);
if (!isEmpty(value)) {
values[field.id] = value;
}
}