@openfn/language-dhis2 2.0.11 → 3.0.0-4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +39 -4
  2. package/ast.json +220 -2573
  3. package/lib/Adaptor.js +548 -1636
  4. package/lib/Client.js +48 -0
  5. package/lib/Utils.js +50 -183
  6. package/lib/index.js +4 -6
  7. package/node_modules/@openfn/language-common/node_modules/axios/package.json +20 -0
  8. package/node_modules/@openfn/language-common/node_modules/follow-redirects/package.json +20 -0
  9. package/node_modules/@openfn/language-common/node_modules/jsonpath-plus/package.json +20 -0
  10. package/node_modules/@openfn/language-common/node_modules/lodash/package.json +20 -0
  11. package/node_modules/@openfn/language-common/package.json +8 -4
  12. package/node_modules/axios/CHANGELOG.md +159 -8
  13. package/node_modules/axios/README.md +98 -6
  14. package/node_modules/axios/SECURITY.md +5 -0
  15. package/node_modules/axios/dist/axios.js +2101 -1582
  16. package/node_modules/axios/dist/axios.map +1 -1
  17. package/node_modules/axios/dist/axios.min.js +1 -2
  18. package/node_modules/axios/dist/axios.min.map +1 -1
  19. package/node_modules/axios/index.d.ts +76 -31
  20. package/node_modules/axios/lib/adapters/http.js +74 -14
  21. package/node_modules/axios/lib/adapters/xhr.js +66 -33
  22. package/node_modules/axios/lib/axios.js +6 -5
  23. package/node_modules/axios/lib/cancel/CancelToken.js +62 -0
  24. package/node_modules/axios/lib/core/Axios.js +60 -7
  25. package/node_modules/axios/lib/core/InterceptorManager.js +4 -2
  26. package/node_modules/axios/lib/core/README.md +1 -0
  27. package/node_modules/axios/lib/core/dispatchRequest.js +11 -3
  28. package/node_modules/axios/lib/core/enhanceError.js +2 -1
  29. package/node_modules/axios/lib/core/mergeConfig.js +50 -38
  30. package/node_modules/axios/lib/core/transformData.js +3 -1
  31. package/node_modules/axios/lib/defaults.js +48 -12
  32. package/node_modules/axios/lib/env/README.md +3 -0
  33. package/node_modules/axios/lib/env/data.js +3 -0
  34. package/node_modules/axios/lib/helpers/validator.js +82 -0
  35. package/node_modules/axios/lib/utils.js +1 -3
  36. package/node_modules/axios/package.json +37 -40
  37. package/node_modules/axios/tsconfig.json +14 -0
  38. package/node_modules/axios/tslint.json +6 -0
  39. package/node_modules/follow-redirects/README.md +1 -1
  40. package/node_modules/follow-redirects/debug.js +14 -8
  41. package/node_modules/follow-redirects/index.js +106 -41
  42. package/node_modules/follow-redirects/package.json +14 -17
  43. package/node_modules/lodash/package.json +2 -2
  44. package/package.json +6 -5
package/lib/Adaptor.js CHANGED
@@ -4,145 +4,95 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.execute = execute;
7
- exports.getTEIs = getTEIs;
8
- exports.upsertTEI = upsertTEI;
9
- exports.createTEI = createTEI;
10
- exports.updateTEI = updateTEI;
11
- exports.getEvents = getEvents;
12
- exports.createEvents = createEvents;
13
- exports.updateEvents = updateEvents;
14
- exports.getPrograms = getPrograms;
15
- exports.createPrograms = createPrograms;
16
- exports.updatePrograms = updatePrograms;
17
- exports.getEnrollments = getEnrollments;
18
- exports.enrollTEI = enrollTEI;
19
- exports.updateEnrollments = updateEnrollments;
20
- exports.cancelEnrollment = cancelEnrollment;
21
- exports.completeEnrollment = completeEnrollment;
22
- exports.getRelationships = getRelationships;
23
- exports.getDataValues = getDataValues;
24
- exports.createDataValues = createDataValues;
25
- exports.generateDhis2UID = generateDhis2UID;
26
- exports.discover = discover;
27
- exports.getAnalytics = getAnalytics;
28
- exports.getResources = getResources;
29
- exports.getSchema = getSchema;
30
- exports.getData = getData;
31
- exports.getMetadata = getMetadata;
32
7
  exports.create = create;
33
8
  exports.update = update;
9
+ exports.get = get;
10
+ exports.discover = discover;
34
11
  exports.patch = patch;
