-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPopulationCalculation.tsx
More file actions
334 lines (320 loc) · 13.1 KB
/
Copy pathPopulationCalculation.tsx
File metadata and controls
334 lines (320 loc) · 13.1 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
import { Button, Center, Drawer, Group, Modal, Tooltip } from '@mantine/core';
import { useRecoilValue } from 'recoil';
import { Calculator, CalculatorTypes } from 'fqm-execution';
import { patientTestCaseState } from '../../state/atoms/patientTestCase';
import { measureBundleState } from '../../state/atoms/measureBundle';
import { useState } from 'react';
import { measurementPeriodFormattedState } from '../../state/atoms/measurementPeriod';
import { showNotification } from '@mantine/notifications';
import { IconAlertCircle, IconCircleCheck } from '@tabler/icons';
import { getPatientInfoString, getPatientNameString } from '../../util/fhir/patient';
import { createDataExchangeMeasureReport, createPatientBundle } from '../../util/fhir/resourceCreation';
import PopulationResultTable, { LabeledDetailedResult } from './PopulationResultsTable';
import { DetailedResult } from '../../util/types';
import { useRouter } from 'next/router';
import { trustMetaProfileState } from '../../state/atoms/trustMetaProfile';
import { useDisclosure } from '@mantine/hooks';
import { evaluationState } from '../../state/atoms/evaluation';
import { dataRequirementsLookupByType } from '../../state/selectors/dataRequirementsLookupByType';
import { minimizeTestCaseResources } from '../../util/ValueSetHelper';
export default function PopulationCalculation() {
const router = useRouter();
const currentPatients = useRecoilValue(patientTestCaseState);
const measureBundle = useRecoilValue(measureBundleState);
const measurementPeriodFormatted = useRecoilValue(measurementPeriodFormattedState);
const { evaluationServiceUrl, evaluationMeasureId } = useRecoilValue(evaluationState);
const drLookupByType = useRecoilValue(dataRequirementsLookupByType);
const [detailedResults, setDetailedResults] = useState<LabeledDetailedResult[]>([]);
const [drawerOpened, setDrawerOpened] = useState(false);
const [opened, { open, close }] = useDisclosure(false);
const [enableTableButton, setEnableTableButton] = useState(false);
const [enableClauseCoverageButton, setEnableClauseCoverageButton] = useState(false);
const [enableEvaluateButton, setEnableEvaluateButton] = useState(false);
const [clauseCoverageHTML, setClauseCoverageHTML] = useState<string | null>(null);
const [clauseUncoverageHTML, setClauseUncoverageHTML] = useState<string | null>(null);
const trustMetaProfile = useRecoilValue(trustMetaProfileState);
/**
* Creates object that maps patient ids to their name/DOB info strings.
* @returns { Object } mapping of patient ids to patient info labels
*/
const createPatientLabels = () => {
const patientLabels: Record<string, string> = {};
Object.keys(currentPatients).forEach(id => {
patientLabels[id] = getPatientInfoString(currentPatients[id].patient);
});
return patientLabels;
};
/**
* POSTS patient data in conformance with https://build.fhir.org/ig/HL7/davinci-deqm/OperationDefinition-submit-data.html
* without using Measure/$deqm-submit-data endpoint
* Each transaction bundle should contain DEQM Data Exchange MeasureReports with data-of-interest
* and should be for a single subject (will do a separate POST for each patient)
* @returns { string|undefined[] } the evaluation service ids for POSTed patients (may be different than sent IDs or undefined if send was unsuccessful)
*/
const submitDataToEvaluationService = async (): Promise<(string | undefined)[]> => {
// collect data and POST to evaluation service (TODO: should be $submit-data when available)
const measure = measureBundle.content?.entry?.find(e => e.resource?.resourceType === 'Measure')
?.resource as fhir4.Measure;
const postedIds: Promise<string | undefined>[] = Object.keys(currentPatients).map(async id => {
const bundle = createPatientBundle(
currentPatients[id].patient,
minimizeTestCaseResources(currentPatients[id], measureBundle.content, drLookupByType),
currentPatients[id].fullUrl,
createDataExchangeMeasureReport(measure, measurementPeriodFormatted as fhir4.Period, id)
);
const response = await fetch(`${evaluationServiceUrl}/`, {
method: 'POST',
body: JSON.stringify(bundle),
headers: { 'Content-Type': 'application/json+fhir' }
});
const responseBody: fhir4.Bundle | fhir4.OperationOutcome = await response.json();
if (responseBody.resourceType === 'OperationOutcome') {
showNotification({
icon: <IconAlertCircle />,
title: 'Patient data submission failed',
message: `Submitting data for Patient: ${getPatientNameString(
currentPatients[id].patient
)} failed with details: "${responseBody.issue[0].details?.text ?? response.status}"`,
color: 'red'
});
return;
}
// should return transaction response bundles from which we can pull the posted patient id
return responseBody.entry
?.find(e => e.response?.location?.includes('Patient/'))
?.response?.location?.split('Patient/')[1];
});
return Promise.all(postedIds);
};
/**
* Wrapper function that calls submitDataToEvaluationService() and resolves patient data for future evaluation
*/
const submitData = () => {
submitDataToEvaluationService()
.then(postedIds => {
const resolvedIds = postedIds?.filter(id => id !== undefined);
if (resolvedIds.length > 0) {
showNotification({
icon: <IconCircleCheck />,
title: 'Successfully sent data',
message: `Successfully sent data for ${resolvedIds.length} patients for measure ${evaluationMeasureId}`, //TODO: update to canonical, currently using evaluationMeasureId here whereas it will be used for $submit-data in the future
color: 'green'
});
// TODO: use resolvedIds to populate evaluate modal
setEnableEvaluateButton(true);
} else {
showNotification({
icon: <IconAlertCircle />,
title: 'No patient information',
message: 'No patient information was successfully POSTed to the Evaluation Service',
color: 'red'
});
}
})
.catch(e => {
if (e instanceof Error) {
showNotification({
icon: <IconAlertCircle />,
title: 'Data Submission Error',
message: e.message,
color: 'red'
});
}
});
};
/**
* Uses fqm-execution library to perform calculation on all patients and return their
* detailed results.
* @returns { Array | void } array of detailed results (if measure bundle is provided)
*/
const calculateDetailedResults = async (): Promise<DetailedResult[] | void> => {
// specify options for calculation
const options: CalculatorTypes.CalculationOptions = {
calculateHTML: false,
calculateSDEs: true,
calculateClauseCoverage: true,
calculateClauseUncoverage: true,
reportType: 'individual',
measurementPeriodStart: measurementPeriodFormatted?.start,
measurementPeriodEnd: measurementPeriodFormatted?.end,
trustMetaProfile: trustMetaProfile
};
// get all patient bundles as array to feed into fqm-execution
const patientBundles: fhir4.Bundle[] = [];
Object.keys(currentPatients).forEach(id => {
const bundle = createPatientBundle(currentPatients[id].patient, currentPatients[id].resources);
patientBundles.push(bundle);
});
if (measureBundle.content) {
const { results, groupClauseCoverageHTML, groupClauseUncoverageHTML } = await Calculator.calculate(
measureBundle.content,
patientBundles,
options
);
if (groupClauseCoverageHTML) {
setClauseCoverageHTML(JSON.stringify(groupClauseCoverageHTML));
}
if (groupClauseUncoverageHTML) {
setClauseUncoverageHTML(JSON.stringify(groupClauseUncoverageHTML));
}
return results;
} else return;
};
/**
* Wrapper function that calls calculateDetailedResults() and creates the LabeledDetailedResult that will be used to render
* the population results. Catches errors in fqm-execution that result from calculateDetailedResults().
*/
const runCalculation = () => {
calculateDetailedResults()
.then(detailedResults => {
if (detailedResults) {
const patientLabels = createPatientLabels();
const labeledDetailedResults: LabeledDetailedResult[] = [];
detailedResults.forEach(dr => {
const patientId = dr.patientId;
labeledDetailedResults.push({
label: patientId ? patientLabels[patientId] : '',
detailedResult: dr as DetailedResult
});
});
setDetailedResults(labeledDetailedResults);
setDrawerOpened(true);
setEnableTableButton(true);
setEnableClauseCoverageButton(true);
}
})
.catch(e => {
if (e instanceof Error) {
showNotification({
icon: <IconAlertCircle />,
title: 'Calculation Error',
message: e.message,
color: 'red'
});
}
});
};
return (
<>
{Object.keys(currentPatients).length > 0 && measureBundle.content && (
<Center>
<Group position="center">
<Button
data-testid="calculate-all-button"
aria-label="Calculate Population Results"
styles={{ root: { marginTop: 20 } }}
onClick={() => runCalculation()}
variant="outline"
>
Calculate Population Results
</Button>
<Tooltip
label="Disabled until calculation results are available"
openDelay={1000}
disabled={enableTableButton ? true : false}
>
<Button
data-testid="show-table-button"
aria-label="Show Table"
styles={{ root: { marginTop: 20 } }}
disabled={!enableTableButton}
onClick={() => setDrawerOpened(true)}
variant="outline"
>
Show Table
</Button>
</Tooltip>
<Tooltip
label="Disabled until calculation results are available"
openDelay={1000}
disabled={enableClauseCoverageButton}
>
<Button
data-testid="show-coverage-button"
aria-label="Show Clause Coverage"
styles={{ root: { marginTop: 20 } }}
disabled={!enableClauseCoverageButton}
variant="outline"
onClick={() => {
if (measureBundle.content) {
router.push(
{
pathname: `/${measureBundle.content.id}/coverage`,
query: {
clauseCoverageHTML,
clauseUncoverageHTML
}
},
`/${measureBundle.content.id}/coverage`
);
}
}}
>
Show Clause Coverage
</Button>
</Tooltip>
<Button
data-testid="submit-data-button"
aria-label="Submit Data"
styles={{ root: { marginTop: 20 } }}
onClick={() => submitData()}
variant="outline"
>
Submit Data
</Button>
<Tooltip
label="Disabled until data submission has succeeeded"
openDelay={1000}
disabled={enableEvaluateButton}
>
<Button
data-testid="evaluate-button"
aria-label="Evaluate"
styles={{ root: { marginTop: 20 } }}
disabled={!enableEvaluateButton}
onClick={open}
variant="outline"
>
Evaluate
</Button>
</Tooltip>
</Group>
{detailedResults.length > 0 && (
<>
<Drawer
opened={drawerOpened}
onClose={() => setDrawerOpened(false)}
position="bottom"
padding="md"
overlayProps={{
opacity: 0.3
}}
lockScroll={false}
size="lg"
styles={{
body: {
height: '100%'
}
}}
>
<h2>Population Results</h2>
<div
data-testid="results-table"
style={{
height: '100%',
overflow: 'scroll'
}}
>
<PopulationResultTable results={detailedResults} />
</div>
</Drawer>
</>
)}
<Modal centered size="xl" withCloseButton={true} opened={opened} onClose={close} title="Evaluate">
TODO: Evaluate Modal
</Modal>
</Center>
)}
</>
);
}