forked from mcjustin/sof_public_app_testing_2023Q2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
281 lines (252 loc) · 10.5 KB
/
app.js
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
const defaultSectionDisplayFn = listSection;
const defaultItemDisplayFn = simpleItem;
const patientResourceConfig = {
'Patient': {
sectionDisplayFn: patientSection,
},
'AllergyIntolerance': {
title: 'Allergies and Intolerances',
},
// 'MedicationStatement': {}, // Not in EPIC USCDI R4
'MedicationRequest': {},
// 'Medication': {}, // can't search by patient; "Only an _ID search is allowed."
'Condition': {},
'Observation': {}, // "Must have either code or category."
// 'Organization': {}, // can't search by patient; "Only an _ID search is allowed."
'Immunization': {
title: 'Immunization History',
itemDisplayFn: immunizationItem,
},
// 'Device': {},
// 'DeviceUseStatement': {}, // Not in EPIC USCDI R4
'DiagnosticReport': {}, // TODO change to subject
// 'ImagingStudy': {}, // Not in EPIC USCDI R4
// 'Media': {}, // Not in EPIC USCDI R4
// 'Practitioner': {}, // can't search by patient; "Either name, family, or identifier is a required parameter."
// 'PractitionerRole': {}, // can't search by patient; "An identifier, practitioner, organization, location, or specialty parameter is required."
'Procedure': {}, // TODO change to subject
// 'Specimen': {}, // Not in EPIC USCDI R4
}
const patientResourceScope = Object.keys(patientResourceConfig).map(resourceType => `patient/${resourceType}.read`);
const resourceScope = patientResourceScope.join(" ");
const clientIDs = {
"epic": {
"production": "d1bc396c-1b91-4135-bfd7-e028f3eeb43a",
"non-production": "1fb63933-3891-4ac2-a080-e7de0acb6c7f"
},
"cerner": {
"production": "0cffd924-9824-4d1d-989e-735833c49c74",
"non-production": "0cffd924-9824-4d1d-989e-735833c49c74"
}
}
const config = {
// This client ID worked through 2023-04-17, and then I marked the app as ready for production. I think at that point I was assigned new prod & non-prod client ID's...
clientId: "no client id provided", // Set later. I believe clientId is ignored at smit.
scope: `openid fhirUser launch/patient ${resourceScope} offline_access`,
iss: '(populated later)',
completeInTarget: true,
redirect_uri: 'index.html'
};
$(document).ready(() => {
$('#start-app-button').on('click', startApp);
$('#fhir-base-url').on('click', selectOther);
$('.accordion-header').click(function() {
$(this).toggleClass('active');
$(this).next('.accordion-content').slideToggle();
});
$('#show-more').click(function() {
$('#show-more').slideToggle();
$('#more').slideToggle();
});
$('#show-less').click(function() {
$('#more').slideToggle();
$('#show-more').slideToggle();
});
});
function startApp() {
// At this point, the field has the user's desired host URL.
const endpointSelection = $('input[type=radio]:checked');
Object.keys(clientIDs).forEach(ehr => {
if (endpointSelection.hasClass(ehr)) {
if (endpointSelection.hasClass('production')) {
config.clientId = clientIDs[ehr]['production'];
} else {
config.clientId = clientIDs[ehr]['non-production'];
}
}
});
let valueInput = endpointSelection.attr('id') === "other" ? $('#fhir-base-url') : endpointSelection;
let inputFhirUrl = valueInput.val().trim();
if (inputFhirUrl.endsWith('/')) {
inputFhirUrl = inputFhirUrl.split(0, -1);
}
if (!isValidUrl(inputFhirUrl)) {
alert('The URL is not valid. Please enter a valid URL.');
return;
}
config.iss = inputFhirUrl;
FHIR.oauth2.authorize(config);
}; // const startApp
function selectOther() {
$('input[type=radio]:checked').prop('checked', false);
$('#other').prop('checked', true);
}
if (sessionStorage.getItem('SMART_KEY')) { // is there an event like FHIR.oauth2.ready() which would include this criteria?
$('.loader').show();
FHIR.oauth2.ready().then(client => {
if (client.getPatientId()) {
const requestResources = (resourceType) => {
let endpoint = (resourceType == 'Patient' ? 'Patient/' : `${resourceType}?patient=`) + client.getPatientId();
return client.request(endpoint, { flat: true }).then(result => {
let resourcesToPass = []
if (Array.isArray (result)) {
result.forEach(resource => {
if (resource === undefined || resource.resourceType != resourceType) return;
resourcesToPass.push(resource);
});
} else {
resourcesToPass.push(result);
}
return resourcesToPass;
}).catch(error => {
console.error(error);
return []; // resolve successfully with an empty array despite request error
});
};
// Establish resource display methods
const sectionDisplays = Object.fromEntries(
Object.entries(patientResourceConfig).map(([resourceType, resourceConfig]) => {
let title = resourceConfig.title ?? resourceNameToTitle(resourceType);
let itemDisplayFn = resourceConfig.itemDisplayFn ?? defaultItemDisplayFn;
let sectionDisplayFn = (resourceList) => (resourceConfig.sectionDisplayFn ?? defaultSectionDisplayFn)(resourceList, title, itemDisplayFn);
return [resourceType, sectionDisplayFn];
})
);
// Request resources, then display content according to configuration
Promise.all(Object.keys(sectionDisplays).map((resourceType) => {
return requestResources(resourceType);
})).then(
results => {
displayFunctions = Object.values(sectionDisplays);
if (results.length == displayFunctions.length) {
let numResourceTypesDisplayed = 0;
for (i = 0; i < displayFunctions.length; i++) {
if (results[i].length > 0) {
if (results[i][0].resourceType != 'Patient') {
numResourceTypesDisplayed++;
}
displayFunctions[i](results[i]);
}
}
if (numResourceTypesDisplayed == 0) {
emptyDisplay();
}
$('.loader').hide();
$('#content').show();
} else {
alert('Something went wrong.');
}
} // display the resource content
).catch(
error => alert(error) // doesn't run
);
}
}).catch(console.error);
} //if (sessionStorage.getItem('SMART_KEY'))
// Read 'fhirUrl' cookie and populate the field with it.
function readCookiesAndApply() {
let fhirUrlCookie = getCookie('fhirUrl');
if (fhirUrlCookie != undefined){
const fhirBaseUrlInput = $('#fhir-base-url');
fhirBaseUrlInput.val(fhirUrlCookie);
}
const environmentCookie = getCookie('environment');
if (environmentCookie) {
const nonProductionRadio = $('#non-production');
const productionRadio = $('#production');
if (environmentCookie === 'production') {
nonProductionRadio.prop('checked', false);
productionRadio.prop('checked', true);
} else {
nonProductionRadio.prop('checked', true);
productionRadio.prop('checked', false);
}
}
}
// Utility function to validate a URL
function isValidUrl(url) {
try {
new URL(url);
return true;
} catch (e) {
return false;
}
}
// Utility function to set a cookie
function setCookie(name, value, hours) {
const date = new Date();
date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
const expires = '; expires=' + date.toUTCString();
document.cookie = name + '=' + value + expires + '; path=/';
}
// Utility function to get a cookie
function getCookie(name) {
const nameEQ = name + '=';
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
function simpleItem(resource){
return `${resource.resourceType}: ${JSON.stringify(resource, space=4)}`;
};
function immunizationItem(immunization){
const displayText = immunization.vaccineCode.coding[0].display === undefined ? immunization.vaccineCode.text : immunization.vaccineCode.coding[0].display;
return `${displayText} - ${immunization.occurrenceDateTime}`;
}
function resourceNameToTitle(str){
if (str == null) return "";
// "PractitionerRole" ->"Practitioner Roles"
return str.match(/[A-Z][a-z]+/g).join(" ") + "s";
}
function sectionTitle(title) {
return `<h2>${title}</h2>`;
}
function patientSection(resourceList, title, resourceContentFn) {
let patient = resourceList[0];
const PatientContent = $(`#${patient.resourceType}Content`);
const name = patient.name[0];
const formattedName = `${name.given.join(' ')} ${name.family}`;
PatientContent.append(sectionTitle(`Patient Name: ${formattedName}`));
}
function listSection(resourceList, title, resourceContentFn){
if (resourceList.length == 0) return;
let resourceType = resourceList[0].resourceType;
title = title ?? resourceNameToTitle(resourceType);
const sectionId = `#${resourceType}Content`;
const section = $(sectionId);
addToTOC(title, resourceType);
section.append(sectionTitle(title));
const list = document.createElement('ul');
for (let i = 0; i < resourceList.length; i++) {
const resource = resourceList[i];
const listItem = document.createElement('li');
listItem.textContent = resourceContentFn(resource);
list.append(listItem);
}
section.append(list);
};
function addToTOC(title, resourceType) {
$(`#${resourceType}TOC`).html(`${title}<br/>`);
}
function emptyDisplay() {
$('#toc').hide();
$(`#EmptyContent`).html(`<p>No content returned.</p>`);
}