-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatient-lib.js
More file actions
311 lines (281 loc) · 8.65 KB
/
patient-lib.js
File metadata and controls
311 lines (281 loc) · 8.65 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
export const patientLib = {
handleFormSubmit,
getFormPermanentContent,
getFormHistorical,
getHistoricalContent,
navGetPages
}
// --------------- navigation - to be replaced if built-in framework ------- //
const pagesByTypes = {
home: 'patient.html',
permanent: 'patient-profile.html',
recurring: 'patient-history.html'
};
async function navGetPages(collectorClient) {
const pages = [{
type: 'home',
url: pagesByTypes.home,
label: 'Home',
formKey: null
}];
for (const section of collectorClient.request.sections) {
pages.push({
type: section.type,
label: HDSLib.l(section.name),
url: pagesByTypes[section.type] + '?formKey=' + section.key,
formKey: section.key
});
}
console.log("NNNN ", collectorClient.request, pages);
return pages;
}
// ---------------- form content ---------------- //
async function getFormHistorical (collectorClient, formKey) {
await HDSLib.initHDSModel();
const section = collectorClient.request.getSectionByKey(formKey);
const formFields = section.itemKeys.map((itemKey) => {
const itemDef = HDSLib.getHDSModel().itemsDefs.forKey(itemKey);
return {
id: itemDef.key,
label: itemDef.label,
type: itemDef.data.type,
options: itemDef.data.options,
itemDef
}
});
return formFields;
}
// local copy of formProfileContent + actual values
/**
* @param {*} form
* @param {*} date
* @returns
*/
async function getFormPermanentContent (collectorClient, formKey) {
await HDSLib.initHDSModel();
const section = collectorClient.request.getSectionByKey(formKey);
console.log('## getFormPermanentContent ', {section, formKey, collectorClient})
// get formItems
const formItemDefs = section.itemKeys.map((itemKey) => (HDSLib.getHDSModel().itemsDefs.forKey(itemKey)));
// get the values from the API
const apiCalls = formItemDefs.map(itemDef => ({
method: 'events.get',
params: {
streams: [itemDef.data.streamId],
types: itemDef.eventTypes,
limit: 1,
}
}));
const formContent = [];
const res = await collectorClient.app.connection.api(apiCalls);
for (let i = 0; i < res.length; i++) {
const e = res[i];
const itemDef = formItemDefs[i];
const content = {
id: itemDef.key,
type: itemDef.data.type,
label: itemDef.label,
options: itemDef.data.options,
itemDef,
}
if (e.events && e.events.length > 0) {
const event = e.events[0];
const valueAndTxt = valueAndTxtForField(event, itemDef);
console.log('>> valueAndtxt', {event, valueAndTxt});
content.value = valueAndTxt.value;
content.valueTxt = valueAndTxt.txt;
content.eventId = event.id; // will allow t track if the event is to be updated
} else {
console.log('>> no event', e);
}
formContent.push(content);
}
return formContent;
};
async function getHistoricalContent(collectorClient, formKey) {
await HDSLib.initHDSModel();
const section = collectorClient.request.getSectionByKey(formKey);
const itemDefs = section.itemKeys.map((itemKey) => (HDSLib.getHDSModel().itemsDefs.forKey(itemKey)));
const tableHeaders = itemDefs.map(itemDef => ({
fieldId: itemDef.key,
label: itemDef.label,
type: itemDef.data.type
}));
const valuesByDateStr = {};
function addEntry (event) {
const itemDef = HDSLib.getHDSModel().itemsDefs.forEvent(event, false);
if (itemDef == null) {
console.log('Historical content -- unkown event', event);
return;
}
const dateStr = (new Date(event.time * 1000)).toISOString().split('T')[0];
if (valuesByDateStr[dateStr] == null) valuesByDateStr[dateStr] = {
dateNum: (new Date(dateStr)).getTime() / 1000,
dateStr,
};
const valueAndTxt = valueAndTxtForField(event, itemDef);
valuesByDateStr[dateStr][itemDef.key] = {
value: valueAndTxt.value,
valueTxt: valueAndTxt.txt,
eventId: event.id
}
}
// get the values from the API
const apiCalls = itemDefs.map(itemDef => ({
method: 'events.get',
params: {
streams: [itemDef.data.streamId],
types: itemDef.eventTypes,
limit: 20, // last 20 of each item is enough for a demo
}
}));
const res = await collectorClient.app.connection.api(apiCalls);
for (let i = 0; i < res.length; i++) {
const e = res[i];
if (e.events) {
for (const event of e.events) {
addEntry(event);
}
}
}
// order by date
const valuesByDate = Object.values(valuesByDateStr).sort((a, b) => b.dateNum - a.dateNum);
return { tableHeaders, valuesByDate };
}
function valueAndTxtForField (event, itemDef) {
if (event.type === 'activity/plain' ) {
return { value: 'x', txt: 'X'};
}
if (itemDef.data.type === 'date' && event.content != null ) {
// convert the date to a Date object
const date = new Date(event.content);
if (!isNaN(date)) {
const dayStr = date.toISOString().split('T')[0];
return { value: dayStr, txt: dayStr }; // format YYYY-MM-DD
}
console.error('## Error parsing date', event.content);
return {value: '', txt: 'Error parsing date'};
}
if (itemDef.data.type === 'select') {
let value = event.content;
let txt = value;
if (event.type === 'ratio/generic') {
value = event.content.value;
}
console.log({value, event})
const selected = itemDef.data.options.find((o) => ( o.value === value ));
if (selected) {
txt = selected != null ? HDSLib.l(selected.label) : ' - ';
}
return { value, txt };
}
if (event.type === 'ratio/generic' && event.content != null ) {
return { value: event.content.value, txt: event.content.value};
}
return { value: event.content, txt: event.content };
}
// ---------------- create / update data ---------------- //
function parseValue (value, field) {
const type = field.itemDef.data.type;
console.log('>> parsValue', {value, field});
if (value === undefined || value === null || value === '') {
return '';
}
if (type === 'number') {
return parseFloatCustom(value);
}
if (type === 'date') {
if (value instanceof Date && !isNaN(value)) {
return value.toISOString();
}
return value === '';
}
if (type === 'select' && field.itemDef.eventTypes[0] === 'ratio/generic') {
const numValue = parseFloatCustom(value);
if (numValue === '') return '';
// relative to is the latest value of options
const relativeTo = field.options[field.options.length -1].value;
return {
value: numValue,
relativeTo
}
}
if (type === 'checkbox' && field.itemDef.eventTypes[0] === 'activity/plain') {
if (value === 'true') return null; // will be handled as a value
return '';
}
if (type === 'checkbox') {
return value === 'true';
}
return value;
}
function parseFloatCustom(value) {
const parsedValue = parseFloat(value);
if (isNaN(parsedValue)) {
console.error('## Error parsing number', value);
return '';
}
return parsedValue;
}
async function handleFormSubmit (collectorClient, formData, formKey, values, date) {
console.log('## handleForm', {formData, values, date});
const apiCalls = [];
// list of items that will be created or updated
const itemDefsToCreateOrUpdate = new Set();
for (const field of formData) {
const streamId = field.itemDef.data.streamId;
const eventType = field.itemDef.eventTypes[0];
const eventId = field.eventId;
const value = parseValue(values[field.id], field);
console.log('>> parsed value:', value);
if (value === '' && eventId) {
// delete the event
apiCalls.push({
method: 'events.delete',
params: {
id: eventId,
}
});
continue;
}
if (value === field.value || value === '') {
// no change or noting to create
continue;
}
// bellow update or create
itemDefsToCreateOrUpdate.add(field.itemDef);
if (eventId) {
// update the event
apiCalls.push({
method: 'events.update',
params: {
id: eventId,
update: {
content: value
}
}
});
continue;
}
// create a new event
const eventData = {
streamId: streamId,
type: eventType,
content: value
};
if (date) eventData.time = date.getTime() / 1000;
apiCalls.push({
method: 'events.create',
params: eventData
});
}
if (apiCalls.length === 0) {
console.log('## No changes to submit');
return;
}
// ensure streams exists
await collectorClient.app.connection.streamsAutoCreate.ensureExistsForItems(itemDefsToCreateOrUpdate);
// send the API calls
const res = await collectorClient.app.connection.api(apiCalls);
console.log('## Form submitted', res);
}