-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresponseMapper.ts
More file actions
277 lines (244 loc) · 9.42 KB
/
responseMapper.ts
File metadata and controls
277 lines (244 loc) · 9.42 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
import {
Bundle,
FhirResource,
RequestGroup,
Patient,
MedicationRequest,
MedicationDispense,
RequestGroupAction
} from "fhir/r4"
import {DoHSData} from "./types"
import {
mapPrescriptionOrigin,
extractPatientDetails,
mapMessageHistoryTitleToMessageCode,
extractItems
} from "./fhirMappers"
import {
findExtensionByKey,
findExtensionsByKey,
getBooleanFromNestedExtension,
getIntegerFromNestedExtension,
PrescriptionOdsCodes
} from "./extensionUtils"
import {
MessageHistory,
DispenseNotificationItem,
OrgSummary,
PrescriptionDetailsResponse
} from "@cpt-ui-common/common-types"
import {DoHSOrg} from "@cpt-ui-common/doHSClient"
import {Logger} from "@aws-lambda-powertools/logger"
/**
* Extracts a specific resource type from the FHIR Bundle
*/
const extractResourcesFromBundle = <T extends FhirResource>(
bundle: Bundle,
resourceType: T["resourceType"]
): Array<T> => {
return bundle.entry!
.filter(entry => entry.resource!.resourceType === resourceType)
.map(entry => entry.resource as T)
}
const extractDispenseNotificationItem = (
request: MedicationRequest,
action: RequestGroupAction,
medicationDispenses: Array<MedicationDispense>
) => {
let dispenses: Array<MedicationDispense> = []
const requestId = request.id
if (requestId && action.action) {
dispenses = action.action.map(action => {
const dispenseReference = action.resource?.reference
if (!dispenseReference) return undefined
return medicationDispenses.find(dispense =>
dispense.id && dispenseReference.includes(dispense.id)
&& dispense.authorizingPrescription?.[0]?.reference?.includes(requestId)
)
}).filter(dispense => dispense !== undefined)
}
return {
statusCode: dispenses[0]?.type?.coding?.[0].code ?? "unknown",
components: dispenses.map(dispense => {
const medicationName = dispense.medicationCodeableConcept?.text
if (!medicationName) return undefined
const quantityValue = dispense.quantity?.value?.toString() ?? ""
const quantityUnit = dispense.quantity?.unit
const quantity = quantityUnit ? `${quantityValue} ${quantityUnit}` : quantityValue
return {
medicationName,
quantity,
dosageInstruction: dispense.dosageInstruction?.[0]?.text
}
}).filter(c => c !== undefined)
}
}
/**
* Extracts message history from RequestGroup actions
*/
const extractMessageHistory = (
requestGroup: RequestGroup,
doHSData: DoHSData,
medicationRequests: Array<MedicationRequest>,
medicationDispenses: Array<MedicationDispense>,
logger?: Logger
): Array<MessageHistory> => {
// find the specific "Prescription status transitions" action
const historyAction = requestGroup.action?.find(action =>
action.title === "Prescription status transitions"
)
if (!historyAction?.action) return []
return historyAction.action.map(action => {
// Find the status coding with the EPS task business status system
const statusCoding = action.code?.find(code =>
code.coding?.some(coding => coding.system === "https://fhir.nhs.uk/CodeSystem/EPS-task-business-status")
)?.coding?.find(coding => coding.system === "https://fhir.nhs.uk/CodeSystem/EPS-task-business-status")
const orgODS = action.participant![0].extension![0].valueReference!.identifier!.value!
const messageCodeDisplayName = action.title!
const messageCode = mapMessageHistoryTitleToMessageCode(messageCodeDisplayName, logger)
let orgName: string | undefined = undefined
// Find organization name from DoHS data if ODS code is present
if (doHSData.prescribingOrganization?.ODSCode === orgODS) {
orgName = doHSData.prescribingOrganization.OrganisationName
} else if (doHSData.nominatedPerformer?.ODSCode === orgODS) {
orgName = doHSData.nominatedPerformer.OrganisationName
} else if (doHSData.dispensingOrganization?.ODSCode === orgODS) {
orgName = doHSData.dispensingOrganization.OrganisationName
}
let dispenseNotificationItems: Array<DispenseNotificationItem> | undefined
// Only populate if this message type should have dispense notification
if (messageCode === "dispense-notified" && action.action && action.action.length > 0) {
dispenseNotificationItems = medicationRequests.map(request => {
return extractDispenseNotificationItem(request, action, medicationDispenses)
})
}
return {
messageCode,
sentDateTime: action.timingDateTime!,
orgName,
orgODS,
newStatusCode: statusCoding?.code ?? "Unknown",
dispenseNotificationItems
}
})
}
/**
* Creates organization summary from DoHS data
*/
const createOrganizationSummary = (
doHSOrg: DoHSOrg | null | undefined,
odsCodeFallback: string,
prescribedFrom?: string
): OrgSummary => {
// If we have an ODS code from either DoHS data or FHIR fallback, create a summary
const telephone = doHSOrg?.Contacts?.find(c =>
c.ContactMethodType === "Telephone"
)?.ContactValue ?? "Not found"
const address = [
doHSOrg?.Address1,
doHSOrg?.City,
doHSOrg?.Postcode
].filter(Boolean).join(", ") || "Not found"
return {
name: doHSOrg?.OrganisationName ?? "",
odsCode: doHSOrg?.ODSCode ?? odsCodeFallback ?? "Not found",
address,
telephone,
...(prescribedFrom && {prescribedFrom})
}
}
/**
* Main function to merge FHIR Bundle data with DoHS data into the required response format
*/
export const mergePrescriptionDetails = (
bundle: Bundle,
doHSData: DoHSData,
{
prescribingOrganization,
nominatedPerformer,
dispensingOrganization
}: PrescriptionOdsCodes,
logger?: Logger
): PrescriptionDetailsResponse => {
// Extract resources from bundle
const requestGroup = extractResourcesFromBundle<RequestGroup>(bundle, "RequestGroup")[0]
const patient = extractResourcesFromBundle<Patient>(bundle, "Patient")[0]
const medicationRequests = extractResourcesFromBundle<MedicationRequest>(bundle, "MedicationRequest")
const firstMedicationRequest = medicationRequests[0]
const medicationDispenses = extractResourcesFromBundle<MedicationDispense>(bundle, "MedicationDispense")
// extract basic prescription details
const prescriptionId = requestGroup.identifier![0].value!
// get prescription type and treatment type
const prescriptionTypeExt = findExtensionByKey(requestGroup.extension, "PRESCRIPTION_TYPE")
const typeCode = firstMedicationRequest
.courseOfTherapyType!
.coding![0]
.code! as PrescriptionDetailsResponse["typeCode"]
const issueDate = requestGroup.authoredOn!
// get repeat information
const repeatInfoExt = findExtensionByKey(requestGroup.extension, "REPEAT_INFORMATION")
const instanceNumber = getIntegerFromNestedExtension(repeatInfoExt, "numberOfRepeatsIssued", 1)
const maxRepeats = getIntegerFromNestedExtension(repeatInfoExt, "numberOfRepeatsAllowed")
// get days supply from RequestGroup timing information
const lineItemsAction = requestGroup.action!.filter(action =>
action.title === "Prescription Line Items(Medications)"
)[0]
const daysSupply = lineItemsAction.timingTiming?.repeat!.period!.toString() ?? "Not applicable"
// get pending cancellation status
const prescriptionPendingCancellation = getBooleanFromNestedExtension(
findExtensionByKey(requestGroup.extension, "PENDING_CANCELLATION"),
"prescriptionPendingCancellation"
)
// extract and format all the data
const patientDetails = extractPatientDetails(patient)
const items = extractItems(medicationRequests, medicationDispenses)
const messageHistory = extractMessageHistory(requestGroup, doHSData, medicationRequests, medicationDispenses, logger)
// TODO: extract NHS App status from dispensing information extension
// const dispensingInfoExt = findExtensionByKey(dispense.extension, "DISPENSING_INFORMATION")
let statusCode
let cancellationReason
const statusExt = findExtensionsByKey(requestGroup.extension, "PRESCRIPTION_STATUS_HISTORY")
for (const ext of statusExt){
const url = ext.extension?.[0].url
const system = ext.extension?.[0].valueCoding?.system
if (url === "status" && system === "https://fhir.nhs.uk/CodeSystem/EPS-task-business-status"){
statusCode = ext?.extension?.[0].valueCoding?.code
}
if (url === "cancellationReason" && system === "https://fhir.nhs.uk/CodeSystem/medicationrequest-status-reason"){
cancellationReason = ext?.extension?.[0].valueCoding?.code
}
}
const nonDispensingExt = findExtensionByKey(requestGroup.extension, "NON_DISPENSING_REASON")
const nonDispensingReason = nonDispensingExt?.valueCoding?.code
// create organization summaries
const prescriptionTypeCode = prescriptionTypeExt?.valueCoding?.code ?? "Unknown"
const prescriberOrg = createOrganizationSummary(
doHSData.prescribingOrganization,
prescribingOrganization,
mapPrescriptionOrigin(prescriptionTypeCode)
)
const nominatedDispenser = nominatedPerformer
? createOrganizationSummary(doHSData.nominatedPerformer, nominatedPerformer)
: undefined
const currentDispenser = dispensingOrganization
? createOrganizationSummary(doHSData.dispensingOrganization, dispensingOrganization)
: undefined
return {
patientDetails,
prescriptionId,
typeCode,
...(statusCode ? {statusCode} : {statusCode: "unknown"}),
issueDate,
instanceNumber,
maxRepeats,
daysSupply,
prescriptionPendingCancellation,
items,
messageHistory,
prescriberOrg,
nominatedDispenser,
currentDispenser,
cancellationReason,
nonDispensingReason
}
}