This repository has been archived by the owner on Oct 21, 2022. It is now read-only.
/
Adaptor.js
1874 lines (1716 loc) · 92 KB
/
Adaptor.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";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.execute = execute;
exports.getTEIs = getTEIs;
exports.upsertTEI = upsertTEI;
exports.createTEI = createTEI;
exports.updateTEI = updateTEI;
exports.getEvents = getEvents;
exports.createEvents = createEvents;
exports.updateEvents = updateEvents;
exports.getPrograms = getPrograms;
exports.createPrograms = createPrograms;
exports.updatePrograms = updatePrograms;
exports.getEnrollments = getEnrollments;
exports.enrollTEI = enrollTEI;
exports.updateEnrollments = updateEnrollments;
exports.cancelEnrollment = cancelEnrollment;
exports.completeEnrollment = completeEnrollment;
exports.getRelationships = getRelationships;
exports.getDataValues = getDataValues;
exports.createDataValues = createDataValues;
exports.generateDhis2UID = generateDhis2UID;
exports.discover = discover;
exports.getAnalytics = getAnalytics;
exports.getResources = getResources;
exports.getSchema = getSchema;
exports.getData = getData;
exports.getMetadata = getMetadata;
exports.create = create;
exports.update = update;
exports.patch = patch;
exports.del = del;
exports.upsert = upsert;
exports.attrVal = attrVal;
Object.defineProperty(exports, "field", {
enumerable: true,
get: function get() {
return _languageCommon.field;
}
});
Object.defineProperty(exports, "fields", {
enumerable: true,
get: function get() {
return _languageCommon.fields;
}
});
Object.defineProperty(exports, "sourceValue", {
enumerable: true,
get: function get() {
return _languageCommon.sourceValue;
}
});
Object.defineProperty(exports, "merge", {
enumerable: true,
get: function get() {
return _languageCommon.merge;
}
});
Object.defineProperty(exports, "each", {
enumerable: true,
get: function get() {
return _languageCommon.each;
}
});
Object.defineProperty(exports, "dataPath", {
enumerable: true,
get: function get() {
return _languageCommon.dataPath;
}
});
Object.defineProperty(exports, "dataValue", {
enumerable: true,
get: function get() {
return _languageCommon.dataValue;
}
});
Object.defineProperty(exports, "lastReferenceValue", {
enumerable: true,
get: function get() {
return _languageCommon.lastReferenceValue;
}
});
Object.defineProperty(exports, "alterState", {
enumerable: true,
get: function get() {
return _languageCommon.alterState;
}
});
Object.defineProperty(exports, "fn", {
enumerable: true,
get: function get() {
return _languageCommon.fn;
}
});
Object.defineProperty(exports, "http", {
enumerable: true,
get: function get() {
return _languageCommon.http;
}
});
Object.defineProperty(exports, "attribute", {
enumerable: true,
get: function get() {
return _Utils.attribute;
}
});
var _axios = _interopRequireDefault(require("axios"));
var _languageCommon = require("@openfn/language-common");
var _lodash = require("lodash");
var _Utils = require("./Utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Execute a sequence of operations.
* Wraps `language-common/execute`, and prepends initial state for DHIS2.
* @example
* execute(
* create('foo'),
* delete('bar')
* )(state)
* @constructor
* @param {Operations} operations - Operations to be performed.
* @returns {Operation}
*/
function execute() {
for (var _len = arguments.length, operations = new Array(_len), _key = 0; _key < _len; _key++) {
operations[_key] = arguments[_key];
}
var initialState = {
references: [],
data: null
};
return function (state) {
return _languageCommon.execute.apply(void 0, [configMigrationHelper].concat(operations))(_objectSpread({}, initialState, {}, state));
};
}
/**
* Migrates `apiUrl` to `hostUrl` if `hostUrl` is `blank`.
* For `OpenFn.org` users with the `old-style configuration`.
* @example
* configMigrationHelper(state)
* @constructor
* @param {object} state - the runtime state
* @returns {object}
*/
function configMigrationHelper(state) {
var _state$configuration = state.configuration,
hostUrl = _state$configuration.hostUrl,
apiUrl = _state$configuration.apiUrl;
if (!hostUrl) {
_Utils.Log.warn('DEPRECATION WARNING: Please migrate instance address from `apiUrl` to `hostUrl`.');
state.configuration.hostUrl = apiUrl;
return state;
}
return state;
}
_axios["default"].interceptors.response.use(function (response) {
var _response$headers$con, _response;
var contentType = (_response$headers$con = response.headers['content-type']) === null || _response$headers$con === void 0 ? void 0 : _response$headers$con.split(';')[0];
var acceptHeaders = response.config.headers['Accept'].split(';')[0].split(',');
if (response.config.method === 'get') {
if ((0, _lodash.indexOf)(acceptHeaders, contentType) === -1) {
var newError = {
status: 404,
message: 'Unexpected content,returned',
responseData: response.data
};
_Utils.Log.error(newError.message);
return Promise.reject(newError);
}
}
if (typeof ((_response = response) === null || _response === void 0 ? void 0 : _response.data) === 'string' && contentType === (_Utils.CONTENT_TYPES === null || _Utils.CONTENT_TYPES === void 0 ? void 0 : _Utils.CONTENT_TYPES.json)) {
try {
response = _objectSpread({}, response, {
data: JSON.parse(response.data)
});
} catch (error) {
/* Keep quiet */
}
}
return response;
}, function (error) {
_Utils.Log.error("".concat(error === null || error === void 0 ? void 0 : error.message));
return Promise.reject(JSON.stringify(error.response.data, null, 2));
});
/**
* Get Tracked Entity Instance(s).
* @public
* @function
* @param {Object} [params] - Optional `query parameters` e.g. `{ou: 'DiszpKrYNg8', filters: ['lZGmxYbs97q':GT:5']}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html DHIS2 docs} for more details on which params to use when querying tracked entities instances.
* @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `getTEIs` operation. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`.
* @param {function} [callback] - Optional callback to handle the response.
* @returns {Operation}
* @example <caption>- Example `getTEIs` `expression.js` for fetching a `single` `Tracked Entity Instance` with all the fields included.</caption>
* getTEIs({
* fields: '*',
* ou: 'CMqUILyVnBL',
* trackedEntityInstance: 'HNTA9qD6EEG',
* skipPaging: true,
* });
*/
function getTEIs(params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'getTEIs';else {
options = {
operationName: 'getTEIs'
};
}
return getData('trackedEntityInstances', params, options, callback)(state);
};
}
/**
* Update TEI if exists otherwise create.
* - Update if the record exists otherwise insert a new record.
* - This is useful for idempotency and duplicate record management.
* @public
* @function
* @param {string} uniqueAttributeId - Tracked Entity Instance unique identifier attribute used during matching.
* @param {Object} data - Payload data for new tracked entity instance or updated data for an existing tracked entity instance.
* @param {{apiVersion: number,strict: boolean,responseType: string}} [options] - `Optional` options for `upsertTEI` operation. Defaults to `{apiVersion: state.configuration.apiVersion,strict: true,responseType: 'json'}`.
* @param {function} [callback] - Optional `callback` to handle the response.
* @throws {RangeError} - Throws `RangeError` when `uniqueAttributeId` is `invalid` or `not unique`.
* @returns {Operation}
* @example <caption>- Example `expression.js` for upserting a tracked entity instance on attribute with Id `lZGmxYbs97q`.</caption>
* upsertTEI('lZGmxYbs97q', {
* orgUnit: 'TSyzvBiovKh',
* trackedEntityType: 'nEenWmSyUEp',
* attributes: [
* {
* attribute: 'lZGmxYbs97q',
* value: '77790012',
* },
* {
* attribute: 'w75KJ2mc4zz',
* value: 'Gigiwe',
* },
* {
* attribute: 'zDhUuAYrxNC',
* value: 'Mwanza',
* },
* ],
* });
*/
function upsertTEI(uniqueAttributeId, data, options, callback) {
return function (state) {
var _options$apiVersion, _options, _options$strict, _options2, _body$attributes, _body$attributes$find;
uniqueAttributeId = (0, _languageCommon.expandReferences)(uniqueAttributeId)(state);
var body = (0, _languageCommon.expandReferences)(data)(state);
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'upsertTEI';else {
options = {
operationName: 'upsertTEI'
};
}
var _state$configuration2 = state.configuration,
password = _state$configuration2.password,
username = _state$configuration2.username,
hostUrl = _state$configuration2.hostUrl;
var apiVersion = (_options$apiVersion = (_options = options) === null || _options === void 0 ? void 0 : _options.apiVersion) !== null && _options$apiVersion !== void 0 ? _options$apiVersion : state.configuration.apiVersion;
var strict = (_options$strict = (_options2 = options) === null || _options2 === void 0 ? void 0 : _options2.strict) !== null && _options$strict !== void 0 ? _options$strict : true;
var params = {
ou: body.orgUnit
};
var uniqueAttributeValue = (_body$attributes = body.attributes) === null || _body$attributes === void 0 ? void 0 : (_body$attributes$find = _body$attributes.find(function (obj) {
return (obj === null || obj === void 0 ? void 0 : obj.attribute) === uniqueAttributeId;
})) === null || _body$attributes$find === void 0 ? void 0 : _body$attributes$find.value;
var trackedEntityType = body.trackedEntityType;
var uniqueAttributeUrl = (0, _Utils.buildUrl)("/trackedEntityAttributes/".concat(uniqueAttributeId), hostUrl, apiVersion);
var trackedEntityTypeUrl = (0, _Utils.buildUrl)("/trackedEntityTypes/".concat(trackedEntityType, "?fields=*"), hostUrl, apiVersion);
var findTrackedEntityType = function findTrackedEntityType() {
return _axios["default"].get(trackedEntityTypeUrl, {
auth: {
username: username,
password: password
}
}).then(function (result) {
var _result$data, _result$data$trackedE;
var attribute = (_result$data = result.data) === null || _result$data === void 0 ? void 0 : (_result$data$trackedE = _result$data.trackedEntityTypeAttributes) === null || _result$data$trackedE === void 0 ? void 0 : _result$data$trackedE.find(function (obj) {
var _obj$trackedEntityAtt;
return (obj === null || obj === void 0 ? void 0 : (_obj$trackedEntityAtt = obj.trackedEntityAttribute) === null || _obj$trackedEntityAtt === void 0 ? void 0 : _obj$trackedEntityAtt.id) === uniqueAttributeId;
});
return _objectSpread({}, result.data, {
upsertAttributeAssigned: attribute ? true : false
});
});
};
var isAttributeUnique = function isAttributeUnique() {
return _axios["default"].get(uniqueAttributeUrl, {
auth: {
username: username,
password: password
}
}).then(function (result) {
var foundAttribute = result.data;
return {
unique: foundAttribute.unique,
name: foundAttribute.name
};
});
};
return Promise.all([findTrackedEntityType(), strict === true ? isAttributeUnique() : Promise.resolve({
unique: true
})]).then(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
entityType = _ref2[0],
attribute = _ref2[1];
if (!entityType.upsertAttributeAssigned) {
_Utils.Log.error('');
throw new RangeError("Tracked Entity Attribute ".concat(uniqueAttributeId, " is not assigned to the ").concat(entityType.name, " Entity Type."));
}
if (!attribute.unique) {
var _attribute$name;
_Utils.Log.error('');
throw new RangeError("Attribute ".concat((_attribute$name = attribute.name) !== null && _attribute$name !== void 0 ? _attribute$name : '', "(").concat(uniqueAttributeId, ") is not marked as unique."));
}
return upsert('trackedEntityInstances', {
attributeId: uniqueAttributeId,
attributeValue: uniqueAttributeValue
}, body, params, options, callback)(state);
});
};
}
/**
* Create Tracked Entity Instance.
* @public
* @function
* @param {Object} data - The update data containing new values.
* @param {Object} [params] - Optional `import parameters` for a given a resource. E.g. `{dryRun: true, importStrategy: CREATE}` See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#import-parameters_1 DHIS2 Import parameters documentation} or run `discover`. Defauls to `DHIS2 default import parameters`.
* @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `createTEI` operation. Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`.
* @param {function} [callback] - Optional callback to handle the response.
* @returns {Operation}
* @example <caption>- Example `expression.js` of `createTEI`.</caption>
* createTEI({
* orgUnit: 'TSyzvBiovKh',
* trackedEntityType: 'nEenWmSyUEp',
* attributes: [
* {
* attribute: 'lZGmxYbs97q',
* value: valUpsertTEI,
* },
* {
* attribute: 'w75KJ2mc4zz',
* value: 'Gigiwe',
* },
* ],
* enrollments: [
* {
* orgUnit: 'TSyzvBiovKh',
* program: 'fDd25txQckK',
* programState: 'lST1OZ5BDJ2',
* enrollmentDate: '2021-01-04',
* incidentDate: '2021-01-04',
* },
* ],
* });
*/
function createTEI(data, params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'createTEI';else {
options = {
operationName: 'createTEI'
};
}
return create('trackedEntityInstances', data, params, options, callback)(state);
};
}
/**
* Update a Tracked Entity Instance.
* @public
* @function
* @param {string} path - Path to the object being updated. This can be an `id` or path to an `object` in a `nested collection` on the object(E.g. `/api/{collection-object}/{collection-object-id}/{collection-name}/{object-id}`).
* @param {Object} data - The update data containing new values.
* @param {Object} [params] - Optional `import parameters` for a given a resource. E.g. `{dryRun: true, importStrategy: CREATE, filters:[]}` See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#import-parameters_1 DHIS2 Import parameters documentation} or run `discover`. Defauls to `DHIS2 default import parameters`.
* @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `updateTEI` operation. Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`.
* @param {function} [callback] - Optional callback to handle the response.
* @returns {Operation}
* @example <caption>- Example `expression.js` of `updateTEI`.</caption>
* updateTEI('PVqUD2hvU4E', {
* orgUnit: 'TSyzvBiovKh',
* trackedEntityType: 'nEenWmSyUEp',
* attributes: [
* {
* attribute: 'lZGmxYbs97q',
* value: valUpsertTEI,
* },
* {
* attribute: 'w75KJ2mc4zz',
* value: 'Gigiwe',
* },
* ],
* enrollments: [
* {
* orgUnit: 'TSyzvBiovKh',
* program: 'fDd25txQckK',
* programState: 'lST1OZ5BDJ2',
* enrollmentDate: '2021-01-04',
* incidentDate: '2021-01-04',
* },
* ],
* });
*/
function updateTEI(path, data, params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'updateTEI';else {
options = {
operationName: 'updateTEI'
};
}
return update('trackedEntityInstances', path, data, params, options, callback)(state);
};
}
/**
* Get annonymous events or tracker events.
* @public
* @function
* @param {Object} params - `import` parameters for `getEvents`. See examples here
* @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `getEvents` operation. Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`.
* @param {function} [callback] - Optional callback to handle the response.
* @returns {Operation}
* @example <caption>- Query for `all events` with `children` of a certain `organisation unit`</caption>
* getEvents({ orgUnit: 'YuQRtpLP10I', ouMode: 'CHILDREN' });
*/
function getEvents(params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'getEvents';else {
options = {
operationName: 'getEvents'
};
}
return getData('events', params, responseType, options, callback)(state);
};
}
/**
* Create DHIS2 Events
* - You will need a `program` which can be looked up using the `getPrograms` operation, an `orgUnit` which can be looked up using the `getMetadata` operation and passing `{organisationUnits: true}` as `resources` param, and a list of `valid data element identifiers` which can be looked up using the `getMetadata` passing `{dataElements: true}` as `resources` param.
* - For events with registration, a `tracked entity instance identifier is required`
* - For sending `events` to `programs with multiple stages`, you will need to also include the `programStage` identifier, the identifiers for `programStages` can be found in the `programStages` resource via a call to `getMetadata` operation.
* @public
* @function
* @param {Object} data - The payload containing new values
* @param {Object} [params] - Optional `import parameters` for events. E.g. `{dryRun: true, importStrategy: CREATE, filters:[]}` See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#events DHIS2 Event Import parameters documentation} or run `discover`. Defauls to `DHIS2 default import parameters`.
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `createEvents` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation} state
* @example <caption>- Example `expression.js` of `createEvents` for a `single event` can look like this:</caption>
* createEvents({
* program: 'eBAyeGv0exc',
* orgUnit: 'DiszpKrYNg8',
* eventDate: date,
* status: 'COMPLETED',
* completedDate: date,
* storedBy: 'admin',
* coordinate: {
* latitude: 59.8,
* longitude: 10.9,
* },
* dataValues: [
* {
* dataElement: 'qrur9Dvnyt5',
* value: '33',
* },
* {
* dataElement: 'oZg33kd9taw',
* value: 'Male',
* },
* {
* dataElement: 'msodh3rEMJa',
* value: date,
* },
* ],
* });
*/
function createEvents(data, params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'createEvents';else {
options = {
operationName: 'createEvents'
};
}
return create('events', data, params, options, callback)(state);
};
}
/**
* Update DHIS2 Event.
* - To update an existing event, the format of the payload is the same as that of `creating an event` via `createEvents` operations
* - But you should supply the `identifier` of the object you are updating
* - The payload has to contain `all`, even `non-modified`, `attributes`.
* - Attributes that were present before and are not present in the current payload any more will be removed by DHIS2.
* - If you do not want this behavior, please use `upsert` operation to upsert your events.
* @public
* @function
* @param {string} path - Path to the object being updated. This can be an `id` or path to an `object` in a `nested collection` on the object(E.g. `/api/{collection-object}/{collection-object-id}/{collection-name}/{object-id}`)
* @param {Object} data - The update data containing new values
* @param {Object} [params] - Optional `import` parameters for `updateEvents`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `updateEvents` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- Example `expression.js` of `updateEvents`</caption>
* updateEvents('PVqUD2hvU4E', { events: [
* {
* program: 'eBAyeGv0exc',
* orgUnit: 'DiszpKrYNg8',
* eventDate: date,
* status: 'COMPLETED',
* storedBy: 'admin',
* coordinate: {
* latitude: '59.8',
* longitude: '10.9',
* },
* dataValues: [
* {
* dataElement: 'qrur9Dvnyt5',
* value: '22',
* },
* {
* dataElement: 'oZg33kd9taw',
* value: 'Male',
* },
* ],
* }]
* });
*/
function updateEvents(path, data, params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'updateEvents';else {
options = {
operationName: 'updateEvents'
};
}
return update('events', path, data, params, options, callback)(state);
};
}
/**
* Get DHIS2 Tracker Programs.
* @public
* @function
* @param {Object} params - `import` parameters for `getPrograms`. See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#tracker-web-api DHIS2 api documentation for allowed query parameters }
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getPrograms` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- Query for `all programs` with a certain `organisation unit`</caption>
* getPrograms({ orgUnit: 'DiszpKrYNg8' , fields: '*' });
*/
function getPrograms(params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'getPrograms';else {
options = {
operationName: 'getPrograms'
};
}
return getData('programs', params, options, callback)(state);
};
}
/**
* Create a DHIS2 Tracker Program
* @public
* @function
* @param {Object} data - The update data containing new values
* @param {Object} [params] - Optional `import` parameters for `createPrograms`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getPrograms` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- Example `expression.js` of `createPrograms` for a `single program` can look like this:</caption>
* createPrograms(state.data);
*/
function createPrograms(data, params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'createPrograms';else {
options = {
operationName: 'createPrograms'
};
}
return create('programs', data, options, params, callback)(state);
};
}
/**
* Update DHIS2 Tracker Programs
* - To update an existing program, the format of the payload is the same as that of `creating an event` via `createEvents` operations
* - But you should supply the `identifier` of the object you are updating
* - The payload has to contain `all`, even `non-modified`, `attributes`.
* - Attributes that were present before and are not present in the current payload any more will be removed by DHIS2.
* - If you do not want this behavior, please use `upsert` operation to upsert your events.
* @public
* @function
* @param {string} path - Path to the object being updated. This can be an `id` or path to an `object` in a `nested collection` on the object(E.g. `/api/{collection-object}/{collection-object-id}/{collection-name}/{object-id}`)
* @param {Object} data - The update data containing new values
* @param {Object} [params] - Optional `import` parameters for `updatePrograms`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getPrograms` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- Example `expression.js` of `updatePrograms`</caption>
* updatePrograms('PVqUD2hvU4E', state.data);
*/
function updatePrograms(path, data, params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'updatePrograms';else {
options = {
operationName: 'updatePrograms'
};
}
return update('programs', path, data, params, options, callback)(state);
};
}
/**
* Get DHIS2 Enrollments
* @public
* @function
* @param {Object} params - `Query` parameters for `getEnrollments`. See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#enrollment-management here}
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getEnrollments` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- To constrain the response to `enrollments` which are part of a `specific program` you can include a `program query parameter`</caption>
* getEnrollments({
* ou: 'O6uvpzGd5pu',
* ouMode: 'DESCENDANTS',
* program: 'ur1Edk5Oe2n',
* fields: '*',
* });
*/
function getEnrollments(params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'getEnrollments';else {
options = {
operationName: 'getEnrollments'
};
}
return getData('enrollments', params, options, callback)(state);
};
}
/**
* Enroll a TEI into a program
* - Enrolling a tracked entity instance into a program
* - For enrolling `persons` into a `program`, you will need to first get the `identifier of the person` from the `trackedEntityInstances resource` via the `getTEIs` operation.
* - Then, you will need to get the `program identifier` from the `programs` resource via the `getPrograms` operation.
* @public
* @function
* @param {Object} data - The enrollment data. See example {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#enrollment-management here }
* @param {Object} [params] - Optional `import` parameters for `createEnrollment`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `enrollTEI` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- Example `expression.js` of `createEnrollment` of a `person` into a `program` can look like this:</caption>
* enrollTEI({
* trackedEntity: 'tracked-entity-id',
* orgUnit: 'org-unit-id',
* attributes: [
* {
* attribute: 'attribute-id',
* value: 'attribute-value',
* },
* ],
* enrollments: [
* {
* orgUnit: 'org-unit-id',
* program: 'program-id',
* enrollmentDate: '2013-09-17',
* incidentDate: '2013-09-17',
* },
* ],
*});
*/
function enrollTEI(data, params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'enrollTEI';else {
options = {
operationName: 'enrollTEI'
};
}
return create('enrollments', data, options, params, callback)(state);
};
}
/**
* Update a DHIS2 Enrollemts
* - To update an existing enrollment, the format of the payload is the same as that of `creating an event` via `createEvents` operations
* - But you should supply the `identifier` of the object you are updating
* - The payload has to contain `all`, even `non-modified`, `attributes`.
* - Attributes that were present before and are not present in the current payload any more will be removed by DHIS2.
* - If you do not want this behavior, please use `upsert` operation to upsert your events.
* @public
* @function
* @param {string} path - Path to the object being updated. This can be an `id` or path to an `object` in a `nested collection` on the object(E.g. `/api/{collection-object}/{collection-object-id}/{collection-name}/{object-id}`)
* @param {Object} data - The update data containing new values
* @param {Object} [params] - Optional `import` parameters for `updateEnrollments`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `updateEnrollments` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- Example `expression.js` of `updateEnromments`</caption>
* updateEnrollments('PVqUD2hvU4E', state.data);
*/
function updateEnrollments(path, data, params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'updateEnrollments';else {
options = {
operationName: 'updateEnrollments'
};
}
return update('enrollments', path, data, params, options, callback)(state);
};
}
/**
* Cancel a DHIS2 Enrollment
* - To cancel an existing enrollment, you should supply the `enrollment identifier`(`enrollemt-id`)
* @public
* @function
* @param {string} enrollmentId - The `enrollment-id` of the enrollment you wish to cancel
* @param {Object} [params] - Optional `import` parameters for `cancelEnrollment`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `cancelEnrollment` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- Example `expression.js` of `cancelEnrollment`</caption>
* cancelEnrollments('PVqUD2hvU4E');
*/
function cancelEnrollment(enrollmentId, params, options, callback) {
return function (state) {
enrollmentId = (0, _languageCommon.expandReferences)(enrollmentId)(state);
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'cancelEnrollment';else {
options = {
operationName: 'cancelEnrollment'
};
}
var path = "".concat(enrollmentId, "/cancelled");
return update('enrollments', path, null, params, options, callback)(state);
};
}
/**
* Complete a DHIS2 Enrollment
* - To complete an existing enrollment, you should supply the `enrollment identifier`(`enrollemt-id`)
* @public
* @function
* @param {string} enrollmentId - The `enrollment-id` of the enrollment you wish to cancel
* @param {Object} [params] - Optional `import` parameters for `completeEnrollment`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `completeEnrollment` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- Example `expression.js` of `completeEnrollment`</caption>
* completeEnrollment('PVqUD2hvU4E');
*/
function completeEnrollment(enrollmentId, params, options, callback) {
return function (state) {
enrollmentId = (0, _languageCommon.expandReferences)(enrollmentId)(state);
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'completeEnrollment';else {
options = {
operationName: 'completeEnrollment'
};
}
var path = "".concat(enrollmentId, "/completed");
return update('enrollments', path, null, params, options, callback)(state);
};
}
/**
* Get DHIS2 Relationships(links) between two entities in tracker. These entities can be tracked entity instances, enrollments and events.
* - All the tracker operations, `getTEIs`, `getEnrollments` and `getEvents` also list their relationships if requested in the `field` filter.
* - To list all relationships, this requires you to provide the UID of the trackedEntityInstance, Enrollment or event that you want to list all the relationships for.
* @public
* @function
* @param {Object} params - `Query` parameters for `getRelationships`. See examples {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#relationships here}
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getRelationships` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- A query for `all relationships` associated with a `specific tracked entity instance` can look like this:</caption>
* getRelationships({ tei: 'F8yKM85NbxW', fields: '*' });
*/
function getRelationships(params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'getRelationships';else {
options = {
operationName: 'getRelationships'
};
}
return getData('relationships', params, options, callback)(state);
};
}
/**
* Get DHIS2 Data Values.
* - This operation retrives data values from DHIS2 Web API by interacting with the `dataValueSets` resource
* - Data values can be retrieved in XML, JSON and CSV format.
* @public
* @function
* @param {Object} params - `Query` parameters for `getDataValues`. E.g. `{dataset: 'pBOMPrpg1QX', limit: 3, period: 2021, orgUnit: 'DiszpKrYNg8'} Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#data-values DHIS2 API docs} for available `Data Value Set Query Parameters`.
* @param {{apiVersion: number,responseType: string}} [options] - Optional `options` for `getDataValues` operation. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`
* @param {function} [callback] - Optional `callback` to handle the response
* @returns {Operation}
* @example <caption>- Example getting **two** `data values` associated with a specific `orgUnit`, `dataSet`, and `period `</caption>
* getDataValues({
* orgUnit: 'DiszpKrYNg8',
* period: '202010',
* dataSet: 'pBOMPrpg1QX',
* limit: 2,
* });
*/
function getDataValues(params, options, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'getDataValues';else {
options = {
operationName: 'getDataValues'
};
}
return getData('dataValueSets', params, options, callback)(state);
};
}
/**
* Create DHIS2 Data Values
* - This is used to send aggregated data to DHIS2
* - A data value set represents a set of data values which have a relationship, usually from being captured off the same data entry form.
* - To send a set of related data values sharing the same period and organisation unit, we need to identify the period, the data set, the org unit (facility) and the data elements for which to report.
* - You can also use this operation to send large bulks of data values which don't necessarily are logically related.
* - To send data values that are not linked to a `dataSet`, you do not need to specify the dataSet and completeDate attributes. Instead, you will specify the period and orgUnit attributes on the individual data value elements instead of on the outer data value set element. This will enable us to send data values for various periods and organisation units
* @public
* @function
* @param {object} data - The `data values` to upload or create. See example shape.
* @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `createDataVaues` operation.
* @param {object} [params] - Optional `import` parameters for `createDataValues`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`. Run `discover` or visit {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#data-values DHIS2 Docs API} to learn about available data values import parameters.
* @param {function} [callback] - Optional callback to handle the response
* @returns {Operation}
* @example <caption>- Example `expression.js` of `createDataValues` for sending a set of related data values sharing the same period and organisation unit</caption>
* createDataValues({
* dataSet: 'pBOMPrpg1QX',
* completeDate: '2014-02-03',
* period: '201401',
* orgUnit: 'DiszpKrYNg8',
* dataValues: [
* {
* dataElement: 'f7n9E0hX8qk',
* value: '1',
* },
* {
* dataElement: 'Ix2HsbDMLea',
* value: '2',
* },
* {
* dataElement: 'eY5ehpbEsB7',
* value: '3',
* },
* ],
* });
*/
function createDataValues(data, options, params, callback) {
return function (state) {
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'createDataValues';else {
options = {
operationName: 'createDataValues'
};
}
return create('dataValueSets', data, options, params, callback)(state);
};
}
/**
* Generate valid, random DHIS2 identifiers
* - Useful for client generated Ids compatible with DHIS2
* @public
* @function
* @param {{apiVersion: number,limit: number,responseType: string}} [options] - Optional `options` for `generateDhis2UID` operation. Defaults to `{apiVersion: state.configuration.apiVersion,limit: 1,responseType: 'json'}`
* @param {function} [callback] - Callback to handle response
* @returns {Operation}
* @example <caption>Example generating `three UIDs` from the DHIS2 server</caption>
* generateDhis2UID({limit: 3});
*/
function generateDhis2UID(options, callback) {
return function (state) {
var _options$limit, _options3, _options4;
options = (0, _languageCommon.expandReferences)(options)(state);
if (options) options.operationName = 'generateDhis2UID';else {
options = {
operationName: 'generateDhis2UID'
};
}
var limit = {
limit: (_options$limit = (_options3 = options) === null || _options3 === void 0 ? void 0 : _options3.limit) !== null && _options$limit !== void 0 ? _options$limit : 1
};
(_options4 = options) === null || _options4 === void 0 ? true : delete _options4.limit;
return getData('system/id', limit, options, callback)(state);
};
}
/**
* Discover `DHIS2` `api` `endpoint` `query parameters` and allowed `operators` for a given resource's endpoint.
* @public
* @function
* @param {string} httpMethod - The HTTP to inspect parameter usage for a given endpoint, e.g., `get`, `post`,`put`,`patch`,`delete`
* @param {string} endpoint - The path for a given endpoint. E.g. `/trackedEntityInstances` or `/dataValueSets`
* @returns {Operation}
* @example <caption>Example getting a list of `parameters allowed` on a given `endpoint` for specific `http method`</caption>
* discover('post', '/trackedEntityInstances')
*/