-
Notifications
You must be signed in to change notification settings - Fork 0
/
reports.js
2143 lines (2104 loc) · 77.5 KB
/
reports.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
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const axios = require('axios');
const https = require('https')
const async = require('async');
const moment = require('moment')
const pluralize = require('pluralize')
const logger = require('./winston')
const URI = require('urijs');
const _ = require('lodash');
const { v5: uuid5 } = require('uuid');
const FHIRPath = require('fhirpath');
const sqlstring = require('sqlstring');
const { Sequelize, DataTypes, QueryTypes } = require('sequelize');
/**
* Disable only in development mode
*/
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
})
axios.defaults.httpsAgent = httpsAgent
class CacheFhirToES {
constructor({
FHIRBaseURL,
FHIRUsername,
FHIRPassword,
relationshipsIDs = [],
since,
reset = false,
ESModulesBasePath,
DBConnection
}) {
this.FHIRBaseURL = FHIRBaseURL
this.FHIRUsername = FHIRUsername
this.FHIRPassword = FHIRPassword
this.relationshipsIDs = relationshipsIDs
this.since = since
this.reset = reset
this.deletedRelatedDocs = []
this.ESModulesBasePath = ESModulesBasePath
this.sequelize = new Sequelize(DBConnection.database, DBConnection.username, DBConnection.password, {
host: 'localhost',
dialect: DBConnection.dialect
});
}
getRelationshipFields(relationship) {
let fields = []
for(let ext of relationship.extension) {
let elements = ext.extension.filter((ext) => {
return ext.url === "http://ihris.org/fhir/StructureDefinition/iHRISReportElement"
})
for(let element of elements) {
let name = element.extension.find((ext) => {
return ext.url === "name"
})?.valueString
let type = element.extension.find((ext) => {
return ext.url === "type"
})?.valueString
if(name) {
fields.push({
name,
type
})
}
}
}
return fields
}
flattenComplex(extension) {
let results = {};
for (let ext of extension) {
let value = '';
for (let key of Object.keys(ext)) {
if (key !== 'url') {
value = ext[key];
}
}
if (results[ext.url]) {
if (Array.isArray(results[ext.url])) {
results[ext.url].push(value);
} else {
results[ext.url] = [results[ext.url], value];
}
} else {
if (Array.isArray(value)) {
results[ext.url] = [value];
} else {
results[ext.url] = value;
}
}
}
return results;
};
/**
*
* @param {relativeURL} reference //reference must be a relative url i.e Practioner/10
*/
getResourceFromReference(reference) {
return new Promise((resolve) => {
let url = URI(this.FHIRBaseURL)
.segment(reference)
.toString()
axios.get(url, {
headers: {
'Cache-Control': 'no-cache',
},
withCredentials: true,
auth: {
username: this.FHIRUsername,
password: this.FHIRPassword
},
}).then(response => {
return resolve(response.data)
}).catch((err) => {
logger.error('Error occured while getting resource reference');
logger.error(err);
return resolve()
})
}).catch((err) => {
logger.error('Error occured while getting resource reference');
logger.error(err);
})
}
resourceDisplayName(resource, displayFormat) {
return new Promise((resolve) => {
let details = {}
let valformat = displayFormat && displayFormat.extension.find((ext) => {
return ext.url === 'format'
})
if(valformat) {
details.format = valformat.valueString
}
let valorder = displayFormat && displayFormat.extension.find((ext) => {
return ext.url === 'order'
})
let paths = displayFormat && displayFormat.extension.filter((ext) => {
return ext.url.startsWith("paths:")
})
if(valorder) {
details.order = valorder.valueString
} else {
if(paths) {
for(let path of paths) {
path = path.url.split(":")
if(path.length > 1) {
if(!details.order) {
details.order = path[1]
} else {
details.order += ',' + path[1]
}
}
}
}
}
if(paths && paths.length > 0) {
details.paths = {}
for(let path of paths) {
let url = path.url.split(":")
if(url.length > 1) {
if(!details.paths[url[1]]) {
details.paths[url[1]] = {}
}
details.paths[url[1]][url[2]] = path.valueString
}
}
}
if(!details.order && !details.paths) {
let name = resource.name
if(!name) {
name = resource.extension && resource.extension.find((ext) => {
return ext.url === 'http://ihris.org/fhir/StructureDefinition/ihris-basic-name'
})
if(name) {
name = name.valueString
}
}
return resolve(name)
}
let format = details.format || "%s"
let output = []
let order = details.order.split(',')
if ( details.fhirpath ) {
output.push( FHIRPath.evaluate( resource, details.fhirpath ).join( details.join || " " ) )
} else if ( details.paths ) {
for ( let ord of order ) {
ord = ord.trim()
output.push( FHIRPath.evaluate( resource, details.paths[ ord ].fhirpath ).join( details.paths[ord].join || " " ) )
}
}
for(let val of output) {
format = format.replace('%s', val)
}
return resolve(format)
})
}
/**
*
* @param {Array} extension
* @param {String} element
*/
getElementValFromExtension(extension, element) {
return new Promise((resolve) => {
let elementValue = ''
async.each(extension, (ext, nxtExt) => {
let value
for (let key of Object.keys(ext)) {
if (key !== 'url') {
value = ext[key];
}
}
if (ext.url === element) {
elementValue = value
}
(async () => {
if (Array.isArray(value)) {
let val
try {
val = await this.getElementValFromExtension(value, element)
} catch (error) {
logger.error(error);
}
if (val) {
elementValue = val
}
return nxtExt()
} else {
return nxtExt()
}
})();
}, () => {
resolve(elementValue)
})
}).catch((err) => {
logger.error('Error occured while geting Element value from extension');
logger.error(err);
})
}
getImmediateLinks(links, callback) {
if (this.orderedResources.length - 1 === links.length) {
return callback(this.orderedResources);
}
let promises = [];
for (let link of links) {
promises.push(
new Promise((resolve, reject) => {
link = this.flattenComplex(link.extension);
let parentOrdered = this.orderedResources.find(orderedResource => {
let linkToResource = link.linkTo.split('.').shift()
return orderedResource.name === linkToResource;
});
let exists = this.orderedResources.find(orderedResource => {
return JSON.stringify(orderedResource) === JSON.stringify(link);
});
if (parentOrdered && !exists) {
this.orderedResources.push(link);
}
resolve();
})
);
}
Promise.all(promises).then(() => {
if (this.orderedResources.length - 1 !== links.length) {
this.getImmediateLinks(links, () => {
return callback();
});
} else {
return callback();
}
}).catch((err) => {
logger.error(err);
return callback();
});
};
getReportRelationship(callback) {
let url = URI(this.FHIRBaseURL)
.segment('Basic')
if(this.relationshipsIDs.length > 0) {
url.addQuery('_id', this.relationshipsIDs.join(','));
} else {
url.addQuery('code', 'iHRISRelationship');
}
url = url.toString();
axios
.get(url, {
headers: {
'Cache-Control': 'no-cache',
},
withCredentials: true,
auth: {
username: this.FHIRUsername,
password: this.FHIRPassword,
},
})
.then(relationships => {
return callback(false, relationships.data);
})
.catch(err => {
logger.error(err);
return callback(err, false);
});
};
createSyncDataTable() {
return new Promise((resolve, reject) => {
let syncdatafields = {
id: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true
},
last_began_indexing_time: {
type: DataTypes.DATE
},
last_ended_indexing_time: {
type: DataTypes.DATE
}
}
let table = this.sequelize.define("fhir2sqlsyncdata", syncdatafields, {
timestamps: false
})
table.sync().then(() => {
resolve()
}).catch((err) => {
logger.error(err);
reject()
})
})
}
updateLastIndexingTime(start, ended, index) {
return new Promise((resolve, reject) => {
logger.info('Updating lastIndexingTime')
let sql = `update fhir2sqlsyncdata set last_began_indexing_time='${start}', last_ended_indexing_time='${ended}' where id='${index}'`
this.executeSQL(sql, "UPDATE").then((response) => {
if(response[1] == 0) {
let sql = `insert into fhir2sqlsyncdata values ('${index}', '${start}', '${ended}')`
this.executeSQL(sql, "INSERT").then(() => {
return resolve(false)
}).catch((err) => {
logger.error(err)
logger.error('An error occured while updating lastIndexingTime')
return reject(true)
})
} else {
return resolve(false)
}
}).catch((err) => {
logger.error(err)
logger.error('An error occured while updating lastIndexingTime')
return reject(true)
})
})
}
getLastIndexingTime(index) {
return new Promise((resolve, reject) => {
if(this.since && !this.reset) {
this.last_began_indexing_time = this.since
this.last_ended_indexing_time = this.since
return resolve()
}
logger.info('Getting lastIndexingTime')
let sql = `select * from fhir2sqlsyncdata where id='${index}'`
this.executeSQL(sql, 'SELECT').then((response) => {
if(this.reset) {
logger.info('Returning lastIndexingTime of 1970-01-01T00:00:00')
this.last_began_indexing_time = '1970-01-01T00:00:00'
this.last_ended_indexing_time = '1970-01-01T00:00:00'
return resolve()
}
if(response.length === 0) {
logger.info('Returning lastIndexingTime of 1970-01-01T00:00:00')
this.last_began_indexing_time = '1970-01-01T00:00:00'
this.last_ended_indexing_time = '1970-01-01T00:00:00'
return resolve()
}
logger.info('Returning last_began_indexing_time of ' + response[0].last_began_indexing_time)
this.last_began_indexing_time = moment(response[0].last_began_indexing_time).format("YYYY-MM-DDTHH:mm:ss")
this.last_ended_indexing_time = moment(response[0].last_ended_indexing_time).format("YYYY-MM-DDTHH:mm:ss")
return resolve()
}).catch((err) => {
logger.error(err);
logger.error('Error occured while getting last indexing time in ES');
logger.info('Returning last_began_indexing_time of 1970-01-01T00:00:00')
this.last_began_indexing_time = '1970-01-01T00:00:00'
this.last_ended_indexing_time = '1970-01-01T00:00:00'
return reject()
})
})
}
formatColumn(name) {
if(name.startsWith('__') || name == 'id') {
return name
}
name = name.toLowerCase()
name = 'ihris_' + name
name = name.split("-").join("_")
return name
}
createTable(name, IDFields, relationship) {
return new Promise((resolve, reject) => {
let relfields = [...IDFields, ...this.getRelationshipFields(relationship)]
let fields = {
id: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true
}
}
for(let field of relfields) {
let fieldname = this.formatColumn(field.name)
let type = 'TEXT'
if(field.type === 'string') {
type = 'TEXT'
} else if(field.type === 'date') {
type = 'DATEONLY'
} else if(field.type === 'datetime' || field.type === 'dateTime' || field.type === 'DateTime') {
type = 'DATE'
}
fields[fieldname] = {
type: DataTypes[type]
}
}
fields.lastupdated = {
type: DataTypes.DATE
}
let table = this.sequelize.define(name, fields, {
timestamps: false
})
table.sync({ alter: true }).then(() => {
resolve()
}).catch((err) => {
logger.error(err);
reject()
})
})
}
getQueryCondition(data) {
let where = ''
if(data.query.terms) {
let condition = Object.keys(data.query.terms)[0]
let conditionVal = data.query.terms[condition]
condition = condition.replace(".keyword", "")
if(condition) {
condition = this.formatColumn(condition)
}
if(Array.isArray(conditionVal)) {
conditionVal = conditionVal[0]
}
if(condition && conditionVal) {
where += ` where ${condition}='${conditionVal}'`
}
} else if(data.query.bool) {
if(Array.isArray(data.query.bool.should)) {
for(let should of data.query.bool.should) {
let where_should = ''
let terms
if(should.terms) {
terms = should.terms
} else if(should.term) {
terms = should.term
} else if(should.match) {
terms = should.match
}
let key = Object.keys(terms)[0]
let column = key.replace(".keyword", "")
if(column) {
column = this.formatColumn(column)
}
if(Array.isArray(terms[key])) {
for(let term of terms[key]) {
if(!where_should) {
where_should = ` (`
} else {
where_should += ` or `
}
where_should += `${column}='${term}'`
}
if(where_should) {
where_should += ')'
}
} else {
where_should += ` (${column}='${terms[key]}')`
}
if(where) {
where += ` or ${where_should}`
} else {
where = ` where ${where_should}`
}
}
}
if(Array.isArray(data.query.bool.must)) {
for(let must of data.query.bool.must) {
let where_must = ''
let terms
if(must.terms) {
terms = must.terms
} else if(must.term) {
terms = must.term
} else if(must.match) {
terms = must.match
}
let key = Object.keys(terms)[0]
let column = key.replace(".keyword", "")
if(column) {
column = this.formatColumn(column)
}
if(Array.isArray(terms[key])) {
for(let term of terms[key]) {
if(!where_must) {
where_must = ` (`
} else {
where_must += ` or `
}
where_must += `${column}='${term}'`
}
if(where_must) {
where_must += ')'
}
} else {
where_must += ` (${column}='${terms[key]}')`
}
if(where) {
where += ` and ${where_must}`
} else {
where = ` where ${where_must}`
}
}
}
if(Array.isArray(data.query.bool.must_not)) {
for(let must_not of data.query.bool.must_not) {
let where_must_not = ''
let terms
if(must_not.terms) {
terms = must_not.terms
} else if(must_not.term) {
terms = must_not.term
} else if(must_not.match) {
terms = must_not.match
} else if(must_not.exists) {
let column = this.formatColumn(must_not.exists.field)
where_must_not = ` (${column} is NULL or ${column}='')`
if(where) {
where += ` and ${where_must_not}`
} else {
where += ` where ${where_must_not}`
}
break
}
let key = Object.keys(terms)[0]
let column = key.replace(".keyword", "")
if(column) {
column = this.formatColumn(column)
}
if(Array.isArray(terms[key])) {
for(let term of terms[key]) {
if(!where_must_not) {
where_must_not = ` (`
} else {
where_must_not += ` or `
}
where_must_not += `${column}!='${term}'`
}
if(where_must_not) {
where_must_not += ')'
}
} else {
where_must_not += ` (${column}!='${terms[key]}')`
}
if(where) {
where += ` and ${where_must_not}`
} else {
where += ` where ${where_must_not}`
}
}
}
}
return where
}
generateSelectSQL(data, index) {
index = pluralize(index)
let where = this.getQueryCondition(data)
let query = `select * from ${index} ${where}`
return query
}
generateDeleteSQL(data, index) {
index = pluralize(index)
let where = this.getQueryCondition(data)
let query = `delete from ${index} ${where}`
return query
}
generateUpdateSQL(data, index) {
index = pluralize(index)
let query = `update ${index} set `
if(data.script && data.script.source) {
let sources = data.script.source.split(";")
for(let source of sources) {
let src = source.split("=")
let value = src[1]
let col = src[0].split("'")[1]
if(!col) {
continue
}
col = this.formatColumn(col)
query += `${col}=${value.trim()}, `
}
query += `lastUpdated='${moment().format("Y-MM-DDTHH:mm:ss")}'`
let where = this.getQueryCondition(data)
query += where
} else if(typeof data === 'object') {
for(let dt in data) {
let column = this.formatColumn(dt)
query += `${column}=${data[dt].trim()} `
}
}
return query
}
generateInsertSQL(data, index) {
index = pluralize(index)
let query = `insert into ${index} `
let columns = ''
let values = ''
if(typeof data === 'object') {
delete data.lastUpdated
for(let dt in data) {
let column = this.formatColumn(dt)
if(!columns) {
columns = `(${column}`
} else {
columns += `, ${column}`
}
let value = data[dt]
if(data[dt]) {
value = sqlstring.escape(data[dt].trim())
}
if(!values) {
values = `(${value}`
} else {
values += `, ${value}`
}
}
} else {
let sources = data.split(";")
for(let source of sources) {
let src = source.split("=")
let value = sqlstring.escape(src[1].trim())
let col = src[0].split("'")[1]
let column = this.formatColumn(col)
if(!columns) {
columns = `(${column}`
} else {
columns += `, ${column}`
}
if(!values) {
values = `(${value}`
} else {
values += `, ${value}`
}
}
}
let time = moment().format("Y-MM-DDTHH:mm:ss")
columns += `, lastUpdated)`
values += `, '${time}')`
query += `${columns} values ${values}`
return query
}
executeSQL(sql, type) {
return new Promise((resolve, reject) => {
if(type) {
type = { type: QueryTypes[type] }
}
this.sequelize.query(sql, type).then((response) => {
resolve(response)
}).catch((err) => {
logger.error(err);
reject()
})
})
}
getResourcesFields(resources) {
let fields = []
for(let resource of resources) {
if(resource["http://ihris.org/fhir/StructureDefinition/iHRISReportElement"]) {
for (let element of resource["http://ihris.org/fhir/StructureDefinition/iHRISReportElement"]) {
let fieldName
let fhirPathValue
let fieldAutogenerated = false
for (let el of element) {
let value = '';
for (let key of Object.keys(el)) {
if (key !== 'url') {
value = el[key];
}
}
if (el.url === "name") {
let fleldChars = value.split(' ')
//if name has space then format it
if (fleldChars.length > 1) {
fieldName = value.toLowerCase().split(' ').map(word => word.replace(word[0], word[0].toUpperCase())).join('');
} else {
fieldName = value
}
} else if (el.url === "fhirpath") {
fhirPathValue = value
} else if (el.url === "autoGenerated") {
fieldAutogenerated = value
}
}
fields.push({
resourceName: resource.name,
resourceType: resource.resource,
field: fieldName,
fhirPath: fhirPathValue,
fieldAutogenerated
})
}
fields.push({
resourceName: resource.name,
resourceType: resource.resource,
field: resource.name,
fhirPath: "id",
fieldAutogenerated: false
})
}
}
return fields;
}
getChildrenResources(resourceName) {
let childrenResources = []
for(let orderedResource of this.orderedResources) {
if(orderedResource.linkTo === resourceName || (orderedResource.linkTo && orderedResource.linkTo.startsWith(resourceName + '.'))) {
childrenResources.push(orderedResource)
let grandChildren = this.getChildrenResources(orderedResource.name)
childrenResources = childrenResources.concat(grandChildren)
}
}
return childrenResources
}
async updateESDocument(body, record, index, orderedResource, resourceData, tryDeleting, extraTerms, callback) {
let multiple = orderedResource.multiple
let allTerms = _.cloneDeep(body.query.terms)
//this handles records that should be deleted instead of its fields being truncated
let recordDeleted = false;
async.series({
addNewRows: (callback) => {
//ensure that this is not the primary resource and has multiple tag, otherwise return
if(!orderedResource.hasOwnProperty('linkElement') || !multiple) {
return callback(null)
}
let query = {
query: {
bool: {
must: [{
terms: body.query.terms
}]
}
}
}
query.query.bool.must = query.query.bool.must.concat(extraTerms)
let sqlquery = this.generateSelectSQL(query, index)
this.executeSQL(sqlquery, 'SELECT').then(async(results) => {
//if field values for this record needs to be truncated and there are multiple records of the parent, then delete the one we are truncating instead of updating
if(results.length > 1 && tryDeleting) {
let recordFields = Object.keys(record)
let idField = recordFields[recordFields.length - 1]
let termField = Object.keys(body.query.terms)[0]
let delQry = {
query: {
bool: {
must: []
}
}
}
let must1 = {
terms: {}
}
must1.terms[termField] = body.query.terms[termField]
delQry.query.bool.must.push(must1)
let must2 = {
terms: {}
}
must2.terms[idField] = [record[idField]]
delQry.query.bool.must.push(must2)
delQry.query.bool.must = delQry.query.bool.must.concat(extraTerms)
try {
let sqlquery = this.generateDeleteSQL(delQry, index)
await this.executeSQL(sqlquery)
} catch (error) {
logger.error(error);
}
recordDeleted = true;
}
if(recordDeleted || tryDeleting) {
return callback(null)
}
//because this resource supports multiple rows, then we are trying to add new rows
let newRows = []
// take the last field because it is the ID
let recordFields = Object.keys(record)
let checkField = recordFields[recordFields.length - 1]
for(let linkField in allTerms) {
for(let index in allTerms[linkField]) {
let newRowBody = {}
// create new row only if there is no checkField or checkField exist but it is different
let updateThis = results.find((hit) => {
return hit[linkField] === allTerms[linkField][index] && (!hit[checkField] || hit[checkField] === record[checkField])
})
if(!updateThis) {
let hit = results.find((hit) => {
return hit[linkField] === allTerms[linkField][index]
})
if(!hit) {
continue;
}
for(let field in hit) {
newRowBody[field] = hit[field]
}
for(let recField in record) {
newRowBody[recField] = record[recField]
}
let trmInd = body.query.terms[linkField].findIndex((trm) => {
return trm === allTerms[linkField][index]
})
body.query.terms[linkField].splice(trmInd, 1)
}
if(Object.keys(newRowBody).length > 0) {
newRows.push(newRowBody)
}
}
}
if(newRows.length > 0) {
async.eachSeries(newRows, (newRowBody, nxt) => {
newRowBody.lastUpdated = moment().format('Y-MM-DDTHH:mm:ss');
let query = this.generateInsertSQL(newRowBody, index)
this.executeSQL(query).then(() => {
return nxt()
}).catch(() => {
return nxt()
})
}, () => {
return callback(null)
})
} else {
return callback(null)
}
})
},
updateRow: (callback) => {
if(recordDeleted) {
return callback(null);
}
// for multiple rows, ensure that we dont update all rows but just one row
let bodyData = {}
let recordFields = Object.keys(record)
let idField = recordFields[recordFields.length - 1]
if(multiple) {
let termField = Object.keys(body.query.terms)[0]
bodyData = {
query: {
bool: {
must: []
}
}
}
let must1 = {
terms: {}
}
must1.terms[termField] = body.query.terms[termField]
bodyData.query.bool.must.push(must1)
let must2 = {
terms: {}
}
must2.terms[idField] = [record[idField]]
bodyData.query.bool.must.push(must2)
bodyData.query.bool.must = bodyData.query.bool.must.concat(extraTerms)
bodyData.script = body.script
} else {
bodyData = body
}
async.series({
updateDocMissingField: (callback) => {
if(!multiple) {
return callback(null)
}
let updBodyData = _.cloneDeep(bodyData)
updBodyData.script.source += `ctx._source.lastUpdated='${moment().format("Y-MM-DDTHH:mm:ss")}';`
updBodyData.query.bool.must.splice(1, 1)
let must_not = {
exists: {}
}
must_not.exists.field = idField
updBodyData.query.bool.must_not = [must_not]
let query = this.generateUpdateSQL(updBodyData, index)
this.executeSQL(query).then(() => {
return callback(null)
}).catch(() => {
return callback(null)
})
},
updateDocHavingField: (callback) => {
let updBodyData = _.cloneDeep(bodyData)
updBodyData.script.source += `ctx._source.lastUpdated='${moment().format("Y-MM-DDTHH:mm:ss")}';`
let query = this.generateUpdateSQL(updBodyData, index)
this.executeSQL(query).then((response) => {
// if nothing was updated and its from the primary (top) resource then create as new
if (response[1].rowCount == 0 && !orderedResource.hasOwnProperty('linkElement')) {
logger.info('No record with id ' + resourceData.id + ' found on elastic search, creating new');
let id = record[orderedResource.name].split('/')[1]
if(extraTerms.length > 0) {
let ids = [id]
for(let extraTerm of extraTerms) {
ids.push(Object.values(extraTerm.terms)[0][0].split('/')[1])
}
id = this.generateId(ids)
}
let recordData = _.cloneDeep(record)
recordData.lastUpdated = moment().format("Y-MM-DDTHH:mm:ss");
recordData.id = id
let query = this.generateInsertSQL(recordData, index)
this.executeSQL(query).then(() => {
return callback(null)
}).catch(() => {
return callback(null)
})
} else {
return callback(null)
}
}).catch(() => {
return callback(null)
})
}
}, () => {
return callback(null)
})
},
cleanBrokenLinks: (callback) => {
if(!orderedResource.hasOwnProperty('linkElement') || (resourceData.meta && resourceData.meta.versionId == '1')) {
return callback(null)
}
// get all documents that doesnt meet the search terms but are linked to this resource and truncate
let qry = {
query: {
bool: {
must_not: [],
must: []
}
}
}
qry.query.bool.must_not = [{
terms: allTerms
}]
let recordFields = Object.keys(record)
let idField = recordFields[recordFields.length - 1]
let term = {}
term[idField] = record[idField]
qry.query.bool.must = [{
term
}]
//include extra terms
qry.query.bool.must = qry.query.bool.must.concat(extraTerms)
let childrenResources = this.getChildrenResources(orderedResource.name);
childrenResources.unshift(orderedResource)
let fields = this.getResourcesFields(childrenResources)
let ctx = ''
for(let field of fields) {
ctx += `ctx._source['${field.field}']=null;`;
}
ctx += `ctx._source.lastUpdated='${moment().format('Y-MM-DDTHH:mm:ss')}';`
let sqlquery = this.generateSelectSQL(qry, index)
this.executeSQL(sqlquery, 'SELECT').then(async(results) => {
let queryRelated = {
query: {
bool: {
should: []
}
}
}
//save fields that are used to test if two docs are the same
let compFieldsRelDocs = []
let ids = []