35
- exports.del = del;
36
- exports.upsert = upsert;
37
- exports.attrVal = attrVal;
12
+ exports.destroy = destroy;
13
+ exports.findAttributeValue = findAttributeValue;
14
+ exports.attr = attr;
15
+ exports.dv = dv;
38
16
  Object.defineProperty(exports, "field", {
39
17
  enumerable: true,
40
- get: function get() {
18
+ get: function () {
41
19
  return _languageCommon.field;
42
20
  }
43
21
  });
44
22
  Object.defineProperty(exports, "fields", {
45
23
  enumerable: true,
46
- get: function get() {
24
+ get: function () {
47
25
  return _languageCommon.fields;
48
26
  }
49
27
  });
50
28
  Object.defineProperty(exports, "sourceValue", {
51
29
  enumerable: true,
52
- get: function get() {
30
+ get: function () {
53
31
  return _languageCommon.sourceValue;
54
32
  }
55
33
  });
56
34
  Object.defineProperty(exports, "merge", {
57
35
  enumerable: true,
58
- get: function get() {
36
+ get: function () {
59
37
  return _languageCommon.merge;
60
38
  }
61
39
  });
62
40
  Object.defineProperty(exports, "each", {
63
41
  enumerable: true,
64
- get: function get() {
42
+ get: function () {
65
43
  return _languageCommon.each;
66
44
  }
67
45
  });
68
46
  Object.defineProperty(exports, "dataPath", {
69
47
  enumerable: true,
70
- get: function get() {
48
+ get: function () {
71
49
  return _languageCommon.dataPath;
72
50
  }
73
51
  });
74
52
  Object.defineProperty(exports, "dataValue", {
75
53
  enumerable: true,
76
- get: function get() {
54
+ get: function () {
77
55
  return _languageCommon.dataValue;
78
56
  }
79
57
  });
80
58
  Object.defineProperty(exports, "lastReferenceValue", {
81
59
  enumerable: true,
82
- get: function get() {
60
+ get: function () {
83
61
  return _languageCommon.lastReferenceValue;
84
62
  }
85
63
  });
86
64
  Object.defineProperty(exports, "alterState", {
87
65
  enumerable: true,
88
- get: function get() {
66
+ get: function () {
89
67
  return _languageCommon.alterState;
90
68
  }
91
69
  });
92
70
  Object.defineProperty(exports, "fn", {
93
71
  enumerable: true,
94
- get: function get() {
72
+ get: function () {
95
73
  return _languageCommon.fn;
96
74
  }
97
75
  });
98
76
  Object.defineProperty(exports, "http", {
99
77
  enumerable: true,
100
- get: function get() {
78
+ get: function () {
101
79
  return _languageCommon.http;
102
80
  }
103
81
  });
104
- Object.defineProperty(exports, "attribute", {
105
- enumerable: true,
106
- get: function get() {
107
- return _Utils.attribute;
108
- }
109
- });
110
82
 
111
83
  var _axios = _interopRequireDefault(require("axios"));
112
84
 
113
- var _languageCommon = require("@openfn/language-common");
114
-
115
85
  var _lodash = require("lodash");
116
86
 
117
- var _Utils = require("./Utils");
118
-
119
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
120
-
121
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
122
-
123
- 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."); }
124
-
125
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
126
-
127
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
128
-
129
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
130
-
131
- 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."); }
132
-
133
- 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); }
134
-
135
- 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; }
136
-
137
- 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; }
87
+ var _languageCommon = require("@openfn/language-common");
138
88
 
139
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
89
+ var _Utils = require("./Utils");
140
90
 
141
- 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; }
91
+ var _Client = require("./Client");
142
92
 
143
- 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; }
93
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
144
94
 
145
- 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; }
95
+ /** @module Adaptor */
146
96
 
147
97
  /**
148
98
  * Execute a sequence of operations.
@@ -156,17 +106,15 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope
156
106
  * @param {Operations} operations - Operations to be performed.
157
107
  * @returns {Operation}
158
108
  */
159
- function execute() {
160
- for (var _len = arguments.length, operations = new Array(_len), _key = 0; _key < _len; _key++) {
161
- operations[_key] = arguments[_key];
162
- }
163
-
164
- var initialState = {
109
+ function execute(...operations) {
110
+ const initialState = {
165
111
  references: [],
166
112
  data: null
167
113
  };
168
- return function (state) {
169
- return _languageCommon.execute.apply(void 0, [configMigrationHelper].concat(operations))(_objectSpread({}, initialState, {}, state));
114
+ return state => {
115
+ return (0, _languageCommon.execute)(configMigrationHelper, ...operations)({ ...initialState,
116
+ ...state
117
+ });
170
118
  };
171
119
  }
172
120
  /**
@@ -181,9 +129,10 @@ function execute() {
181
129
 
182
130
 
183
131
  function configMigrationHelper(state) {
184
- var _state$configuration = state.configuration,
185
- hostUrl = _state$configuration.hostUrl,
186
- apiUrl = _state$configuration.apiUrl;
132
+ const {
133
+ hostUrl,
134
+ apiUrl
135
+ } = state.configuration;
187
136
 
188
137
  if (!hostUrl) {
189
138
  _Utils.Log.warn('DEPRECATION WARNING: Please migrate instance address from `apiUrl` to `hostUrl`.');
@@ -193,19 +142,21 @@ function configMigrationHelper(state) {
193
142
  }
194
143
 
195
144
  return state;
196
- }
145
+ } // NOTE: In order to prevent unintended exposure of authentication information
146
+ // in the logs, we make use of an axios interceptor.
197
147
 
198
- _axios["default"].interceptors.response.use(function (response) {
148
+
149
+ _axios.default.interceptors.response.use(function (response) {
199
150
  var _response$headers$con, _response;
200
151
 
201
- var contentType = (_response$headers$con = response.headers['content-type']) === null || _response$headers$con === void 0 ? void 0 : _response$headers$con.split(';')[0];
202
- var acceptHeaders = response.config.headers['Accept'].split(';')[0].split(',');
152
+ const contentType = (_response$headers$con = response.headers['content-type']) === null || _response$headers$con === void 0 ? void 0 : _response$headers$con.split(';')[0];
153
+ const acceptHeaders = response.config.headers['Accept'].split(';')[0].split(',');
203
154
 
204
155
  if (response.config.method === 'get') {
205
156
  if ((0, _lodash.indexOf)(acceptHeaders, contentType) === -1) {
206
- var newError = {
157
+ const newError = {
207
158
  status: 404,
208
- message: 'Unexpected content,returned',
159
+ message: 'Unexpected content returned',
209
160
  responseData: response.data
210
161
  };
211
162
 
@@ -217,1658 +168,619 @@ _axios["default"].interceptors.response.use(function (response) {
217
168
 
218
169
  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)) {
219
170
  try {
220
- response = _objectSpread({}, response, {
171
+ response = { ...response,
221
172
  data: JSON.parse(response.data)
222
- });
173
+ };
223
174
  } catch (error) {
224
- /* Keep quiet */
175
+ _Utils.Log.warn('Non-JSON response detected, unable to parse.');
225
176
  }
226
177
  }
227
178
 
228
179
  return response;
229
180
  }, function (error) {
230
- _Utils.Log.error("".concat(error === null || error === void 0 ? void 0 : error.message));
181
+ var _error$config, _error$config2, _error$response, _error$response$data, _error$response2;
182
+
183
+ if ((_error$config = error.config) === null || _error$config === void 0 ? void 0 : _error$config.auth) error.config.auth = '--REDACTED--';
184
+ if ((_error$config2 = error.config) === null || _error$config2 === void 0 ? void 0 : _error$config2.data) error.config.data = '--REDACTED--';
185
+ const details = (_error$response = error.response) === null || _error$response === void 0 ? void 0 : (_error$response$data = _error$response.data) === null || _error$response$data === void 0 ? void 0 : _error$response$data.response;
186
+
187
+ _Utils.Log.error(error.message || "That didn't work.");
231
188
 
232
- return Promise.reject(JSON.stringify(error.response.data, null, 2));
189
+ if (details) console.log(JSON.stringify(details, null, 2));
190
+ return Promise.reject({
191
+ request: error.config,
192
+ error: error.message,
193
+ response: (_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : _error$response2.data
194
+ });
233
195
  });
234
196
  /**
235
- * Get Tracked Entity Instance(s).
197
+ * Create a record
236
198
  * @public
237
199
  * @function
238
- * @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.
239
- * @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `getTEIs` operation. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`.
240
- * @param {function} [callback] - Optional callback to handle the response.
200
+ * @param {string} resourceType - Type of resource to create. E.g. `trackedEntityInstances`, `programs`, `events`, ...
201
+ * @param {Object} data - Data that will be used to create a given instance of resource. To create a single instance of a resource, `data` must be a javascript object, and to create multiple instances of a resources, `data` must be an array of javascript objects.
202
+ * @param {Object} [options] - Optional `options` to define URL parameters via params (E.g. `filter`, `dimension` and other import parameters), request config (E.g. `auth`) and the DHIS2 apiVersion.
203
+ * @param {function} [callback] - Optional callback to handle the response
241
204
  * @returns {Operation}
242
- * @example <caption>- Example `getTEIs` `expression.js` for fetching a `single` `Tracked Entity Instance` with all the fields included.</caption>
243
- * getTEIs({
244
- * fields: '*',
245
- * ou: 'CMqUILyVnBL',
246
- * trackedEntityInstance: 'HNTA9qD6EEG',
247
- * skipPaging: true,
205
+ * @example <caption>a program</caption>
206
+ * create('programs', {
207
+ * name: 'name 20',
208
+ * shortName: 'n20',
209
+ * programType: 'WITHOUT_REGISTRATION',
210
+ * });
211
+ * @example <caption>an event</caption>
212
+ * create('events', {
213
+ * program: 'eBAyeGv0exc',
214
+ * orgUnit: 'DiszpKrYNg8',
215
+ * status: 'COMPLETED',
216
+ * });
217
+ * @example <caption>a trackedEntityInstance</caption>
218
+ * create('trackedEntityInstances', {
219
+ * orgUnit: 'TSyzvBiovKh',
220
+ * trackedEntityType: 'nEenWmSyUEp',
221
+ * attributes: [
222
+ * {
223
+ * attribute: 'w75KJ2mc4zz',
224
+ * value: 'Gigiwe',
225
+ * },
226
+ * ]
227
+ * });
228
+ * @example <caption>a dataSet</caption>
229
+ * create('dataSets', { name: 'OpenFn Data Set', periodType: 'Monthly' });
230
+ * @example <caption>a dataSetNotification</caption>
231
+ * create('dataSetNotificationTemplates', {
232
+ * dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
233
+ * notificationRecipient: 'ORGANISATION_UNIT_CONTACT',
234
+ * name: 'Notification',
235
+ * messageTemplate: 'Hello',
236
+ * deliveryChannels: ['SMS'],
237
+ * dataSets: [],
238
+ * });
239
+ * @example <caption>a dataElement</caption>
240
+ * create('dataElements', {
241
+ * aggregationType: 'SUM',
242
+ * domainType: 'AGGREGATE',
243
+ * valueType: 'NUMBER',
244
+ * name: 'Paracetamol',
245
+ * shortName: 'Para',
246
+ * });
247
+ * @example <caption>a dataElementGroup</caption>
248
+ * create('dataElementGroups', {
249
+ * name: 'Data Element Group 1',
250
+ * dataElements: [],
251
+ * });
252
+ * @example <caption>a dataElementGroupSet</caption>
253
+ * create('dataElementGroupSets', {
254
+ * name: 'Data Element Group Set 4',
255
+ * dataDimension: true,
256
+ * shortName: 'DEGS4',
257
+ * dataElementGroups: [],
258
+ * });
259
+ * @example <caption>a dataValueSet</caption>
260
+ * create('dataValueSets', {
261
+ * dataElement: 'f7n9E0hX8qk',
262
+ * period: '201401',
263
+ * orgUnit: 'DiszpKrYNg8',
264
+ * value: '12',
265
+ * });
266
+ * @example <caption>a dataValueSet with related dataValues</caption>
267
+ * create('dataValueSets', {
268
+ * dataSet: 'pBOMPrpg1QX',
269
+ * completeDate: '2014-02-03',
270
+ * period: '201401',
271
+ * orgUnit: 'DiszpKrYNg8',
272
+ * dataValues: [
273
+ * {
274
+ * dataElement: 'f7n9E0hX8qk',
275
+ * value: '1',
276
+ * },
277
+ * {
278
+ * dataElement: 'Ix2HsbDMLea',
279
+ * value: '2',
280
+ * },
281
+ * {
282
+ * dataElement: 'eY5ehpbEsB7',
283
+ * value: '3',
284
+ * },
285
+ * ],
286
+ * });
287
+ * @example <caption>an enrollment</caption>
288
+ * create('enrollments', {
289
+ * trackedEntityInstance: 'bmshzEacgxa',
290
+ * orgUnit: 'TSyzvBiovKh',
291
+ * program: 'gZBxv9Ujxg0',
292
+ * enrollmentDate: '2013-09-17',
293
+ * incidentDate: '2013-09-17',
248
294
  * });
249
295
  */
250
296
 
251
297
 
252
- function getTEIs(params, options, callback) {
253
- return function (state) {
298
+ function create(resourceType, data, options = {}, callback = false) {
299
+ return state => {
300
+ console.log(`Preparing create operation...`);
301
+ resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
302
+ data = (0, _languageCommon.expandReferences)(data)(state);
254
303
  options = (0, _languageCommon.expandReferences)(options)(state);
255
- if (options) options.operationName = 'getTEIs';else {
256
- options = {
257
- operationName: 'getTEIs'
258
- };
259
- }
260
- return getData('trackedEntityInstances', params, options, callback)(state);
304
+ const {
305
+ params,
306
+ requestConfig
307
+ } = options;
308
+ const {
309
+ configuration
310
+ } = state;
311
+ return (0, _Client.request)(configuration, {
312
+ method: 'post',
313
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType),
314
+ params,
315
+ data: (0, _Utils.nestArray)(data, resourceType),
316
+ ...requestConfig
317
+ }).then(result => {
318
+ _Utils.Log.success(`Created ${resourceType}: ${result.headers.location}`);
319
+
320
+ return (0, _Utils.handleResponse)(result, state, callback);
321
+ });
261
322
  };
262
323
  }
263
324
  /**
264
- * Update TEI if exists otherwise create.
265
- * - Update if the record exists otherwise insert a new record.
266
- * - This is useful for idempotency and duplicate record management.
325
+ * Update data. A generic helper function to update a resource object of any type.
326
+ * Updating an object requires to send `all required fields` or the `full body`
267
327
  * @public
268
328
  * @function
269
- * @param {string} uniqueAttributeId - Tracked Entity Instance unique identifier attribute used during matching.
270
- * @param {Object} data - Payload data for new tracked entity instance or updated data for an existing tracked entity instance.
271
- * @param {{apiVersion: number,strict: boolean,responseType: string}} [options] - `Optional` options for `upsertTEI` operation. Defaults to `{apiVersion: state.configuration.apiVersion,strict: true,responseType: 'json'}`.
272
- * @param {function} [callback] - Optional `callback` to handle the response.
273
- * @throws {RangeError} - Throws `RangeError` when `uniqueAttributeId` is `invalid` or `not unique`.
329
+ * @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
330
+ * @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
331
+ * @param {Object} data - Data to update. It requires to send `all required fields` or the `full body`. If you want `partial updates`, use `patch` operation.
332
+ * @param {Object} [options] - Optional `options` to define URL parameters via params (E.g. `filter`, `dimension` and other import parameters), request config (E.g. `auth`) and the DHIS2 apiVersion.
333
+ * @param {function} [callback] - Optional callback to handle the response
274
334
  * @returns {Operation}
275
- * @example <caption>- Example `expression.js` for upserting a tracked entity instance on attribute with Id `lZGmxYbs97q`.</caption>
276
- * upsertTEI('lZGmxYbs97q', {
335
+ * @example <caption>a program</caption>
336
+ * update('programs', 'qAZJCrNJK8H', {
337
+ * name: '14e1aa02c3f0a31618e096f2c6d03bed',
338
+ * shortName: '14e1aa02',
339
+ * programType: 'WITHOUT_REGISTRATION',
340
+ * });
341
+ * @example <caption>an event</caption>
342
+ * update('events', 'PVqUD2hvU4E', {
343
+ * program: 'eBAyeGv0exc',
344
+ * orgUnit: 'Ngelehun CHC',
345
+ * status: 'COMPLETED',
346
+ * storedBy: 'admin',
347
+ * dataValues: [],
348
+ * });
349
+ * @example <caption>a trackedEntityInstance</caption>
350
+ * update('trackedEntityInstances', 'IeQfgUtGPq2', {
351
+ * created: '2015-08-06T21:12:37.256',
277
352
  * orgUnit: 'TSyzvBiovKh',
353
+ * createdAtClient: '2015-08-06T21:12:37.256',
354
+ * trackedEntityInstance: 'IeQfgUtGPq2',
355
+ * lastUpdated: '2015-08-06T21:12:37.257',
278
356
  * trackedEntityType: 'nEenWmSyUEp',
357
+ * inactive: false,
358
+ * deleted: false,
359
+ * featureType: 'NONE',
360
+ * programOwners: [
361
+ * {
362
+ * ownerOrgUnit: 'TSyzvBiovKh',
363
+ * program: 'IpHINAT79UW',
364
+ * trackedEntityInstance: 'IeQfgUtGPq2',
365
+ * },
366
+ * ],
367
+ * enrollments: [],
368
+ * relationships: [],
279
369
  * attributes: [
280
370
  * {
281
- * attribute: 'lZGmxYbs97q',
282
- * value: '77790012',
371
+ * lastUpdated: '2016-01-12T00:00:00.000',
372
+ * displayName: 'Last name',
373
+ * created: '2016-01-12T00:00:00.000',
374
+ * valueType: 'TEXT',
375
+ * attribute: 'zDhUuAYrxNC',
376
+ * value: 'Russell',
283
377
  * },
284
378
  * {
379
+ * lastUpdated: '2016-01-12T00:00:00.000',
380
+ * code: 'MMD_PER_NAM',
381
+ * displayName: 'First name',
382
+ * created: '2016-01-12T00:00:00.000',
383
+ * valueType: 'TEXT',
285
384
  * attribute: 'w75KJ2mc4zz',
286
- * value: 'Gigiwe',
385
+ * value: 'Catherine',
386
+ * },
387
+ * ],
388
+ * });
389
+ * @example <caption>a dataSet</caption>
390
+ * update('dataSets', 'lyLU2wR22tC', { name: 'OpenFN Data Set', periodType: 'Weekly' });
391
+ * @example <caption>a dataSetNotification</caption>
392
+ * update('dataSetNotificationTemplates', 'VbQBwdm1wVP', {
393
+ * dataSetNotificationTrigger: 'DATA_SET_COMPLETION',
394
+ * notificationRecipient: 'ORGANISATION_UNIT_CONTACT',
395
+ * name: 'Notification',
396
+ * messageTemplate: 'Hello Updated,
397
+ * deliveryChannels: ['SMS'],
398
+ * dataSets: [],
399
+ * });
400
+ * @example <caption>a dataElement</caption>
401
+ * update('dataElements', 'FTRrcoaog83', {
402
+ * aggregationType: 'SUM',
403
+ * domainType: 'AGGREGATE',
404
+ * valueType: 'NUMBER',
405
+ * name: 'Paracetamol',
406
+ * shortName: 'Para',
407
+ * });
408
+ * @example <caption>a dataElementGroup</caption>
409
+ * update('dataElementGroups', 'QrprHT61XFk', {
410
+ * name: 'Data Element Group 1',
411
+ * dataElements: [],
412
+ * });
413
+ * @example <caption>a dataElementGroupSet</caption>
414
+ * update('dataElementGroupSets', 'VxWloRvAze8', {
415
+ * name: 'Data Element Group Set 4',
416
+ * dataDimension: true,
417
+ * shortName: 'DEGS4',
418
+ * dataElementGroups: [],
419
+ * });
420
+ * @example <caption>a dataValueSet</caption>
421
+ * update('dataValueSets', 'AsQj6cDsUq4', {
422
+ * dataElement: 'f7n9E0hX8qk',
423
+ * period: '201401',
424
+ * orgUnit: 'DiszpKrYNg8',
425
+ * value: '12',
426
+ * });
427
+ * @example <caption>a dataValueSet with related dataValues</caption>
428
+ * update('dataValueSets', 'Ix2HsbDMLea', {
429
+ * dataSet: 'pBOMPrpg1QX',
430
+ * completeDate: '2014-02-03',
431
+ * period: '201401',
432
+ * orgUnit: 'DiszpKrYNg8',
433
+ * dataValues: [
434
+ * {
435
+ * dataElement: 'f7n9E0hX8qk',
436
+ * value: '1',
287
437
  * },
288
438
  * {
289
- * attribute: 'zDhUuAYrxNC',
290
- * value: 'Mwanza',
439
+ * dataElement: 'Ix2HsbDMLea',
440
+ * value: '2',
441
+ * },
442
+ * {
443
+ * dataElement: 'eY5ehpbEsB7',
444
+ * value: '3',
291
445
  * },
292
446
  * ],
293
447
  * });
448
+ * @example <caption>a single enrollment</caption>
449
+ * update('enrollments', 'CmsHzercTBa' {
450
+ * trackedEntityInstance: 'bmshzEacgxa',
451
+ * orgUnit: 'TSyzvBiovKh',
452
+ * program: 'gZBxv9Ujxg0',
453
+ * enrollmentDate: '2013-10-17',
454
+ * incidentDate: '2013-10-17',
455
+ * });
294
456
  */
295
457
 
296
458
 
297
- function upsertTEI(uniqueAttributeId, data, options, callback) {
298
- return function (state) {
299
- var _options$apiVersion, _options, _options$strict, _options2, _body$attributes, _body$attributes$find;
300
-
301
- uniqueAttributeId = (0, _languageCommon.expandReferences)(uniqueAttributeId)(state);
302
- var body = (0, _languageCommon.expandReferences)(data)(state);
459
+ function update(resourceType, path, data, options = {}, callback = false) {
460
+ return state => {
461
+ console.log(`Preparing update operation...`);
462
+ resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
463
+ path = (0, _languageCommon.expandReferences)(path)(state);
464
+ data = (0, _languageCommon.expandReferences)(data)(state);
303
465
  options = (0, _languageCommon.expandReferences)(options)(state);
304
- if (options) options.operationName = 'upsertTEI';else {
305
- options = {
306
- operationName: 'upsertTEI'
307
- };
308
- }
309
- var _state$configuration2 = state.configuration,
310
- password = _state$configuration2.password,
311
- username = _state$configuration2.username,
312
- hostUrl = _state$configuration2.hostUrl;
313
- var apiVersion = (_options$apiVersion = (_options = options) === null || _options === void 0 ? void 0 : _options.apiVersion) !== null && _options$apiVersion !== void 0 ? _options$apiVersion : state.configuration.apiVersion;
314
- var strict = (_options$strict = (_options2 = options) === null || _options2 === void 0 ? void 0 : _options2.strict) !== null && _options$strict !== void 0 ? _options$strict : true;
315
- var params = {
316
- ou: body.orgUnit
317
- };
318
- var uniqueAttributeValue = (_body$attributes = body.attributes) === null || _body$attributes === void 0 ? void 0 : (_body$attributes$find = _body$attributes.find(function (obj) {
319
- return (obj === null || obj === void 0 ? void 0 : obj.attribute) === uniqueAttributeId;
320
- })) === null || _body$attributes$find === void 0 ? void 0 : _body$attributes$find.value;
321
- var trackedEntityType = body.trackedEntityType;
322
- var uniqueAttributeUrl = (0, _Utils.buildUrl)("/trackedEntityAttributes/".concat(uniqueAttributeId), hostUrl, apiVersion);
323
- var trackedEntityTypeUrl = (0, _Utils.buildUrl)("/trackedEntityTypes/".concat(trackedEntityType, "?fields=*"), hostUrl, apiVersion);
324
-
325
- var findTrackedEntityType = function findTrackedEntityType() {
326
- return _axios["default"].get(trackedEntityTypeUrl, {
327
- auth: {
328
- username: username,
329
- password: password
330
- }
331
- }).then(function (result) {
332
- var _result$data, _result$data$trackedE;
333
-
334
- 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) {
335
- var _obj$trackedEntityAtt;
336
-
337
- return (obj === null || obj === void 0 ? void 0 : (_obj$trackedEntityAtt = obj.trackedEntityAttribute) === null || _obj$trackedEntityAtt === void 0 ? void 0 : _obj$trackedEntityAtt.id) === uniqueAttributeId;
338
- });
339
- return _objectSpread({}, result.data, {
340
- upsertAttributeAssigned: attribute ? true : false
341
- });
342
- });
343
- };
344
-
345
- var isAttributeUnique = function isAttributeUnique() {
346
- return _axios["default"].get(uniqueAttributeUrl, {
347
- auth: {
348
- username: username,
349
- password: password
350
- }
351
- }).then(function (result) {
352
- var foundAttribute = result.data;
353
- return {
354
- unique: foundAttribute.unique,
355
- name: foundAttribute.name
356
- };
357
- });
358
- };
359
-
360
- return Promise.all([findTrackedEntityType(), strict === true ? isAttributeUnique() : Promise.resolve({
361
- unique: true
362
- })]).then(function (_ref) {
363
- var _ref2 = _slicedToArray(_ref, 2),
364
- entityType = _ref2[0],
365
- attribute = _ref2[1];
366
-
367
- if (!entityType.upsertAttributeAssigned) {
368
- _Utils.Log.error('');
369
-
370
- throw new RangeError("Tracked Entity Attribute ".concat(uniqueAttributeId, " is not assigned to the ").concat(entityType.name, " Entity Type."));
371
- }
372
-
373
- if (!attribute.unique) {
374
- var _attribute$name;
375
-
376
- _Utils.Log.error('');
377
-
378
- throw new RangeError("Attribute ".concat((_attribute$name = attribute.name) !== null && _attribute$name !== void 0 ? _attribute$name : '', "(").concat(uniqueAttributeId, ") is not marked as unique."));
379
- }
380
-
381
- return upsert('trackedEntityInstances', {
382
- attributeId: uniqueAttributeId,
383
- attributeValue: uniqueAttributeValue
384
- }, body, params, options, callback)(state);
466
+ const {
467
+ params,
468
+ requestConfig
469
+ } = options;
470
+ const {
471
+ configuration
472
+ } = state;
473
+ return (0, _Client.request)(configuration, {
474
+ method: 'put',
475
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType, path),
476
+ params,
477
+ data,
478
+ ...requestConfig
479
+ }).then(result => {
480
+ _Utils.Log.success(`Updated ${resourceType} at ${path}`);
481
+
482
+ return (0, _Utils.handleResponse)(result, state, callback);
385
483
  });
386
484
  };
387
485
  }
388
486
  /**
389
- * Create Tracked Entity Instance.
487
+ * Get data. Generic helper method for getting data of any kind from DHIS2.
488
+ * - This can be used to get `DataValueSets`,`events`,`trackedEntityInstances`,`etc.`
390
489
  * @public
391
490
  * @function
392
- * @param {Object} data - The update data containing new values.
393
- * @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`.
394
- * @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `createTEI` operation. Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`.
395
- * @param {function} [callback] - Optional callback to handle the response.
396
- * @returns {Operation}
397
- * @example <caption>- Example `expression.js` of `createTEI`.</caption>
398
- * createTEI({
399
- * orgUnit: 'TSyzvBiovKh',
400
- * trackedEntityType: 'nEenWmSyUEp',
401
- * attributes: [
402
- * {
403
- * attribute: 'lZGmxYbs97q',
404
- * value: valUpsertTEI,
405
- * },
406
- * {
407
- * attribute: 'w75KJ2mc4zz',
408
- * value: 'Gigiwe',
409
- * },
410
- * ],
411
- * enrollments: [
412
- * {
413
- * orgUnit: 'TSyzvBiovKh',
414
- * program: 'fDd25txQckK',
415
- * programState: 'lST1OZ5BDJ2',
416
- * enrollmentDate: '2021-01-04',
417
- * incidentDate: '2021-01-04',
418
- * },
419
- * ],
491
+ * @param {string} resourceType - The type of resource to get(use its `plural` name). E.g. `dataElements`, `trackedEntityInstances`,`organisationUnits`, etc.
492
+ * @param {Object} query - A query object that will limit what resources are retrieved when converted into request params.
493
+ * @param {Object} [options] - Optional `options` to define URL parameters via params beyond filters, request configuration (e.g. `auth`) and DHIS2 api version to use.
494
+ * @param {function} [callback] - Optional callback to handle the response
495
+ * @returns {Operation} state
496
+ * @example <caption>all data values for the 'pBOMPrpg1QX' dataset</caption>
497
+ * get('dataValueSets', {
498
+ * dataSet: 'pBOMPrpg1QX',
499
+ * orgUnit: 'DiszpKrYNg8',
500
+ * period: '201401',
501
+ * fields: '*',
502
+ * });
503
+ * @example <caption>all programs for an organization unit</caption>
504
+ * get('programs', { orgUnit: 'TSyzvBiovKh', fields: '*' });
505
+ * @example <caption>a single tracked entity instance by a unique external ID</caption>
506
+ * get('trackedEntityInstances', {
507
+ * ou: 'DiszpKrYNg8',
508
+ * filter: ['flGbXLXCrEo:Eq:124', 'w75KJ2mc4zz:Eq:John'],
420
509
  * });
421
510
  */
422
511
 
423
512
 
424
- function createTEI(data, params, options, callback) {
425
- return function (state) {
513
+ function get(resourceType, query, options = {}, callback = false) {
514
+ return state => {
515
+ console.log('Preparing get operation...');
516
+ resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
517
+ query = (0, _languageCommon.expandReferences)(query)(state);
426
518
  options = (0, _languageCommon.expandReferences)(options)(state);
427
- if (options) options.operationName = 'createTEI';else {
428
- options = {
429
- operationName: 'createTEI'
430
- };
431
- }
432
- return create('trackedEntityInstances', data, params, options, callback)(state);
519
+ const {
520
+ params,
521
+ requestConfig
522
+ } = options;
523
+ const {
524
+ configuration
525
+ } = state;
526
+ return (0, _Client.request)(configuration, {
527
+ method: 'get',
528
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType),
529
+ params: { ...query,
530
+ ...params
531
+ },
532
+ responseType: 'json',
533
+ ...requestConfig
534
+ }).then(result => {
535
+ _Utils.Log.success(`Retrieved ${resourceType}`);
536
+
537
+ return (0, _Utils.handleResponse)(result, state, callback);
538
+ });
433
539
  };
434
- }
540
+ } // /**
541
+ // * Upsert a record. A generic helper function used to atomically either insert a row, or on the basis of the row already existing, UPDATE that existing row instead.
542
+ // * @public
543
+ // * @function
544
+ // * @param {string} resourceType - The type of a resource to `insert` or `update`. E.g. `trackedEntityInstances`
545
+ // * @param {Object} data - The update data containing new values
546
+ // * @param {{replace:boolean, apiVersion: number,strict: boolean,responseType: string}} [options] - `Optional` options for `upsertTEI` operation. Defaults to `{replace: false, apiVersion: state.configuration.apiVersion,strict: true,responseType: 'json'}`.
547
+ // * @param {function} [callback] - Optional callback to handle the response
548
+ // * @throws {RangeError} - Throws range error
549
+ // * @returns {Operation}
550
+ // * @example <caption>Example `expression.js` of upsert</caption>
551
+ // * upsert(
552
+ // * 'trackedEntityInstances',
553
+ // * {
554
+ // * attributeId: 'lZGmxYbs97q',
555
+ // * attributeValue: state =>
556
+ // * state.data.attributes.find(obj => obj.attribute === 'lZGmxYbs97q')
557
+ // * .value,
558
+ // * },
559
+ // * state.data,
560
+ // * { ou: 'TSyzvBiovKh' }
561
+ // * );
562
+ // */
563
+ // export function upsert(resourceType, data, options = {}, callback = false) {
564
+ // return state => {
565
+ // console.log(`Preparing upsert via 'get' then 'create' OR 'update'...`);
566
+ // return get(
567
+ // resourceType,
568
+ // data
569
+ // )(state).then(resp => {
570
+ // const resources = resp.data[resourceType];
571
+ // if (resources.length > 1) {
572
+ // throw new RangeError(
573
+ // `Cannot upsert on Non-unique attribute. The operation found more than one records for your request.`
574
+ // );
575
+ // } else if (resources.length <= 0) {
576
+ // return create(resourceType, data, options, callback)(state);
577
+ // } else {
578
+ // const pathName =
579
+ // resourceType === 'trackedEntityInstances'
580
+ // ? 'trackedEntityInstance'
581
+ // : 'id';
582
+ // const path = resources[0][pathName];
583
+ // return update(resourceType, path, data, options, callback)(state);
584
+ // }
585
+ // });
586
+ // };
587
+ // }
588
+
435
589
  /**
436
- * Update a Tracked Entity Instance.
590
+ * Discover `DHIS2` `api` `endpoint` `query parameters` and allowed `operators` for a given resource's endpoint.
437
591
  * @public
438
592
  * @function
439
- * @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}`).
440
- * @param {Object} data - The update data containing new values.
441
- * @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`.
442
- * @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `updateTEI` operation. Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`.
443
- * @param {function} [callback] - Optional callback to handle the response.
593
+ * @param {string} httpMethod - The HTTP to inspect parameter usage for a given endpoint, e.g., `get`, `post`,`put`,`patch`,`delete`
594
+ * @param {string} endpoint - The path for a given endpoint. E.g. `/trackedEntityInstances` or `/dataValueSets`
444
595
  * @returns {Operation}
445
- * @example <caption>- Example `expression.js` of `updateTEI`.</caption>
446
- * updateTEI('PVqUD2hvU4E', {
447
- * orgUnit: 'TSyzvBiovKh',
448
- * trackedEntityType: 'nEenWmSyUEp',
449
- * attributes: [
450
- * {
451
- * attribute: 'lZGmxYbs97q',
452
- * value: valUpsertTEI,
453
- * },
454
- * {
455
- * attribute: 'w75KJ2mc4zz',
456
- * value: 'Gigiwe',
457
- * },
458
- * ],
459
- * enrollments: [
460
- * {
461
- * orgUnit: 'TSyzvBiovKh',
462
- * program: 'fDd25txQckK',
463
- * programState: 'lST1OZ5BDJ2',
464
- * enrollmentDate: '2021-01-04',
465
- * incidentDate: '2021-01-04',
466
- * },
467
- * ],
468
- * });
596
+ * @example <caption>a list of parameters allowed on a given endpoint for specific http method</caption>
597
+ * discover('post', '/trackedEntityInstances')
469
598
  */
470
599
 
471
600
 
472
- function updateTEI(path, data, params, options, callback) {
473
- return function (state) {
474
- options = (0, _languageCommon.expandReferences)(options)(state);
475
- if (options) options.operationName = 'updateTEI';else {
476
- options = {
477
- operationName: 'updateTEI'
478
- };
479
- }
480
- return update('trackedEntityInstances', path, data, params, options, callback)(state);
481
- };
482
- }
483
- /**
484
- * Get annonymous events or tracker events.
485
- * @public
486
- * @function
487
- * @param {Object} params - `import` parameters for `getEvents`. See examples here
488
- * @param {{apiVersion: number,responseType: string}} [options] - `Optional` options for `getEvents` operation. Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`.
489
- * @param {function} [callback] - Optional callback to handle the response.
490
- * @returns {Operation}
491
- * @example <caption>- Query for `all events` with `children` of a certain `organisation unit`</caption>
492
- * getEvents({ orgUnit: 'YuQRtpLP10I', ouMode: 'CHILDREN' });
493
- */
601
+ function discover(httpMethod, endpoint) {
602
+ return state => {
603
+ console.log(`Discovering query/import parameters for ${httpMethod} on ${endpoint}`);
604
+ return _axios.default.get('https://dhis2.github.io/dhis2-api-specification/spec/metadata_openapi.json', {
605
+ transformResponse: [data => {
606
+ let tempData = JSON.parse(data);
607
+ let filteredData = tempData.paths[endpoint][httpMethod];
608
+ return { ...filteredData,
609
+ parameters: filteredData.parameters.reduce((acc, currentValue) => {
610
+ let index = currentValue['$ref'].lastIndexOf('/') + 1;
611
+ let paramRef = currentValue['$ref'].slice(index);
612
+ let param = tempData.components.parameters[paramRef];
494
613
 
614
+ if (param.schema['$ref']) {
615
+ let schemaRefIndex = param.schema['$ref'].lastIndexOf('/') + 1;
616
+ let schemaRef = param.schema['$ref'].slice(schemaRefIndex);
617
+ param.schema = tempData.components.schemas[schemaRef];
618
+ }
495
619
 
496
- function getEvents(params, options, callback) {
497
- return function (state) {
498
- options = (0, _languageCommon.expandReferences)(options)(state);
499
- if (options) options.operationName = 'getEvents';else {
500
- options = {
501
- operationName: 'getEvents'
620
+ param.schema = JSON.stringify(param.schema);
621
+ let descIndex;
622
+ if ((0, _lodash.indexOf)(param.description, ',') === -1 && (0, _lodash.indexOf)(param.description, '.') > -1) descIndex = (0, _lodash.indexOf)(param.description, '.');else if ((0, _lodash.indexOf)(param.description, ',') > -1 && (0, _lodash.indexOf)(param.description, '.') > -1) {
623
+ descIndex = (0, _lodash.indexOf)(param.description, '.') < (0, _lodash.indexOf)(param.description, ',') ? (0, _lodash.indexOf)(param.description, '.') : (0, _lodash.indexOf)(param.description, ',');
624
+ } else {
625
+ descIndex = param.description.length;
626
+ }
627
+ param.description = param.description.slice(0, descIndex);
628
+ acc[paramRef] = param;
629
+ return acc;
630
+ }, {})
631
+ };
632
+ }]
633
+ }).then(result => {
634
+ var _result$data$descript;
635
+
636
+ console.log(`\t=======================================================================================\n\tQuery Parameters for ${httpMethod} on ${endpoint} [${(_result$data$descript = result.data.description) !== null && _result$data$descript !== void 0 ? _result$data$descript : '<description_missing>'}]\n\t=======================================================================================`);
637
+ console.table(result.data.parameters, ['in', 'required', 'description']);
638
+ console.table(result.data.parameters, ['schema']);
639
+ console.log(`=========================================Responses===============================\n${(0, _Utils.prettyJson)(result.data.responses)}\n=======================================================================================`);
640
+ return { ...state,
641
+ data: result.data
502
642
  };
503
- }
504
- return getData('events', params, responseType, options, callback)(state);
643
+ });
505
644
  };
506
645
  }
507
646
  /**
508
- * Create DHIS2 Events
509
- * - 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.
510
- * - For events with registration, a `tracked entity instance identifier is required`
511
- * - 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.
647
+ * Patch a record. A generic helper function to send partial updates on one or more object properties.
648
+ * - You are not required to send the full body of object properties.
649
+ * - This is useful for cases where you don't want or need to update all properties on a object.
512
650
  * @public
513
651
  * @function
514
- * @param {Object} data - The payload containing new values
515
- * @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`.
516
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `createEvents` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
652
+ * @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
653
+ * @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
654
+ * @param {Object} data - Data to update. Include only the fields you want to update. E.g. `{name: "New Name"}`
655
+ * @param {Object} [options] - Optional configuration, including params for the update ({preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}). Defaults to `{operationName: 'patch', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
517
656
  * @param {function} [callback] - Optional callback to handle the response
518
- * @returns {Operation} state
519
- * @example <caption>- Example `expression.js` of `createEvents` for a `single event` can look like this:</caption>
520
- * createEvents({
521
- * program: 'eBAyeGv0exc',
522
- * orgUnit: 'DiszpKrYNg8',
523
- * eventDate: date,
524
- * status: 'COMPLETED',
525
- * completedDate: date,
526
- * storedBy: 'admin',
527
- * coordinate: {
528
- * latitude: 59.8,
529
- * longitude: 10.9,
530
- * },
531
- * dataValues: [
532
- * {
533
- * dataElement: 'qrur9Dvnyt5',
534
- * value: '33',
535
- * },
536
- * {
537
- * dataElement: 'oZg33kd9taw',
538
- * value: 'Male',
539
- * },
540
- * {
541
- * dataElement: 'msodh3rEMJa',
542
- * value: date,
543
- * },
544
- * ],
545
- * });
657
+ * @returns {Operation}
658
+ * @example <caption>a dataElement</caption>
659
+ * patch('dataElements', 'FTRrcoaog83', { name: 'New Name' });
546
660
  */
661
+ // TODO: @Elias, can this be deleted in favor of update? How does DHIS2 handle PATCH vs PUT?
662
+ // I need to investigate on this. But I think DHIS 2 forces to send all properties back when we do an update. If that's confirmed then this may be needed.
547
663
 
548
664
 
549
- function createEvents(data, params, options, callback) {
550
- return function (state) {
665
+ function patch(resourceType, path, data, options = {}, callback = false) {
666
+ return state => {
667
+ console.log('Preparing patch operation...');
668
+ resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
669
+ path = (0, _languageCommon.expandReferences)(path)(state);
670
+ data = (0, _languageCommon.expandReferences)(data)(state);
551
671
  options = (0, _languageCommon.expandReferences)(options)(state);
552
- if (options) options.operationName = 'createEvents';else {
553
- options = {
554
- operationName: 'createEvents'
555
- };
556
- }
557
- return create('events', data, params, options, callback)(state);
672
+ const {
673
+ params,
674
+ requestConfig
675
+ } = options;
676
+ const {
677
+ configuration
678
+ } = state;
679
+ return (0, _Client.request)(configuration, {
680
+ method: 'patch',
681
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType, path),
682
+ params,
683
+ data,
684
+ ...requestConfig
685
+ }).then(result => {
686
+ _Utils.Log.success(`Patched ${resourceType} at ${path}`);
687
+
688
+ return (0, _Utils.handleResponse)(result, state, callback);
689
+ });
558
690
  };
559
691
  }
560
692
  /**
561
- * Update DHIS2 Event.
562
- * - To update an existing event, the format of the payload is the same as that of `creating an event` via `createEvents` operations
563
- * - But you should supply the `identifier` of the object you are updating
564
- * - The payload has to contain `all`, even `non-modified`, `attributes`.
565
- * - Attributes that were present before and are not present in the current payload any more will be removed by DHIS2.
566
- * - If you do not want this behavior, please use `upsert` operation to upsert your events.
693
+ * Delete a record. A generic helper function to delete an object
567
694
  * @public
568
695
  * @function
569
- * @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}`)
570
- * @param {Object} data - The update data containing new values
571
- * @param {Object} [params] - Optional `import` parameters for `updateEvents`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
572
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `updateEvents` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
696
+ * @param {string} resourceType - The type of resource to be deleted. E.g. `trackedEntityInstances`, `organisationUnits`, etc.
697
+ * @param {string} path - Can be an `id` of an `object` or `path` to the `nested object` to `delete`.
698
+ * @param {Object} [data] - Optional. This is useful when you want to remove multiple objects from a collection in one request. You can send `data` as, for example, `{"identifiableObjects": [{"id": "IDA"}, {"id": "IDB"}, {"id": "IDC"}]}`. See more {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#deleting-objects on DHIS2 API docs}
699
+ * @param {{apiVersion: number,operationName: string,resourceType: string}} [options] - Optional `options` for `del` operation including params e.g. `{preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#create-update-parameters DHIS2 documentation}. Defaults to `{operationName: 'delete', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
573
700
  * @param {function} [callback] - Optional callback to handle the response
574
701
  * @returns {Operation}
575
- * @example <caption>- Example `expression.js` of `updateEvents`</caption>
576
- * updateEvents('PVqUD2hvU4E', { events: [
577
- * {
578
- * program: 'eBAyeGv0exc',
579
- * orgUnit: 'DiszpKrYNg8',
580
- * eventDate: date,
581
- * status: 'COMPLETED',
582
- * storedBy: 'admin',
583
- * coordinate: {
584
- * latitude: '59.8',
585
- * longitude: '10.9',
586
- * },
587
- * dataValues: [
588
- * {
589
- * dataElement: 'qrur9Dvnyt5',
590
- * value: '22',
591
- * },
592
- * {
593
- * dataElement: 'oZg33kd9taw',
594
- * value: 'Male',
595
- * },
596
- * ],
597
- * }]
598
- * });
702
+ * @example <caption>a tracked entity instance</caption>
703
+ * destroy('trackedEntityInstances', 'LcRd6Nyaq7T');
599
704
  */
600
705
 
601
706
 
602
- function updateEvents(path, data, params, options, callback) {
603
- return function (state) {
707
+ function destroy(resourceType, path, data = null, options = {}, callback = false) {
708
+ return state => {
709
+ console.log('Preparing destroy operation...');
710
+ resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
711
+ path = (0, _languageCommon.expandReferences)(path)(state);
712
+ data = (0, _languageCommon.expandReferences)(data)(state);
604
713
  options = (0, _languageCommon.expandReferences)(options)(state);
605
- if (options) options.operationName = 'updateEvents';else {
606
- options = {
607
- operationName: 'updateEvents'
608
- };
609
- }
610
- return update('events', path, data, params, options, callback)(state);
714
+ const {
715
+ params,
716
+ requestConfig
717
+ } = options;
718
+ const {
719
+ configuration
720
+ } = state;
721
+ return (0, _Client.request)({
722
+ method: 'delete',
723
+ url: (0, _Utils.generateUrl)(configuration, options, resourceType, path),
724
+ params,
725
+ data,
726
+ ...requestConfig
727
+ }).then(result => {
728
+ _Utils.Log.success(`Deleted ${resourceType} at ${path}`);
729
+
730
+ return (0, _Utils.handleResponse)(result, state, callback);
731
+ });
611
732
  };
612
733
  }
613
734
  /**
614
- * Get DHIS2 Tracker Programs.
735
+ * Gets an attribute value by its case-insensitive display name
615
736
  * @public
737
+ * @example
738
+ * findAttributeValue(state.data.trackedEntityInstances[0], 'first name')
616
739
  * @function
617
- * @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 }
618
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getPrograms` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
619
- * @param {function} [callback] - Optional callback to handle the response
620
- * @returns {Operation}
621
- * @example <caption>- Query for `all programs` with a certain `organisation unit`</caption>
622
- * getPrograms({ orgUnit: 'DiszpKrYNg8' , fields: '*' });
740
+ * @param {Object} trackedEntityInstance - A tracked entity instance (TEI) object
741
+ * @param {string} attributeDisplayName - The 'displayName' to search for in the TEI's attributes
742
+ * @returns {string}
623
743
  */
624
744
 
625
745
 
626
- function getPrograms(params, options, callback) {
627
- return function (state) {
628
- options = (0, _languageCommon.expandReferences)(options)(state);
629
- if (options) options.operationName = 'getPrograms';else {
630
- options = {
631
- operationName: 'getPrograms'
632
- };
633
- }
634
- return getData('programs', params, options, callback)(state);
635
- };
746
+ function findAttributeValue(trackedEntityInstance, attributeDisplayName) {
747
+ var _trackedEntityInstanc, _trackedEntityInstanc2;
748
+
749
+ return trackedEntityInstance === null || trackedEntityInstance === void 0 ? void 0 : (_trackedEntityInstanc = trackedEntityInstance.attributes) === null || _trackedEntityInstanc === void 0 ? void 0 : (_trackedEntityInstanc2 = _trackedEntityInstanc.find(a => (a === null || a === void 0 ? void 0 : a.displayName.toLowerCase()) == attributeDisplayName.toLowerCase())) === null || _trackedEntityInstanc2 === void 0 ? void 0 : _trackedEntityInstanc2.value;
636
750
  }
637
751
  /**
638
- * Create a DHIS2 Tracker Program
752
+ * Converts an attribute ID and value into a DSHI2 attribute object
639
753
  * @public
754
+ * @example
755
+ * attr('w75KJ2mc4zz', 'Elias')
640
756
  * @function
641
- * @param {Object} data - The update data containing new values
642
- * @param {Object} [params] - Optional `import` parameters for `createPrograms`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
643
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getPrograms` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
644
- * @param {function} [callback] - Optional callback to handle the response
645
- * @returns {Operation}
646
- * @example <caption>- Example `expression.js` of `createPrograms` for a `single program` can look like this:</caption>
647
- * createPrograms(state.data);
757
+ * @param {string} attribute - A tracked entity instance (TEI) attribute ID.
758
+ * @param {string} value - The value for that attribute.
759
+ * @returns {object}
648
760
  */
649
761
 
650
762
 
651
- function createPrograms(data, params, options, callback) {
652
- return function (state) {
653
- options = (0, _languageCommon.expandReferences)(options)(state);
654
- if (options) options.operationName = 'createPrograms';else {
655
- options = {
656
- operationName: 'createPrograms'
657
- };
658
- }
659
- return create('programs', data, options, params, callback)(state);
763
+ function attr(attribute, value) {
764
+ return {
765
+ attribute,
766
+ value
660
767
  };
661
768
  }
662
769
  /**
663
- * Update DHIS2 Tracker Programs
664
- * - To update an existing program, the format of the payload is the same as that of `creating an event` via `createEvents` operations
665
- * - But you should supply the `identifier` of the object you are updating
666
- * - The payload has to contain `all`, even `non-modified`, `attributes`.
667
- * - Attributes that were present before and are not present in the current payload any more will be removed by DHIS2.
668
- * - If you do not want this behavior, please use `upsert` operation to upsert your events.
770
+ * Converts a dataElement and value into a DSHI2 dataValue object
669
771
  * @public
772
+ * @example
773
+ * dv('f7n9E0hX8qk', 12)
670
774
  * @function
671
- * @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}`)
672
- * @param {Object} data - The update data containing new values
673
- * @param {Object} [params] - Optional `import` parameters for `updatePrograms`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
674
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getPrograms` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
675
- * @param {function} [callback] - Optional callback to handle the response
676
- * @returns {Operation}
677
- * @example <caption>- Example `expression.js` of `updatePrograms`</caption>
678
- * updatePrograms('PVqUD2hvU4E', state.data);
775
+ * @param {string} dataElement - A data element ID.
776
+ * @param {string} value - The value for that data element.
777
+ * @returns {object}
679
778
  */
680
779
 
681
780
 
682
- function updatePrograms(path, data, params, options, callback) {
683
- return function (state) {
684
- options = (0, _languageCommon.expandReferences)(options)(state);
685
- if (options) options.operationName = 'updatePrograms';else {
686
- options = {
687
- operationName: 'updatePrograms'
688
- };
689
- }
690
- return update('programs', path, data, params, options, callback)(state);
691
- };
692
- }
693
- /**
694
- * Get DHIS2 Enrollments
695
- * @public
696
- * @function
697
- * @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}
698
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getEnrollments` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
699
- * @param {function} [callback] - Optional callback to handle the response
700
- * @returns {Operation}
701
- * @example <caption>- To constrain the response to `enrollments` which are part of a `specific program` you can include a `program query parameter`</caption>
702
- * getEnrollments({
703
- * ou: 'O6uvpzGd5pu',
704
- * ouMode: 'DESCENDANTS',
705
- * program: 'ur1Edk5Oe2n',
706
- * fields: '*',
707
- * });
708
- */
709
-
710
-
711
- function getEnrollments(params, options, callback) {
712
- return function (state) {
713
- options = (0, _languageCommon.expandReferences)(options)(state);
714
- if (options) options.operationName = 'getEnrollments';else {
715
- options = {
716
- operationName: 'getEnrollments'
717
- };
718
- }
719
- return getData('enrollments', params, options, callback)(state);
720
- };
721
- }
722
- /**
723
- * Enroll a TEI into a program
724
- * - Enrolling a tracked entity instance into a program
725
- * - 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.
726
- * - Then, you will need to get the `program identifier` from the `programs` resource via the `getPrograms` operation.
727
- * @public
728
- * @function
729
- * @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 }
730
- * @param {Object} [params] - Optional `import` parameters for `createEnrollment`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
731
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `enrollTEI` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
732
- * @param {function} [callback] - Optional callback to handle the response
733
- * @returns {Operation}
734
- * @example <caption>- Example `expression.js` of `createEnrollment` of a `person` into a `program` can look like this:</caption>
735
- * enrollTEI({
736
- * trackedEntity: 'tracked-entity-id',
737
- * orgUnit: 'org-unit-id',
738
- * attributes: [
739
- * {
740
- * attribute: 'attribute-id',
741
- * value: 'attribute-value',
742
- * },
743
- * ],
744
- * enrollments: [
745
- * {
746
- * orgUnit: 'org-unit-id',
747
- * program: 'program-id',
748
- * enrollmentDate: '2013-09-17',
749
- * incidentDate: '2013-09-17',
750
- * },
751
- * ],
752
- *});
753
- */
754
-
755
-
756
- function enrollTEI(data, params, options, callback) {
757
- return function (state) {
758
- options = (0, _languageCommon.expandReferences)(options)(state);
759
- if (options) options.operationName = 'enrollTEI';else {
760
- options = {
761
- operationName: 'enrollTEI'
762
- };
763
- }
764
- return create('enrollments', data, options, params, callback)(state);
765
- };
766
- }
767
- /**
768
- * Update a DHIS2 Enrollemts
769
- * - To update an existing enrollment, the format of the payload is the same as that of `creating an event` via `createEvents` operations
770
- * - But you should supply the `identifier` of the object you are updating
771
- * - The payload has to contain `all`, even `non-modified`, `attributes`.
772
- * - Attributes that were present before and are not present in the current payload any more will be removed by DHIS2.
773
- * - If you do not want this behavior, please use `upsert` operation to upsert your events.
774
- * @public
775
- * @function
776
- * @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}`)
777
- * @param {Object} data - The update data containing new values
778
- * @param {Object} [params] - Optional `import` parameters for `updateEnrollments`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
779
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `updateEnrollments` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
780
- * @param {function} [callback] - Optional callback to handle the response
781
- * @returns {Operation}
782
- * @example <caption>- Example `expression.js` of `updateEnromments`</caption>
783
- * updateEnrollments('PVqUD2hvU4E', state.data);
784
- */
785
-
786
-
787
- function updateEnrollments(path, data, params, options, callback) {
788
- return function (state) {
789
- options = (0, _languageCommon.expandReferences)(options)(state);
790
- if (options) options.operationName = 'updateEnrollments';else {
791
- options = {
792
- operationName: 'updateEnrollments'
793
- };
794
- }
795
- return update('enrollments', path, data, params, options, callback)(state);
796
- };
797
- }
798
- /**
799
- * Cancel a DHIS2 Enrollment
800
- * - To cancel an existing enrollment, you should supply the `enrollment identifier`(`enrollemt-id`)
801
- * @public
802
- * @function
803
- * @param {string} enrollmentId - The `enrollment-id` of the enrollment you wish to cancel
804
- * @param {Object} [params] - Optional `import` parameters for `cancelEnrollment`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
805
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `cancelEnrollment` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
806
- * @param {function} [callback] - Optional callback to handle the response
807
- * @returns {Operation}
808
- * @example <caption>- Example `expression.js` of `cancelEnrollment`</caption>
809
- * cancelEnrollments('PVqUD2hvU4E');
810
- */
811
-
812
-
813
- function cancelEnrollment(enrollmentId, params, options, callback) {
814
- return function (state) {
815
- enrollmentId = (0, _languageCommon.expandReferences)(enrollmentId)(state);
816
- options = (0, _languageCommon.expandReferences)(options)(state);
817
- if (options) options.operationName = 'cancelEnrollment';else {
818
- options = {
819
- operationName: 'cancelEnrollment'
820
- };
821
- }
822
- var path = "".concat(enrollmentId, "/cancelled");
823
- return update('enrollments', path, null, params, options, callback)(state);
824
- };
825
- }
826
- /**
827
- * Complete a DHIS2 Enrollment
828
- * - To complete an existing enrollment, you should supply the `enrollment identifier`(`enrollemt-id`)
829
- * @public
830
- * @function
831
- * @param {string} enrollmentId - The `enrollment-id` of the enrollment you wish to cancel
832
- * @param {Object} [params] - Optional `import` parameters for `completeEnrollment`. E.g. `{dryRun: true, IdScheme: 'CODE'}. Defaults to DHIS2 `default params`
833
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `completeEnrollment` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
834
- * @param {function} [callback] - Optional callback to handle the response
835
- * @returns {Operation}
836
- * @example <caption>- Example `expression.js` of `completeEnrollment`</caption>
837
- * completeEnrollment('PVqUD2hvU4E');
838
- */
839
-
840
-
841
- function completeEnrollment(enrollmentId, params, options, callback) {
842
- return function (state) {
843
- enrollmentId = (0, _languageCommon.expandReferences)(enrollmentId)(state);
844
- options = (0, _languageCommon.expandReferences)(options)(state);
845
- if (options) options.operationName = 'completeEnrollment';else {
846
- options = {
847
- operationName: 'completeEnrollment'
848
- };
849
- }
850
- var path = "".concat(enrollmentId, "/completed");
851
- return update('enrollments', path, null, params, options, callback)(state);
852
- };
853
- }
854
- /**
855
- * Get DHIS2 Relationships(links) between two entities in tracker. These entities can be tracked entity instances, enrollments and events.
856
- * - All the tracker operations, `getTEIs`, `getEnrollments` and `getEvents` also list their relationships if requested in the `field` filter.
857
- * - 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.
858
- * @public
859
- * @function
860
- * @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}
861
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `getRelationships` operation.Defaults to `{apiVersion: state.configuration.apiVersion,responseType: 'json'}`
862
- * @param {function} [callback] - Optional callback to handle the response
863
- * @returns {Operation}
864
- * @example <caption>- A query for `all relationships` associated with a `specific tracked entity instance` can look like this:</caption>
865
- * getRelationships({ tei: 'F8yKM85NbxW', fields: '*' });
866
- */
867
-
868
-
869
- function getRelationships(params, options, callback) {
870
- return function (state) {
871
- options = (0, _languageCommon.expandReferences)(options)(state);
872
- if (options) options.operationName = 'getRelationships';else {
873
- options = {
874
- operationName: 'getRelationships'
875
- };
876
- }
877
- return getData('relationships', params, options, callback)(state);
878
- };
879
- }
880
- /**
881
- * Get DHIS2 Data Values.
882
- * - This operation retrives data values from DHIS2 Web API by interacting with the `dataValueSets` resource
883
- * - Data values can be retrieved in XML, JSON and CSV format.
884
- * @public
885
- * @function
886
- * @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`.
887
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `options` for `getDataValues` operation. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`
888
- * @param {function} [callback] - Optional `callback` to handle the response
889
- * @returns {Operation}
890
- * @example <caption>- Example getting **two** `data values` associated with a specific `orgUnit`, `dataSet`, and `period `</caption>
891
- * getDataValues({
892
- * orgUnit: 'DiszpKrYNg8',
893
- * period: '202010',
894
- * dataSet: 'pBOMPrpg1QX',
895
- * limit: 2,
896
- * });
897
- */
898
-
899
-
900
- function getDataValues(params, options, callback) {
901
- return function (state) {
902
- options = (0, _languageCommon.expandReferences)(options)(state);
903
- if (options) options.operationName = 'getDataValues';else {
904
- options = {
905
- operationName: 'getDataValues'
906
- };
907
- }
908
- return getData('dataValueSets', params, options, callback)(state);
909
- };
910
- }
911
- /**
912
- * Create DHIS2 Data Values
913
- * - This is used to send aggregated data to DHIS2
914
- * - A data value set represents a set of data values which have a relationship, usually from being captured off the same data entry form.
915
- * - 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.
916
- * - You can also use this operation to send large bulks of data values which don't necessarily are logically related.
917
- * - 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
918
- * @public
919
- * @function
920
- * @param {object} data - The `data values` to upload or create. See example shape.
921
- * @param {{apiVersion: number,responseType: string}} [options] - Optional `flags` for the behavior of the `createDataVaues` operation.
922
- * @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.
923
- * @param {function} [callback] - Optional callback to handle the response
924
- * @returns {Operation}
925
- * @example <caption>- Example `expression.js` of `createDataValues` for sending a set of related data values sharing the same period and organisation unit</caption>
926
- * createDataValues({
927
- * dataSet: 'pBOMPrpg1QX',
928
- * completeDate: '2014-02-03',
929
- * period: '201401',
930
- * orgUnit: 'DiszpKrYNg8',
931
- * dataValues: [
932
- * {
933
- * dataElement: 'f7n9E0hX8qk',
934
- * value: '1',
935
- * },
936
- * {
937
- * dataElement: 'Ix2HsbDMLea',
938
- * value: '2',
939
- * },
940
- * {
941
- * dataElement: 'eY5ehpbEsB7',
942
- * value: '3',
943
- * },
944
- * ],
945
- * });
946
- */
947
-
948
-
949
- function createDataValues(data, options, params, callback) {
950
- return function (state) {
951
- options = (0, _languageCommon.expandReferences)(options)(state);
952
- if (options) options.operationName = 'createDataValues';else {
953
- options = {
954
- operationName: 'createDataValues'
955
- };
956
- }
957
- return create('dataValueSets', data, options, params, callback)(state);
958
- };
959
- }
960
- /**
961
- * Generate valid, random DHIS2 identifiers
962
- * - Useful for client generated Ids compatible with DHIS2
963
- * @public
964
- * @function
965
- * @param {{apiVersion: number,limit: number,responseType: string}} [options] - Optional `options` for `generateDhis2UID` operation. Defaults to `{apiVersion: state.configuration.apiVersion,limit: 1,responseType: 'json'}`
966
- * @param {function} [callback] - Callback to handle response
967
- * @returns {Operation}
968
- * @example <caption>Example generating `three UIDs` from the DHIS2 server</caption>
969
- * generateDhis2UID({limit: 3});
970
- */
971
-
972
-
973
- function generateDhis2UID(options, callback) {
974
- return function (state) {
975
- var _options$limit, _options3, _options4;
976
-
977
- options = (0, _languageCommon.expandReferences)(options)(state);
978
- if (options) options.operationName = 'generateDhis2UID';else {
979
- options = {
980
- operationName: 'generateDhis2UID'
981
- };
982
- }
983
- var limit = {
984
- limit: (_options$limit = (_options3 = options) === null || _options3 === void 0 ? void 0 : _options3.limit) !== null && _options$limit !== void 0 ? _options$limit : 1
985
- };
986
- (_options4 = options) === null || _options4 === void 0 ? true : delete _options4.limit;
987
- return getData('system/id', limit, options, callback)(state);
988
- };
989
- }
990
- /**
991
- * Discover `DHIS2` `api` `endpoint` `query parameters` and allowed `operators` for a given resource's endpoint.
992
- * @public
993
- * @function
994
- * @param {string} httpMethod - The HTTP to inspect parameter usage for a given endpoint, e.g., `get`, `post`,`put`,`patch`,`delete`
995
- * @param {string} endpoint - The path for a given endpoint. E.g. `/trackedEntityInstances` or `/dataValueSets`
996
- * @returns {Operation}
997
- * @example <caption>Example getting a list of `parameters allowed` on a given `endpoint` for specific `http method`</caption>
998
- * discover('post', '/trackedEntityInstances')
999
- */
1000
-
1001
-
1002
- function discover(httpMethod, endpoint) {
1003
- return function (state) {
1004
- _Utils.Log.info("Discovering query/import parameters for ".concat(httpMethod, " on ").concat(endpoint));
1005
-
1006
- return _axios["default"].get('https://dhis2.github.io/dhis2-api-specification/spec/metadata_openapi.json', {
1007
- transformResponse: [function (data) {
1008
- var tempData = JSON.parse(data);
1009
- var filteredData = tempData.paths[endpoint][httpMethod];
1010
- return _objectSpread({}, filteredData, {
1011
- parameters: filteredData.parameters.reduce(function (acc, currentValue) {
1012
- var index = currentValue['$ref'].lastIndexOf('/') + 1;
1013
- var paramRef = currentValue['$ref'].slice(index);
1014
- var param = tempData.components.parameters[paramRef];
1015
-
1016
- if (param.schema['$ref']) {
1017
- var schemaRefIndex = param.schema['$ref'].lastIndexOf('/') + 1;
1018
- var schemaRef = param.schema['$ref'].slice(schemaRefIndex);
1019
- param.schema = tempData.components.schemas[schemaRef];
1020
- }
1021
-
1022
- param.schema = JSON.stringify(param.schema);
1023
- var descIndex;
1024
- if ((0, _lodash.indexOf)(param.description, ',') === -1 && (0, _lodash.indexOf)(param.description, '.') > -1) descIndex = (0, _lodash.indexOf)(param.description, '.');else if ((0, _lodash.indexOf)(param.description, ',') > -1 && (0, _lodash.indexOf)(param.description, '.') > -1) {
1025
- descIndex = (0, _lodash.indexOf)(param.description, '.') < (0, _lodash.indexOf)(param.description, ',') ? (0, _lodash.indexOf)(param.description, '.') : (0, _lodash.indexOf)(param.description, ',');
1026
- } else {
1027
- descIndex = param.description.length;
1028
- }
1029
- param.description = param.description.slice(0, descIndex);
1030
- acc[paramRef] = param;
1031
- return acc;
1032
- }, {})
1033
- });
1034
- }]
1035
- }).then(function (result) {
1036
- var _result$data$descript;
1037
-
1038
- _Utils.Log.info("\t=======================================================================================\n\tQuery Parameters for ".concat(httpMethod, " on ").concat(endpoint, " [").concat((_result$data$descript = result.data.description) !== null && _result$data$descript !== void 0 ? _result$data$descript : '<description_missing>', "]\n\t======================================================================================="));
1039
-
1040
- console.table(result.data.parameters, ['in', 'required', 'description']);
1041
- console.table(result.data.parameters, ['schema']);
1042
- console.log("=========================================Responses===============================\n".concat((0, _Utils.prettyJson)(result.data.responses), "\n======================================================================================="));
1043
- return _objectSpread({}, state, {
1044
- data: result.data
1045
- });
1046
- });
1047
- };
1048
- }
1049
- /**
1050
- * Get analytical, aggregated data
1051
- * - The analytics resource is powerful as it lets you query and retrieve data aggregated along all available data dimensions.
1052
- * - For instance, you can ask the analytics resource to provide the aggregated data values for a set of data elements, periods and organisation units.
1053
- * - Also, you can retrieve the aggregated data for a combination of any number of dimensions based on data elements and organisation unit group sets.
1054
- * @public
1055
- * @function
1056
- * @param {Object} params - Analytics `query parameters`, e.g. `{dx: 'fbfJHSPpUQD;cYeuwXTCPkU',filters: ['pe:2014Q1;2014Q2','ou:O6uvpzGd5pu;lc3eMKXaEfw']}`. Run `discover` or visit {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#analytics DHIS2 API docs} to get the params available.
1057
- * @param {{apiVersion: number,responseType: string}}[options] - `Optional` options for `getAnalytics` operation. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`.
1058
- * @param {function} [callback] - Callback to handle response
1059
- * @returns {Operation}
1060
- * @example <caption>Example getting only records where the data value is greater or equal to 6500 and less than 33000</caption>
1061
- * getAnalytics({
1062
- * dimensions: [
1063
- * 'dx:fbfJHSPpUQD;cYeuwXTCPkU',
1064
- * 'pe:2014',
1065
- * 'ou:O6uvpzGd5pu;lc3eMKXaEfw',
1066
- * ],
1067
- * measureCriteria: 'GE:6500;LT:33000',
1068
- * });
1069
- */
1070
-
1071
-
1072
- function getAnalytics(params, options, callback) {
1073
- return function (state) {
1074
- options = (0, _languageCommon.expandReferences)(options)(state);
1075
- if (options) options.operationName = 'getAnalytics';else {
1076
- options = {
1077
- operationName: 'getAnalytics'
1078
- };
1079
- }
1080
- return getData("analytics", params, options, callback)(state);
1081
- };
1082
- }
1083
- /**
1084
- * Get DHIS2 api resources
1085
- * @public
1086
- * @function
1087
- * @param {Object} [params] - The `optional` query parameters for this endpoint. E.g `{filter: 'singular:like:attribute'}`.
1088
- * @param {{filter: string, fields: string, responseType: string}} [options] - The `optional` options, specifiying the filter expression. E.g. `singular:eq:attribute`.
1089
- * @param {function} [callback] - The `optional callback function that will be called to handle data returned by this function.
1090
- * @returns {Operation}
1091
- * @example <caption>Example getting a resource named `attribute`, in `xml` format, returning all the fields</caption>
1092
- * getResources('dataElement', {
1093
- * filter: 'singular:eq:attribute',
1094
- * fields: '*',
1095
- * responseType: 'xml',
1096
- * });
1097
- */
1098
-
1099
-
1100
- function getResources(params, options, callback) {
1101
- return function (state) {
1102
- var _options$responseType, _options5, _params, _CONTENT_TYPES$respon;
1103
-
1104
- params = (0, _languageCommon.expandReferences)(params)(state);
1105
- options = (0, _languageCommon.expandReferences)(options)(state);
1106
- var operationName = 'getResources';
1107
- var _state$configuration3 = state.configuration,
1108
- username = _state$configuration3.username,
1109
- password = _state$configuration3.password,
1110
- hostUrl = _state$configuration3.hostUrl;
1111
- var responseType = (_options$responseType = (_options5 = options) === null || _options5 === void 0 ? void 0 : _options5.responseType) !== null && _options$responseType !== void 0 ? _options$responseType : 'json';
1112
- var filter = (_params = params) === null || _params === void 0 ? void 0 : _params.filter;
1113
- var queryParams = params;
1114
- var headers = {
1115
- Accept: (_CONTENT_TYPES$respon = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon !== void 0 ? _CONTENT_TYPES$respon : 'application/json'
1116
- };
1117
- var path = '/resources';
1118
- var url = (0, _Utils.buildUrl)(path, hostUrl, null, false);
1119
-
1120
- var transformResponse = function transformResponse(data, headers) {
1121
- if (filter) {
1122
- var _headers$contentType, _headers$contentType2;
1123
-
1124
- if (((_headers$contentType = (_headers$contentType2 = headers['content-type']) === null || _headers$contentType2 === void 0 ? void 0 : _headers$contentType2.split(';')[0]) !== null && _headers$contentType !== void 0 ? _headers$contentType : null) === _Utils.CONTENT_TYPES.json) {
1125
- var tempData = JSON.parse(data);
1126
- return _objectSpread({}, tempData, {
1127
- resources: _Utils.applyFilter.apply(void 0, [tempData.resources].concat(_toConsumableArray((0, _Utils.parseFilter)(filter))))
1128
- });
1129
- } else {
1130
- _Utils.Log.warn('Filters on this resource are only supported for json content types. Skipping filtering ...');
1131
- }
1132
- }
1133
-
1134
- return data;
1135
- };
1136
-
1137
- (0, _Utils.logOperation)(operationName);
1138
- (0, _Utils.logWaitingForServer)(url, queryParams);
1139
- (0, _Utils.warnExpectLargeResult)(queryParams, url);
1140
- return _axios["default"].request({
1141
- url: url,
1142
- method: 'GET',
1143
- auth: {
1144
- username: username,
1145
- password: password
1146
- },
1147
- responseType: responseType,
1148
- headers: headers,
1149
- params: queryParams,
1150
- transformResponse: transformResponse
1151
- }).then(function (result) {
1152
- _Utils.Log.info("".concat(operationName, " succeeded. The result of this operation will be in ").concat(operationName, " state.data or in your ").concat(operationName, " callback."));
1153
-
1154
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1155
- return (0, _languageCommon.composeNextState)(state, result.data);
1156
- });
1157
- };
1158
- }
1159
- /**
1160
- * Get schema of a given resource type, in any data format supported by DHIS2
1161
- * @public
1162
- * @function
1163
- * @param {string} resourceType - The type of resource to be updated(`singular` version of the `resource name`). E.g. `dataElement`, `organisationUnit`, etc. Run `getResources` to see available resources and their corresponding `singular` names.
1164
- * @param {Object} params - Optional `query parameters` for the `getSchema` operation. e.g. `{ fields: 'properties' ,skipPaging: true}`. Run`discover` or See {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#metadata-export-examples DHIS2 API Docs}
1165
- * @param {{apiVersion: number,resourceType: string}} [options] - Optional options for `getSchema` method. Defaults to `{apiVersion: state.configuration.apiVersion, responseType: 'json'}`
1166
- * @param {function} [callback] - Optional `callback` to handle the response
1167
- * @returns {Operation}
1168
- * @example <caption>Example getting the `schema` for `dataElement` in XML</caption>
1169
- * getSchema('dataElement', '{ fields: '*' }, { responseType: 'xml' });
1170
- */
1171
-
1172
-
1173
- function getSchema(resourceType, params, options, callback) {
1174
- return function (state) {
1175
- var _options$responseType2, _options6, _params2, _params3, _options$apiVersion2, _options7, _CONTENT_TYPES$respon2, _resourceType;
1176
-
1177
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1178
- params = (0, _languageCommon.expandReferences)(params)(state);
1179
- options = (0, _languageCommon.expandReferences)(options)(state);
1180
- var operationName = 'getSchema';
1181
- var _state$configuration4 = state.configuration,
1182
- username = _state$configuration4.username,
1183
- password = _state$configuration4.password,
1184
- hostUrl = _state$configuration4.hostUrl;
1185
- var responseType = (_options$responseType2 = (_options6 = options) === null || _options6 === void 0 ? void 0 : _options6.responseType) !== null && _options$responseType2 !== void 0 ? _options$responseType2 : 'json';
1186
- var filters = (_params2 = params) === null || _params2 === void 0 ? void 0 : _params2.filters;
1187
- (_params3 = params) === null || _params3 === void 0 ? true : delete _params3.filters;
1188
- var queryParams = new URLSearchParams(params);
1189
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1190
- return queryParams.append('filter', f);
1191
- });
1192
- var apiVersion = (_options$apiVersion2 = (_options7 = options) === null || _options7 === void 0 ? void 0 : _options7.apiVersion) !== null && _options$apiVersion2 !== void 0 ? _options$apiVersion2 : state.configuration.apiVersion;
1193
- var headers = {
1194
- Accept: (_CONTENT_TYPES$respon2 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon2 !== void 0 ? _CONTENT_TYPES$respon2 : 'application/json'
1195
- };
1196
- var url = (0, _Utils.buildUrl)("/schemas/".concat((_resourceType = resourceType) !== null && _resourceType !== void 0 ? _resourceType : ''), hostUrl, apiVersion);
1197
- (0, _Utils.logOperation)(operationName);
1198
- (0, _Utils.logApiVersion)(apiVersion);
1199
- (0, _Utils.logWaitingForServer)(url, queryParams);
1200
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1201
- return _axios["default"].request({
1202
- method: 'GET',
1203
- url: url,
1204
- auth: {
1205
- username: username,
1206
- password: password
1207
- },
1208
- responseType: responseType,
1209
- params: queryParams,
1210
- headers: headers
1211
- }).then(function (result) {
1212
- _Utils.Log.info("".concat(operationName, " succeeded. The result of this operation will be in ").concat(operationName, " state.data or in your ").concat(operationName, " callback."));
1213
-
1214
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1215
- return (0, _languageCommon.composeNextState)(state, result.data);
1216
- });
1217
- };
1218
- }
1219
- /**
1220
- * Get data. Generic helper method for getting data of any kind from DHIS2.
1221
- * - This can be used to get `DataValueSets`,`events`,`trackedEntityInstances`,`etc.`
1222
- * @public
1223
- * @function
1224
- * @param {string} resourceType - The type of resource to get(use its `plural` name). E.g. `dataElements`, `trackedEntityInstances`,`organisationUnits`, etc.
1225
- * @param {Object} [params] - Optional `query parameters` e.g. `{ou: 'DiszpKrYNg8'}`. 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 for a given type of resource.
1226
- * @param {{apiVersion: number,operationName: string,responseType: string}}[options] - `Optional` options for `getData` operation. Defaults to `{operationName: 'getData', apiVersion: state.configuration.apiVersion, responseType: 'json'}`.
1227
- * @param {function} [callback] - Optional callback to handle the response
1228
- * @returns {Operation} state
1229
- * @example <caption>Example getting one `trackedEntityInstance` with `Id` 'dNpxRu1mWG5' for a given `orgUnit(DiszpKrYNg8)`</caption>
1230
- * getData('trackedEntityInstances', {
1231
- * fields: '*',
1232
- * ou: 'DiszpKrYNg8',
1233
- * entityType: 'nEenWmSyUEp',
1234
- * trackedEntityInstance: 'dNpxRu1mWG5',
1235
- * });
1236
- */
1237
-
1238
-
1239
- function getData(resourceType, params, options, callback) {
1240
- return function (state) {
1241
- var _options$operationNam, _options8, _options$responseType3, _options9, _params4, _params5, _params6, _options$apiVersion3, _options10, _CONTENT_TYPES$respon3;
1242
-
1243
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1244
- params = (0, _languageCommon.expandReferences)(params)(state);
1245
- options = (0, _languageCommon.expandReferences)(options)(state);
1246
- var operationName = (_options$operationNam = (_options8 = options) === null || _options8 === void 0 ? void 0 : _options8.operationName) !== null && _options$operationNam !== void 0 ? _options$operationNam : 'getData';
1247
- var _state$configuration5 = state.configuration,
1248
- username = _state$configuration5.username,
1249
- password = _state$configuration5.password,
1250
- hostUrl = _state$configuration5.hostUrl;
1251
- var responseType = (_options$responseType3 = (_options9 = options) === null || _options9 === void 0 ? void 0 : _options9.responseType) !== null && _options$responseType3 !== void 0 ? _options$responseType3 : 'json';
1252
- var filters = (_params4 = params) === null || _params4 === void 0 ? void 0 : _params4.filters;
1253
- var dimensions = (_params5 = params) === null || _params5 === void 0 ? void 0 : _params5.dimensions;
1254
- (_params6 = params) === null || _params6 === void 0 ? true : delete _params6.filters;
1255
- var queryParams = new URLSearchParams(params);
1256
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1257
- return queryParams.append('filter', f);
1258
- });
1259
- dimensions === null || dimensions === void 0 ? void 0 : dimensions.map(function (d) {
1260
- return queryParams.append('dimension', d);
1261
- });
1262
- var apiVersion = (_options$apiVersion3 = (_options10 = options) === null || _options10 === void 0 ? void 0 : _options10.apiVersion) !== null && _options$apiVersion3 !== void 0 ? _options$apiVersion3 : state.configuration.apiVersion;
1263
- var headers = {
1264
- Accept: (_CONTENT_TYPES$respon3 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon3 !== void 0 ? _CONTENT_TYPES$respon3 : 'application/json'
1265
- };
1266
- var url = (0, _Utils.buildUrl)("/".concat(resourceType), hostUrl, apiVersion);
1267
- (0, _Utils.logOperation)(operationName);
1268
- (0, _Utils.logApiVersion)(apiVersion);
1269
- (0, _Utils.logWaitingForServer)(url, queryParams);
1270
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1271
- return _axios["default"].request({
1272
- method: 'GET',
1273
- url: url,
1274
- auth: {
1275
- username: username,
1276
- password: password
1277
- },
1278
- responseType: responseType,
1279
- params: queryParams,
1280
- headers: headers
1281
- }).then(function (result) {
1282
- _Utils.Log.info("".concat(operationName, " succeeded. The result of this operation will be in ").concat(operationName, " state.data or in your callback."));
1283
-
1284
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1285
- return (0, _languageCommon.composeNextState)(state, result.data);
1286
- });
1287
- };
1288
- }
1289
- /**
1290
- * Get metadata. A generic helper function to get metadata records from a given DHIS2 instance
1291
- * @public
1292
- * @function
1293
- * @param {string[]} resources - Required. List of metadata resources to fetch. E.g. `['organisationUnits', 'attributes']` or like `'dataSets'` if you only want a single type of resource. See `getResources` to see the types of resources available.
1294
- * @param {Object} [params] - Optional `query parameters` e.g. `{filters: ['name:like:ANC'],fields:'*'}`. See `discover` or visit {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#metadata-export DHIS2 API docs}
1295
- * @param {{apiVersion: number,operationName: string,resourceType: string}} [options] - Optional `options` for `getMetadata` operation. Defaults to `{operationName: 'getMetadata', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
1296
- * @param {function} [callback] - Optional `callback` to handle the response
1297
- * @returns {Operation}
1298
- * @example <caption>Example getting a list of `data elements` and `indicators` where `name` includes the word **ANC**</caption>
1299
- * getMetadata(['dataElements', 'indicators'], {
1300
- * filters: ['name:like:ANC'],
1301
- * });
1302
- */
1303
-
1304
-
1305
- function getMetadata(resources, params, options, callback) {
1306
- return function (state) {
1307
- var _options$responseType4, _options11, _queryParams, _queryParams2, _options$apiVersion4, _options12, _CONTENT_TYPES$respon4;
1308
-
1309
- resources = (0, _languageCommon.expandReferences)(resources)(state);
1310
- params = (0, _languageCommon.expandReferences)(params)(state);
1311
- options = (0, _languageCommon.expandReferences)(options)(state);
1312
- var operationName = 'getMetadata';
1313
- var _state$configuration6 = state.configuration,
1314
- username = _state$configuration6.username,
1315
- password = _state$configuration6.password,
1316
- hostUrl = _state$configuration6.hostUrl;
1317
- var responseType = (_options$responseType4 = (_options11 = options) === null || _options11 === void 0 ? void 0 : _options11.responseType) !== null && _options$responseType4 !== void 0 ? _options$responseType4 : 'json';
1318
-
1319
- if (typeof resources === 'string') {
1320
- var res = {};
1321
- res[resources] = true;
1322
- resources = res;
1323
- } else {
1324
- resources = resources.reduce(function (acc, currentValue) {
1325
- acc[currentValue] = true;
1326
- return acc;
1327
- }, {});
1328
- }
1329
-
1330
- var queryParams = _objectSpread({}, resources, {}, params);
1331
-
1332
- var filters = (_queryParams = queryParams) === null || _queryParams === void 0 ? void 0 : _queryParams.filters;
1333
- (_queryParams2 = queryParams) === null || _queryParams2 === void 0 ? true : delete _queryParams2.filters;
1334
- queryParams = new URLSearchParams(queryParams);
1335
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1336
- return queryParams.append('filter', f);
1337
- });
1338
- var apiVersion = (_options$apiVersion4 = (_options12 = options) === null || _options12 === void 0 ? void 0 : _options12.apiVersion) !== null && _options$apiVersion4 !== void 0 ? _options$apiVersion4 : state.configuration.apiVersion;
1339
- var headers = {
1340
- Accept: (_CONTENT_TYPES$respon4 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon4 !== void 0 ? _CONTENT_TYPES$respon4 : 'application/json'
1341
- };
1342
- var url = (0, _Utils.buildUrl)('/metadata', hostUrl, apiVersion);
1343
- (0, _Utils.logOperation)(operationName);
1344
- (0, _Utils.logApiVersion)(apiVersion);
1345
- (0, _Utils.logWaitingForServer)(url, queryParams);
1346
- (0, _Utils.warnExpectLargeResult)(queryParams, url);
1347
- return _axios["default"].request({
1348
- method: 'GET',
1349
- url: url,
1350
- auth: {
1351
- username: username,
1352
- password: password
1353
- },
1354
- responseType: responseType,
1355
- params: queryParams,
1356
- headers: headers
1357
- }).then(function (result) {
1358
- _Utils.Log.info("".concat(operationName, " succeeded. The result of this operation will be in ").concat(operationName, " state.data or in your callback."));
1359
-
1360
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1361
- return (0, _languageCommon.composeNextState)(state, result.data);
1362
- });
781
+ function dv(dataElement, value) {
782
+ return {
783
+ dataElement,
784
+ value
1363
785
  };
1364
- }
1365
- /**
1366
- * create data. A generic helper method to create a record of any kind in DHIS2
1367
- * @public
1368
- * @function
1369
- * @param {string} resourceType - Type of resource to create. E.g. `trackedEntityInstances`
1370
- * @param {Object} data - Data that will be used to create a given instance of resource
1371
- * @param {Object} [options] - Optional `options` to control the behavior of the `create` operation.` Defaults to `{operationName: 'create', apiVersion: null, responseType: 'json'}`
1372
- * @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 DHIS2 API documentation} or {@link discover}. Defauls to `DHIS2 default params` for a given resource type.
1373
- * @param {function} [callback] - Optional callback to handle the response
1374
- * @returns {Operation}
1375
- * @example <caption>- Example `expression.js` of `create`</caption>
1376
- * create('events', {
1377
- * program: 'eBAyeGv0exc',
1378
- * orgUnit: 'DiszpKrYNg8',
1379
- * eventDate: date,
1380
- * status: 'COMPLETED',
1381
- * completedDate: date,
1382
- * storedBy: 'admin',
1383
- * coordinate: {
1384
- * latitude: 59.8,
1385
- * longitude: 10.9,
1386
- * },
1387
- * dataValues: [
1388
- * {
1389
- * dataElement: 'qrur9Dvnyt5',
1390
- * value: '33',
1391
- * },
1392
- * {
1393
- * dataElement: 'oZg33kd9taw',
1394
- * value: 'Male',
1395
- * },
1396
- * {
1397
- * dataElement: 'msodh3rEMJa',
1398
- * value: date,
1399
- * },
1400
- * ],
1401
- * });
1402
- */
1403
-
1404
-
1405
- function create(resourceType, data, options, params, callback) {
1406
- return function (state) {
1407
- var _options$operationNam2, _options13, _options$responseType5, _options14, _params7, _params8, _options$apiVersion5, _options15, _CONTENT_TYPES$respon5;
1408
-
1409
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1410
- var body = (0, _languageCommon.expandReferences)(data)(state);
1411
- options = (0, _languageCommon.expandReferences)(options)(state);
1412
- params = (0, _languageCommon.expandReferences)(params)(state);
1413
- var operationName = (_options$operationNam2 = (_options13 = options) === null || _options13 === void 0 ? void 0 : _options13.operationName) !== null && _options$operationNam2 !== void 0 ? _options$operationNam2 : 'create';
1414
- var _state$configuration7 = state.configuration,
1415
- username = _state$configuration7.username,
1416
- password = _state$configuration7.password,
1417
- hostUrl = _state$configuration7.hostUrl;
1418
- var responseType = (_options$responseType5 = (_options14 = options) === null || _options14 === void 0 ? void 0 : _options14.responseType) !== null && _options$responseType5 !== void 0 ? _options$responseType5 : 'json';
1419
- var filters = (_params7 = params) === null || _params7 === void 0 ? void 0 : _params7.filters;
1420
- (_params8 = params) === null || _params8 === void 0 ? true : delete _params8.filters;
1421
- var queryParams = new URLSearchParams(params);
1422
- var apiVersion = (_options$apiVersion5 = (_options15 = options) === null || _options15 === void 0 ? void 0 : _options15.apiVersion) !== null && _options$apiVersion5 !== void 0 ? _options$apiVersion5 : state.configuration.apiVersion;
1423
- var url = (0, _Utils.buildUrl)('/' + resourceType, hostUrl, apiVersion);
1424
- var headers = {
1425
- Accept: (_CONTENT_TYPES$respon5 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon5 !== void 0 ? _CONTENT_TYPES$respon5 : 'application/json',
1426
- 'Content-Type': 'application/json'
1427
- };
1428
- (0, _Utils.logOperation)(operationName);
1429
- (0, _Utils.logApiVersion)(apiVersion);
1430
- (0, _Utils.logWaitingForServer)(url, queryParams);
1431
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1432
- return _axios["default"].request({
1433
- method: 'POST',
1434
- url: url,
1435
- auth: {
1436
- username: username,
1437
- password: password
1438
- },
1439
- params: queryParams,
1440
- data: body,
1441
- headers: headers
1442
- }).then(function (result) {
1443
- var _result$data$response, _result$data$response2;
1444
-
1445
- _Utils.Log.info("".concat(operationName, " succeeded. Created ").concat(resourceType, ": ").concat(((_result$data$response = result.data.response) === null || _result$data$response === void 0 ? void 0 : _result$data$response.importSummaries) ? result.data.response.importSummaries[0].href : (_result$data$response2 = result.data.response) === null || _result$data$response2 === void 0 ? void 0 : _result$data$response2.reference, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
1446
-
1447
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1448
- return (0, _languageCommon.composeNextState)(state, result.data);
1449
- });
1450
- };
1451
- }
1452
- /**
1453
- * Update data. A generic helper function to update a resource object of any type.
1454
- * - It requires to send `all required fields` or the `full body`
1455
- * @public
1456
- * @function
1457
- * @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
1458
- * @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
1459
- * @param {Object} data - Data to update. It requires to send `all required fields` or the `full body`. If you want `partial updates`, use `patch` operation.
1460
- * @param {Object} [params] - Optional `update` parameters e.g. `{preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#create-update-parameters DHIS2 documentation}
1461
- * @param {{apiVersion: number,operationName: string,resourceType: string}} [options] - Optional options for update method. Defaults to `{operationName: 'update', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
1462
- * @param {function} [callback] - Optional callback to handle the response
1463
- * @returns {Operation}
1464
- * @example <caption>Example `updating` a `data element`</caption>
1465
- * update('dataElements', 'FTRrcoaog83',
1466
- * {
1467
- * displayName: 'New display name',
1468
- * aggregationType: 'SUM',
1469
- * domainType: 'AGGREGATE',
1470
- * valueType: 'NUMBER',
1471
- * name: 'Accute Flaccid Paralysis (Deaths < 5 yrs)',
1472
- * shortName: 'Accute Flaccid Paral (Deaths < 5 yrs)',
1473
- * });
1474
- *
1475
- */
1476
-
1477
-
1478
- function update(resourceType, path, data, params, options, callback) {
1479
- return function (state) {
1480
- var _options$operationNam3, _options16, _options$responseType6, _options17, _params9, _params10, _options$apiVersion6, _options18, _CONTENT_TYPES$respon6;
1481
-
1482
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1483
- path = (0, _languageCommon.expandReferences)(path)(state);
1484
- var body = (0, _languageCommon.expandReferences)(data)(state);
1485
- params = (0, _languageCommon.expandReferences)(params)(state);
1486
- options = (0, _languageCommon.expandReferences)(options)(state);
1487
- var _state$configuration8 = state.configuration,
1488
- username = _state$configuration8.username,
1489
- password = _state$configuration8.password,
1490
- hostUrl = _state$configuration8.hostUrl;
1491
- var operationName = (_options$operationNam3 = (_options16 = options) === null || _options16 === void 0 ? void 0 : _options16.operationName) !== null && _options$operationNam3 !== void 0 ? _options$operationNam3 : 'update';
1492
- var responseType = (_options$responseType6 = (_options17 = options) === null || _options17 === void 0 ? void 0 : _options17.responseType) !== null && _options$responseType6 !== void 0 ? _options$responseType6 : 'json';
1493
- var filters = (_params9 = params) === null || _params9 === void 0 ? void 0 : _params9.filters;
1494
- (_params10 = params) === null || _params10 === void 0 ? true : delete _params10.filters;
1495
- var queryParams = new URLSearchParams(params);
1496
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1497
- return queryParams.append('filter', f);
1498
- });
1499
- var apiVersion = (_options$apiVersion6 = (_options18 = options) === null || _options18 === void 0 ? void 0 : _options18.apiVersion) !== null && _options$apiVersion6 !== void 0 ? _options$apiVersion6 : state.configuration.apiVersion;
1500
- var url = (0, _Utils.buildUrl)('/' + resourceType + '/' + path, hostUrl, apiVersion);
1501
- var headers = {
1502
- Accept: (_CONTENT_TYPES$respon6 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon6 !== void 0 ? _CONTENT_TYPES$respon6 : 'application/json'
1503
- };
1504
- (0, _Utils.logOperation)(operationName);
1505
- (0, _Utils.logApiVersion)(apiVersion);
1506
- (0, _Utils.logWaitingForServer)(url, queryParams);
1507
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1508
- return _axios["default"].request({
1509
- method: 'PUT',
1510
- url: url,
1511
- auth: {
1512
- username: username,
1513
- password: password
1514
- },
1515
- params: queryParams,
1516
- data: body,
1517
- headers: headers
1518
- }).then(function (result) {
1519
- _Utils.Log.info("".concat(operationName, " succeeded. Updated ").concat(resourceType, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
1520
-
1521
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1522
- return (0, _languageCommon.composeNextState)(state, result.data);
1523
- });
1524
- };
1525
- }
1526
- /**
1527
- * Patch a record. A generic helper function to send partial updates on one or more object properties.
1528
- * - You are not required to send the full body of object properties.
1529
- * - This is useful for cases where you don't want or need to update all properties on a object.
1530
- * @public
1531
- * @function
1532
- * @param {string} resourceType - The type of resource to be updated. E.g. `dataElements`, `organisationUnits`, etc.
1533
- * @param {string} path - The `id` or `path` to the `object` to be updated. E.g. `FTRrcoaog83` or `FTRrcoaog83/{collection-name}/{object-id}`
1534
- * @param {Object} data - Data to update. Include only the fields you want to update. E.g. `{name: "New Name"}`
1535
- * @param {Object} [params] - Optional `update` parameters e.g. `{preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#create-update-parameters DHIS2 documentation}
1536
- * @param {{apiVersion: number,operationName: string,responseType: string}} [options] - Optional options for update method. Defaults to `{operationName: 'patch', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
1537
- * @param {function} [callback] - Optional callback to handle the response
1538
- * @returns {Operation}
1539
- * @example <caption>Example `patching` a `data element`</caption>
1540
- * patch('dataElements', 'FTRrcoaog83',
1541
- * {
1542
- * name: 'New Name',
1543
- * });
1544
- */
1545
-
1546
-
1547
- function patch(resourceType, path, data, params, options, callback) {
1548
- return function (state) {
1549
- var _options$operationNam4, _options19, _options$responseType7, _options20, _queryParams3, _queryParams4, _options$apiVersion7, _options21, _CONTENT_TYPES$respon7;
1550
-
1551
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1552
- path = (0, _languageCommon.expandReferences)(path)(state);
1553
- var body = (0, _languageCommon.expandReferences)(data)(state);
1554
- params = (0, _languageCommon.expandReferences)(params)(state);
1555
- options = (0, _languageCommon.expandReferences)(options)(state);
1556
- var operationName = (_options$operationNam4 = (_options19 = options) === null || _options19 === void 0 ? void 0 : _options19.operationName) !== null && _options$operationNam4 !== void 0 ? _options$operationNam4 : 'patch';
1557
- var _state$configuration9 = state.configuration,
1558
- username = _state$configuration9.username,
1559
- password = _state$configuration9.password,
1560
- hostUrl = _state$configuration9.hostUrl;
1561
- var responseType = (_options$responseType7 = (_options20 = options) === null || _options20 === void 0 ? void 0 : _options20.responseType) !== null && _options$responseType7 !== void 0 ? _options$responseType7 : 'json';
1562
- var queryParams = params;
1563
- var filters = (_queryParams3 = queryParams) === null || _queryParams3 === void 0 ? void 0 : _queryParams3.filters;
1564
- (_queryParams4 = queryParams) === null || _queryParams4 === void 0 ? true : delete _queryParams4.filters;
1565
- queryParams = new URLSearchParams(queryParams);
1566
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1567
- return queryParams.append('filter', f);
1568
- });
1569
- var apiVersion = (_options$apiVersion7 = (_options21 = options) === null || _options21 === void 0 ? void 0 : _options21.apiVersion) !== null && _options$apiVersion7 !== void 0 ? _options$apiVersion7 : state.configuration.apiVersion;
1570
- var url = (0, _Utils.buildUrl)('/' + resourceType + '/' + path, hostUrl, apiVersion);
1571
- var headers = {
1572
- Accept: (_CONTENT_TYPES$respon7 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon7 !== void 0 ? _CONTENT_TYPES$respon7 : 'application/json'
1573
- };
1574
- (0, _Utils.logOperation)(operationName);
1575
- (0, _Utils.logApiVersion)(apiVersion);
1576
- (0, _Utils.logWaitingForServer)(url, queryParams);
1577
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1578
- return _axios["default"].request({
1579
- method: 'PATCH',
1580
- url: url,
1581
- auth: {
1582
- username: username,
1583
- password: password
1584
- },
1585
- params: queryParams,
1586
- data: body,
1587
- headers: headers
1588
- }).then(function (result) {
1589
- var resultObject = {
1590
- status: result.status,
1591
- statusText: result.statusText
1592
- };
1593
-
1594
- _Utils.Log.info("".concat(operationName, " succeeded. Updated ").concat(resourceType, ".\nSummary:\n").concat((0, _Utils.prettyJson)(resultObject)));
1595
-
1596
- if (callback) return callback((0, _languageCommon.composeNextState)(state, resultObject));
1597
- return (0, _languageCommon.composeNextState)(state, resultObject);
1598
- });
1599
- };
1600
- }
1601
- /**
1602
- * Delete a record. A generic helper function to delete an object
1603
- * @public
1604
- * @function
1605
- * @param {string} resourceType - The type of resource to be deleted. E.g. `trackedEntityInstances`, `organisationUnits`, etc.
1606
- * @param {string} path - Can be an `id` of an `object` or `path` to the `nested object` to `delete`.
1607
- * @param {Object} [data] - Optional. This is useful when you want to remove multiple objects from a collection in one request. You can send `data` as, for example, `{"identifiableObjects": [{"id": "IDA"}, {"id": "IDB"}, {"id": "IDC"}]}`. See more {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#deleting-objects on DHIS2 API docs}
1608
- * @param {Object} [params] - Optional `update` parameters e.g. `{preheatCache: true, strategy: 'UPDATE', mergeMode: 'REPLACE'}`. Run `discover` or see {@link https://docs.dhis2.org/2.34/en/dhis2_developer_manual/web-api.html#create-update-parameters DHIS2 documentation}
1609
- * @param {{apiVersion: number,operationName: string,resourceType: string}} [options] - Optional `options` for `del` operation. Defaults to `{operationName: 'delete', apiVersion: state.configuration.apiVersion, responseType: 'json'}`
1610
- * @param {function} [callback] - Optional callback to handle the response
1611
- * @returns {Operation}
1612
- * @example <caption>Example`deleting` a `tracked entity instance`</caption>
1613
- * del('trackedEntityInstances', 'LcRd6Nyaq7T');
1614
- */
1615
-
1616
-
1617
- function del(resourceType, path, data, params, options, callback) {
1618
- return function (state) {
1619
- var _options$operationNam5, _options22, _options$responseType8, _options23, _queryParams5, _queryParams6, _options$apiVersion8, _options24, _CONTENT_TYPES$respon8;
1620
-
1621
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1622
- path = (0, _languageCommon.expandReferences)(path)(state);
1623
- var body = (0, _languageCommon.expandReferences)(data)(state);
1624
- params = (0, _languageCommon.expandReferences)(params)(state);
1625
- options = (0, _languageCommon.expandReferences)(options)(state);
1626
- var operationName = (_options$operationNam5 = (_options22 = options) === null || _options22 === void 0 ? void 0 : _options22.operationName) !== null && _options$operationNam5 !== void 0 ? _options$operationNam5 : 'delete';
1627
- var _state$configuration10 = state.configuration,
1628
- username = _state$configuration10.username,
1629
- password = _state$configuration10.password,
1630
- hostUrl = _state$configuration10.hostUrl;
1631
- var responseType = (_options$responseType8 = (_options23 = options) === null || _options23 === void 0 ? void 0 : _options23.responseType) !== null && _options$responseType8 !== void 0 ? _options$responseType8 : 'json';
1632
- var queryParams = params;
1633
- var filters = (_queryParams5 = queryParams) === null || _queryParams5 === void 0 ? void 0 : _queryParams5.filters;
1634
- (_queryParams6 = queryParams) === null || _queryParams6 === void 0 ? true : delete _queryParams6.filters;
1635
- queryParams = new URLSearchParams(queryParams);
1636
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1637
- return queryParams.append('filter', f);
1638
- });
1639
- var apiVersion = (_options$apiVersion8 = (_options24 = options) === null || _options24 === void 0 ? void 0 : _options24.apiVersion) !== null && _options$apiVersion8 !== void 0 ? _options$apiVersion8 : state.configuration.apiVersion;
1640
- var headers = {
1641
- Accept: (_CONTENT_TYPES$respon8 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon8 !== void 0 ? _CONTENT_TYPES$respon8 : 'application/json'
1642
- };
1643
- var url = (0, _Utils.buildUrl)('/' + resourceType + '/' + path, hostUrl, apiVersion);
1644
- (0, _Utils.logOperation)(operationName);
1645
- (0, _Utils.logApiVersion)(apiVersion);
1646
- (0, _Utils.logWaitingForServer)(url, queryParams);
1647
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1648
- return _axios["default"].request({
1649
- method: 'DELETE',
1650
- url: url,
1651
- auth: {
1652
- username: username,
1653
- password: password
1654
- },
1655
- params: queryParams,
1656
- data: body,
1657
- headers: headers
1658
- }).then(function (result) {
1659
- _Utils.Log.info("".concat(operationName, " succeeded. DELETED ").concat(resourceType, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
1660
-
1661
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1662
- return (0, _languageCommon.composeNextState)(state, result.data);
1663
- });
1664
- };
1665
- }
1666
- /**
1667
- * Upsert a record. A generic helper function used to atomically either insert a row, or on the basis of the row already existing, UPDATE that existing row instead.
1668
- * @public
1669
- * @function
1670
- * @param {string} resourceType - The type of a resource to `insert` or `update`. E.g. `trackedEntityInstances`
1671
- * @param {{attributeId: string,attributeValue:any}} uniqueAttribute - An object containing a `attributeId` and `attributeValue` which will be used to uniquely identify the record
1672
- * @param {Object} data - The update data containing new values
1673
- * @param {Object} [params] - Optional `import` parameters e.g. `{ou: 'lZGmxYbs97q', filters: ['w75KJ2mc4zz:EQ:Jane']}`
1674
- * @param {{replace:boolean, apiVersion: number,strict: boolean,responseType: string}} [options] - `Optional` options for `upsertTEI` operation. Defaults to `{replace: false, apiVersion: state.configuration.apiVersion,strict: true,responseType: 'json'}`.
1675
- * @param {function} [callback] - Optional callback to handle the response
1676
- * @throws {RangeError} - Throws range error
1677
- * @returns {Operation}
1678
- * @example <caption>- Example `expression.js` of upsert</caption>
1679
- * upsert(
1680
- * 'trackedEntityInstances',
1681
- * {
1682
- * attributeId: 'lZGmxYbs97q',
1683
- * attributeValue: state =>
1684
- * state.data.attributes.find(obj => obj.attribute === 'lZGmxYbs97q')
1685
- * .value,
1686
- * },
1687
- * state.data,
1688
- * { ou: 'TSyzvBiovKh' }
1689
- * );
1690
- * @todo Tweak/refine to mimic implementation based on the following inspiration: {@link https://sqlite.org/lang_upsert.html sqlite upsert} and {@link https://wiki.postgresql.org/wiki/UPSERT postgresql upsert}
1691
- * @todo Test implementation for upserting metadata
1692
- * @todo Test implementation for upserting data values
1693
- * @todo Implement the updateCondition
1694
- */
1695
-
1696
-
1697
- function upsert(resourceType, uniqueAttribute, data, params, options, callback) {
1698
- return function (state) {
1699
- var _options$operationNam6, _options25, _options$replace, _options26, _options$responseType9, _options27, _params11, _options$apiVersion9, _options28, _CONTENT_TYPES$respon9;
1700
-
1701
- resourceType = (0, _languageCommon.expandReferences)(resourceType)(state);
1702
- uniqueAttribute = (0, _languageCommon.expandReferences)(uniqueAttribute)(state);
1703
- var body = (0, _languageCommon.expandReferences)(data)(state);
1704
- params = (0, _languageCommon.expandReferences)(params)(state);
1705
- options = (0, _languageCommon.expandReferences)(options)(state);
1706
- var operationName = (_options$operationNam6 = (_options25 = options) === null || _options25 === void 0 ? void 0 : _options25.operationName) !== null && _options$operationNam6 !== void 0 ? _options$operationNam6 : 'upsert';
1707
- var _state$configuration11 = state.configuration,
1708
- username = _state$configuration11.username,
1709
- password = _state$configuration11.password,
1710
- hostUrl = _state$configuration11.hostUrl;
1711
- var replace = (_options$replace = (_options26 = options) === null || _options26 === void 0 ? void 0 : _options26.replace) !== null && _options$replace !== void 0 ? _options$replace : false;
1712
- var responseType = (_options$responseType9 = (_options27 = options) === null || _options27 === void 0 ? void 0 : _options27.responseType) !== null && _options$responseType9 !== void 0 ? _options$responseType9 : 'json';
1713
- var _uniqueAttribute = uniqueAttribute,
1714
- attributeId = _uniqueAttribute.attributeId,
1715
- attributeValue = _uniqueAttribute.attributeValue;
1716
- var filters = (_params11 = params) === null || _params11 === void 0 ? void 0 : _params11.filters;
1717
- delete params.filters;
1718
- var queryParams = new URLSearchParams(params);
1719
- filters === null || filters === void 0 ? void 0 : filters.map(function (f) {
1720
- return queryParams.append('filter', f);
1721
- });
1722
- var op = resourceType === 'trackedEntityInstances' ? 'EQ' : 'eq';
1723
- queryParams.append('filter', "".concat(attributeId, ":").concat(op, ":").concat(attributeValue));
1724
- var apiVersion = (_options$apiVersion9 = (_options28 = options) === null || _options28 === void 0 ? void 0 : _options28.apiVersion) !== null && _options$apiVersion9 !== void 0 ? _options$apiVersion9 : state.configuration.apiVersion;
1725
- var url = (0, _Utils.buildUrl)('/' + resourceType, hostUrl, apiVersion);
1726
- var headers = {
1727
- Accept: (_CONTENT_TYPES$respon9 = _Utils.CONTENT_TYPES[responseType]) !== null && _CONTENT_TYPES$respon9 !== void 0 ? _CONTENT_TYPES$respon9 : 'application/json'
1728
- };
1729
- (0, _Utils.logOperation)(operationName);
1730
- (0, _Utils.logApiVersion)(apiVersion);
1731
- (0, _Utils.logWaitingForServer)(url, queryParams);
1732
- (0, _Utils.warnExpectLargeResult)(resourceType, url);
1733
-
1734
- var getResouceName = function getResouceName() {
1735
- return _axios["default"].get(hostUrl + '/api/resources', {
1736
- auth: {
1737
- username: username,
1738
- password: password
1739
- },
1740
- transformResponse: [function (data, headers) {
1741
- var filter = "plural:eq:".concat(resourceType);
1742
-
1743
- if (filter) {
1744
- var _headers$contentType3, _headers$contentType4;
1745
-
1746
- if (((_headers$contentType3 = (_headers$contentType4 = headers['content-type']) === null || _headers$contentType4 === void 0 ? void 0 : _headers$contentType4.split(';')[0]) !== null && _headers$contentType3 !== void 0 ? _headers$contentType3 : null) === _Utils.CONTENT_TYPES.json) {
1747
- var tempData = JSON.parse(data);
1748
- return _objectSpread({}, tempData, {
1749
- resources: _Utils.applyFilter.apply(void 0, [tempData.resources].concat(_toConsumableArray((0, _Utils.parseFilter)(filter))))
1750
- });
1751
- } else {
1752
- _Utils.Log.warn('Filters on this resource are only supported for json content types. Skipping filtering ...');
1753
- }
1754
- }
1755
-
1756
- return data;
1757
- }]
1758
- }).then(function (result) {
1759
- return result.data.resources[0].singular;
1760
- });
1761
- };
1762
-
1763
- var findRecordsWithValueOnAttribute = function findRecordsWithValueOnAttribute() {
1764
- console.log(queryParams);
1765
- return _axios["default"].request({
1766
- method: 'GET',
1767
- url: url,
1768
- auth: {
1769
- username: username,
1770
- password: password
1771
- },
1772
- params: queryParams,
1773
- headers: headers
1774
- });
1775
- };
1776
-
1777
- _Utils.Log.info("Checking if a record exists that matches this filter: attribute{ id: ".concat(attributeId, ", value: ").concat(attributeValue, " } ..."));
1778
-
1779
- return Promise.all([getResouceName(), findRecordsWithValueOnAttribute()]).then(function (_ref3) {
1780
- var _ref4 = _slicedToArray(_ref3, 2),
1781
- resourceName = _ref4[0],
1782
- recordsWithValue = _ref4[1];
1783
-
1784
- var recordsWithValueCount = recordsWithValue.data[resourceType].length;
1785
-
1786
- if (recordsWithValueCount > 1) {
1787
- _Utils.Log.error('');
1788
-
1789
- throw new RangeError("Cannot upsert on Non-unique attribute. The operation found more than one records with the same value of ".concat(attributeValue, " for ").concat(attributeId));
1790
- } else if (recordsWithValueCount === 1) {
1791
- var _row1$id;
1792
-
1793
- // TODO
1794
- // Log.info(
1795
- // `Unique record found, proceeding to checking if attribute is NULLABLE ...`
1796
- // );
1797
- // if (recordsWithNulls.data[resourceType].length > 0) {
1798
- // throw new Error(
1799
- // `Cannot upsert on Nullable attribute. The operation found records with a NULL value on ${attributeId}.`
1800
- // );
1801
- // }
1802
- _Utils.Log.info("Attribute has unique values. Proceeding to ".concat(replace ? 'replace' : 'merge', " ..."));
1803
-
1804
- var row1 = recordsWithValue.data[resourceType][0];
1805
- var useCustomPATCH = ['trackedEntityInstances'].includes(resourceType) ? true : false;
1806
- var method = replace ? 'PUT' : useCustomPATCH === true ? 'PUT' : 'PATCH';
1807
- var id = (_row1$id = row1['id']) !== null && _row1$id !== void 0 ? _row1$id : row1[resourceName];
1808
- var updateUrl = "".concat(url, "/").concat(id);
1809
- var payload = useCustomPATCH ? _objectSpread({}, row1, {}, body, {
1810
- attributes: [].concat(_toConsumableArray(row1.attributes), _toConsumableArray(body.attributes))
1811
- }) : body;
1812
- return _axios["default"].request({
1813
- method: method,
1814
- url: updateUrl,
1815
- auth: {
1816
- username: username,
1817
- password: password
1818
- },
1819
- data: payload,
1820
- params: queryParams,
1821
- headers: headers
1822
- }).then(function (result) {
1823
- _Utils.Log.info("".concat(operationName, " succeeded. Updated ").concat(resourceName, ": ").concat(updateUrl, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
1824
-
1825
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1826
- return (0, _languageCommon.composeNextState)(state, result.data);
1827
- });
1828
- } else if (recordsWithValueCount === 0) {
1829
- _Utils.Log.info("Existing record not found, proceeding to CREATE(POST) ..."); // We must delete the filter and ou params so the POST request is not interpreted as a GET request by the server
1830
-
1831
-
1832
- queryParams["delete"]('filter');
1833
- queryParams["delete"]('ou');
1834
- return _axios["default"].request({
1835
- method: 'POST',
1836
- url: url,
1837
- auth: {
1838
- username: username,
1839
- password: password
1840
- },
1841
- data: body,
1842
- params: queryParams,
1843
- headers: headers
1844
- }).then(function (result) {
1845
- var _result$data$response3;
1846
-
1847
- _Utils.Log.info("".concat(operationName, " succeeded. Created ").concat(resourceName, ": ").concat(result.data.response.importSummaries ? result.data.response.importSummaries[0].href : (_result$data$response3 = result.data.response) === null || _result$data$response3 === void 0 ? void 0 : _result$data$response3.reference, ".\nSummary:\n").concat((0, _Utils.prettyJson)(result.data)));
1848
-
1849
- if (callback) return callback((0, _languageCommon.composeNextState)(state, result.data));
1850
- return (0, _languageCommon.composeNextState)(state, result.data);
1851
- });
1852
- }
1853
- });
1854
- };
1855
- }
1856
- /**
1857
- * Gets an attribute value by its case-insensitive display name
1858
- * @public
1859
- * @example
1860
- * valByName(tei.attributes, 'first name')
1861
- * @function
1862
- * @param {Object} tei - A tracked entity instance (TEI) object
1863
- * @param {string} attributeName - The 'displayName' to search for in the TEI's attributes
1864
- * @returns {string}
1865
- */
1866
-
1867
-
1868
- function attrVal(tei, attributeName) {
1869
- var _tei$attributes, _tei$attributes$find;
1870
-
1871
- return tei === null || tei === void 0 ? void 0 : (_tei$attributes = tei.attributes) === null || _tei$attributes === void 0 ? void 0 : (_tei$attributes$find = _tei$attributes.find(function (a) {
1872
- return (a === null || a === void 0 ? void 0 : a.displayName.toLowerCase()) == attributeName.toLowerCase();
1873
- })) === null || _tei$attributes$find === void 0 ? void 0 : _tei$attributes$find.value;
1874
786
  }