@wavemaker-ai/variables 1.0.0-rc.647469

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 (123) hide show
  1. package/index.d.ts +14 -0
  2. package/index.js +15 -0
  3. package/index.js.map +1 -0
  4. package/npm-shrinkwrap.json +1967 -0
  5. package/package-lock.json +1967 -0
  6. package/package.json +48 -0
  7. package/scripts/build.d.ts +1 -0
  8. package/scripts/build.js +183 -0
  9. package/scripts/build.js.map +1 -0
  10. package/src/advanced-options.d.ts +4 -0
  11. package/src/advanced-options.js +2 -0
  12. package/src/advanced-options.js.map +1 -0
  13. package/src/constants/variables.constants.d.ts +307 -0
  14. package/src/constants/variables.constants.js +334 -0
  15. package/src/constants/variables.constants.js.map +1 -0
  16. package/src/factory/variable-manager.factory.d.ts +3 -0
  17. package/src/factory/variable-manager.factory.js +26 -0
  18. package/src/factory/variable-manager.factory.js.map +1 -0
  19. package/src/manager/action/timer-action.manager.d.ts +4 -0
  20. package/src/manager/action/timer-action.manager.js +38 -0
  21. package/src/manager/action/timer-action.manager.js.map +1 -0
  22. package/src/manager/variable/base-variable.manager.d.ts +24 -0
  23. package/src/manager/variable/base-variable.manager.js +79 -0
  24. package/src/manager/variable/base-variable.manager.js.map +1 -0
  25. package/src/manager/variable/crud-variable.manager.d.ts +85 -0
  26. package/src/manager/variable/crud-variable.manager.js +415 -0
  27. package/src/manager/variable/crud-variable.manager.js.map +1 -0
  28. package/src/manager/variable/live-variable.manager.d.ts +154 -0
  29. package/src/manager/variable/live-variable.manager.js +1078 -0
  30. package/src/manager/variable/live-variable.manager.js.map +1 -0
  31. package/src/manager/variable/model-variable.manager.d.ts +4 -0
  32. package/src/manager/variable/model-variable.manager.js +56 -0
  33. package/src/manager/variable/model-variable.manager.js.map +1 -0
  34. package/src/manager/variable/service-variable.manager.d.ts +113 -0
  35. package/src/manager/variable/service-variable.manager.js +713 -0
  36. package/src/manager/variable/service-variable.manager.js.map +1 -0
  37. package/src/model/action/timer-action.d.ts +12 -0
  38. package/src/model/action/timer-action.js +60 -0
  39. package/src/model/action/timer-action.js.map +1 -0
  40. package/src/model/base-action.d.ts +32 -0
  41. package/src/model/base-action.js +89 -0
  42. package/src/model/base-action.js.map +1 -0
  43. package/src/model/base-variable.d.ts +58 -0
  44. package/src/model/base-variable.js +180 -0
  45. package/src/model/base-variable.js.map +1 -0
  46. package/src/model/crud-create.d.ts +8 -0
  47. package/src/model/crud-create.js +17 -0
  48. package/src/model/crud-create.js.map +1 -0
  49. package/src/model/crud-delete.d.ts +8 -0
  50. package/src/model/crud-delete.js +17 -0
  51. package/src/model/crud-delete.js.map +1 -0
  52. package/src/model/crud-list.d.ts +8 -0
  53. package/src/model/crud-list.js +17 -0
  54. package/src/model/crud-list.js.map +1 -0
  55. package/src/model/crud-update.d.ts +8 -0
  56. package/src/model/crud-update.js +17 -0
  57. package/src/model/crud-update.js.map +1 -0
  58. package/src/model/variable/api-aware-variable.d.ts +23 -0
  59. package/src/model/variable/api-aware-variable.js +25 -0
  60. package/src/model/variable/api-aware-variable.js.map +1 -0
  61. package/src/model/variable/crud-variable.d.ts +30 -0
  62. package/src/model/variable/crud-variable.js +181 -0
  63. package/src/model/variable/crud-variable.js.map +1 -0
  64. package/src/model/variable/live-variable.d.ts +40 -0
  65. package/src/model/variable/live-variable.js +262 -0
  66. package/src/model/variable/live-variable.js.map +1 -0
  67. package/src/model/variable/model-variable.d.ts +11 -0
  68. package/src/model/variable/model-variable.js +83 -0
  69. package/src/model/variable/model-variable.js.map +1 -0
  70. package/src/model/variable/service-variable.d.ts +35 -0
  71. package/src/model/variable/service-variable.js +147 -0
  72. package/src/model/variable/service-variable.js.map +1 -0
  73. package/src/types/date-formatter.d.ts +3 -0
  74. package/src/types/date-formatter.js +2 -0
  75. package/src/types/date-formatter.js.map +1 -0
  76. package/src/types/event-notifier.d.ts +9 -0
  77. package/src/types/event-notifier.js +25 -0
  78. package/src/types/event-notifier.js.map +1 -0
  79. package/src/types/http-client.service.d.ts +8 -0
  80. package/src/types/http-client.service.js +2 -0
  81. package/src/types/http-client.service.js.map +1 -0
  82. package/src/types/types.d.ts +50 -0
  83. package/src/types/types.js +54 -0
  84. package/src/types/types.js.map +1 -0
  85. package/src/util/dataset-util.d.ts +27 -0
  86. package/src/util/dataset-util.js +147 -0
  87. package/src/util/dataset-util.js.map +1 -0
  88. package/src/util/file-upload.util.d.ts +11 -0
  89. package/src/util/file-upload.util.js +183 -0
  90. package/src/util/file-upload.util.js.map +1 -0
  91. package/src/util/inflight-queue.d.ts +35 -0
  92. package/src/util/inflight-queue.js +102 -0
  93. package/src/util/inflight-queue.js.map +1 -0
  94. package/src/util/notify-promise.d.ts +3 -0
  95. package/src/util/notify-promise.js +37 -0
  96. package/src/util/notify-promise.js.map +1 -0
  97. package/src/util/oAuth.utils.d.ts +3 -0
  98. package/src/util/oAuth.utils.js +11 -0
  99. package/src/util/oAuth.utils.js.map +1 -0
  100. package/src/util/utils.d.ts +69 -0
  101. package/src/util/utils.js +364 -0
  102. package/src/util/utils.js.map +1 -0
  103. package/src/util/variable/live-variable.http.utils.d.ts +21 -0
  104. package/src/util/variable/live-variable.http.utils.js +212 -0
  105. package/src/util/variable/live-variable.http.utils.js.map +1 -0
  106. package/src/util/variable/live-variable.utils.d.ts +72 -0
  107. package/src/util/variable/live-variable.utils.js +667 -0
  108. package/src/util/variable/live-variable.utils.js.map +1 -0
  109. package/src/util/variable/pagination.utils.d.ts +91 -0
  110. package/src/util/variable/pagination.utils.js +493 -0
  111. package/src/util/variable/pagination.utils.js.map +1 -0
  112. package/src/util/variable/service-variable.utils.d.ts +17 -0
  113. package/src/util/variable/service-variable.utils.js +394 -0
  114. package/src/util/variable/service-variable.utils.js.map +1 -0
  115. package/src/util/variable/variables.utils.d.ts +120 -0
  116. package/src/util/variable/variables.utils.js +544 -0
  117. package/src/util/variable/variables.utils.js.map +1 -0
  118. package/src/wm-namespace.d.ts +11 -0
  119. package/src/wm-namespace.js +13 -0
  120. package/src/wm-namespace.js.map +1 -0
  121. package/webpack.config.d.ts +21 -0
  122. package/webpack.config.js +28 -0
  123. package/webpack.config.js.map +1 -0
@@ -0,0 +1,1078 @@
1
+ var __extends = (this && this.__extends) || (function () {
2
+ var extendStatics = function (d, b) {
3
+ extendStatics = Object.setPrototypeOf ||
4
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6
+ return extendStatics(d, b);
7
+ };
8
+ return function (d, b) {
9
+ if (typeof b !== "function" && b !== null)
10
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
11
+ extendStatics(d, b);
12
+ function __() { this.constructor = d; }
13
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14
+ };
15
+ })();
16
+ // import { $invokeWatchers, processFilterExpBindNode } from '@wm/core';
17
+ import { getClonedObject, isDateTimeType, isDefined, triggerFn } from "../../util/utils";
18
+ import { BaseVariableManager } from './base-variable.manager';
19
+ import { formatExportExpression, initiateCallback, setInput, appManager, formatDate, getErrMessage } from '../../util/variable/variables.utils';
20
+ import { LiveVariableUtils } from '../../util/variable/live-variable.utils';
21
+ import { decodeData } from './../../util/variable/variables.utils';
22
+ import { $queue } from '../../util/inflight-queue';
23
+ import { $rootScope, CONSTANTS, VARIABLE_CONSTANTS, DB_CONSTANTS } from '../../constants/variables.constants';
24
+ import { generateConnectionParams } from '../../util/variable/live-variable.http.utils';
25
+ import { VariableEvents } from "../../model/base-variable";
26
+ var emptyArr = [];
27
+ import { noop, indexOf, isObject, omit, isArray, extend, forEach, join, isUndefined, isEmpty, find, map, filter, get, split, replace, cloneDeep, isNil } from 'lodash-es';
28
+ var LiveVariableManager = /** @class */ (function (_super) {
29
+ __extends(LiveVariableManager, _super);
30
+ function LiveVariableManager() {
31
+ var _this = _super !== null && _super.apply(this, arguments) || this;
32
+ /**
33
+ * Traverses recursively the filterExpressions object and if there is any required field present with no value,
34
+ * then we will return without proceeding further. Its upto the developer to provide the mandatory value,
35
+ * if he wants to assign it in teh onbefore<delete/insert/update>function then make that field in
36
+ * the filter query section as optional
37
+ * @param filterExpressions - recursive rule Object
38
+ * @returns {Object} object or boolean. Object if everything gets validated or else just boolean indicating failure in the validations
39
+ */
40
+ _this.getFilterExprFields = function (filterExpressions) {
41
+ var isRequiredFieldAbsent = false;
42
+ var traverseCallbackFn = function (parentFilExpObj, filExpObj) {
43
+ if (filExpObj
44
+ && filExpObj.required
45
+ && ((indexOf(['null', 'isnotnull', 'empty', 'isnotempty', 'nullorempty'], filExpObj.matchMode) === -1) && filExpObj.value === '')) {
46
+ isRequiredFieldAbsent = true;
47
+ return false;
48
+ }
49
+ };
50
+ LiveVariableUtils.traverseFilterExpressions(filterExpressions, traverseCallbackFn);
51
+ return isRequiredFieldAbsent ? !isRequiredFieldAbsent : filterExpressions;
52
+ };
53
+ /**
54
+ * Allows the user to get the criteria of filtering and the filter fields, based on the method called
55
+ */
56
+ _this.getDataFilterObj = function (clonedFilterFields) {
57
+ return (function (clonedFields) {
58
+ function getCriteria(filterField) {
59
+ var criterian = [];
60
+ LiveVariableUtils.traverseFilterExpressions(clonedFields, function (filterExpressions, criteria) {
61
+ if (filterField === criteria.target) {
62
+ criterian.push(criteria);
63
+ }
64
+ });
65
+ return criterian;
66
+ }
67
+ function getFilterFields() {
68
+ return clonedFields;
69
+ }
70
+ return {
71
+ getFilterFields: getFilterFields,
72
+ getCriteria: getCriteria
73
+ };
74
+ }(clonedFilterFields));
75
+ };
76
+ return _this;
77
+ }
78
+ LiveVariableManager.prototype.initFilterExpressionBinding = function (variable) {
79
+ var context = variable._context;
80
+ var destroyFn = context.registerDestroyListener ? context.registerDestroyListener.bind(context) : noop;
81
+ // ToDo - variable seperation
82
+ // const filterSubscription = processFilterExpBindNode(context, variable.filterExpressions).subscribe((response: any) => {
83
+ // if (variable.operation === 'read') {
84
+ // /* if auto-update set for the variable with read operation only, get its data */
85
+ // if (variable.autoUpdate && !isUndefined(response.newVal) && isFunction(variable.update)) {
86
+ // debounceVariableCall(variable, 'update');
87
+ // }
88
+ // } else {
89
+ // /* if auto-update set for the variable with read operation only, get its data */
90
+ // if (variable.autoUpdate && !isUndefined(response.newVal) && isFunction(variable[variable.operation + 'Record'])) {
91
+ // debounceVariableCall(variable, variable.operation + 'Record');
92
+ // }
93
+ // }
94
+ // });
95
+ // destroyFn(() => filterSubscription.unsubscribe());
96
+ };
97
+ LiveVariableManager.prototype.updateDataset = function (variable, data, propertiesMap, pagination) {
98
+ variable.pagination = pagination;
99
+ variable.dataSet = data;
100
+ // legacy properties in dataSet, [data, pagination]
101
+ Object.defineProperty(variable.dataSet, 'data', {
102
+ get: function () {
103
+ return variable.dataSet;
104
+ }
105
+ });
106
+ Object.defineProperty(variable.dataSet, 'pagination', {
107
+ get: function () {
108
+ return variable.pagination;
109
+ }
110
+ });
111
+ };
112
+ // Set the _options on variable which can be used by the widgets
113
+ LiveVariableManager.prototype.setVariableOptions = function (variable, options) {
114
+ variable._options = variable._options || {};
115
+ variable._options.orderBy = options && options.orderBy;
116
+ variable._options.filterFields = options && options.filterFields;
117
+ variable._options.logicalOp = options && options.logicalOp;
118
+ };
119
+ LiveVariableManager.prototype.handleError = function (variable, errorCB, response, options, advancedOptions) {
120
+ var opt;
121
+ /* If callback function is provided, send the data to the callback.
122
+ * The same callback if triggered in case of error also. The error-handling is done in grid.js*/
123
+ triggerFn(errorCB, response);
124
+ // EVENT: ON_RESULT
125
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.RESULT, variable, response, advancedOptions);
126
+ /* update the dataSet against the variable */
127
+ if (!options.skipDataSetUpdate) {
128
+ this.updateDataset(variable, emptyArr, variable.propertiesMap, null);
129
+ }
130
+ // EVENT: ON_ERROR
131
+ opt = this.prepareCallbackOptions(options.errorDetails);
132
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.ERROR, variable, response, opt);
133
+ // EVENT: ON_CAN_UPDATE
134
+ variable.canUpdate = true;
135
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.CAN_UPDATE, variable, response, advancedOptions);
136
+ };
137
+ LiveVariableManager.prototype.makeCall = function (variable, dbOperation, params) {
138
+ var _this = this;
139
+ var successHandler = function (response, resolve) {
140
+ if (response && response.type || response && response.status) {
141
+ resolve(response);
142
+ }
143
+ };
144
+ var errorHandler = function (error, reject) {
145
+ var errMsg = getErrMessage(error, variable.httpService.getLocale());
146
+ // notify variable error
147
+ _this.notifyInflight(variable, false);
148
+ reject({
149
+ error: errMsg,
150
+ details: error
151
+ });
152
+ };
153
+ return new Promise(function (resolve, reject) {
154
+ var reqParams = generateConnectionParams(params, dbOperation);
155
+ reqParams = {
156
+ url: reqParams.url,
157
+ method: reqParams.method,
158
+ data: reqParams.data,
159
+ headers: reqParams.headers
160
+ };
161
+ params.operation = dbOperation;
162
+ _this.httpCall(reqParams, variable, params).then(function (response) {
163
+ successHandler(response, resolve);
164
+ }, function (e) {
165
+ errorHandler(e, reject);
166
+ });
167
+ });
168
+ };
169
+ LiveVariableManager.prototype.getEntityData = function (variable, options, success, error) {
170
+ var _this = this;
171
+ var dataObj = {};
172
+ var tableOptions, dbOperation, output, newDataSet, clonedFields, requestData, dbOperationOptions, getEntitySuccess, getEntityError;
173
+ // empty array kept (if variable is not of read type filterExpressions will be undefined)
174
+ clonedFields = this.getFilterExprFields(getClonedObject(variable.filterExpressions || {}));
175
+ // clonedFields = getClonedObject(variable.filterFields);
176
+ // EVENT: ON_BEFORE_UPDATE
177
+ output = initiateCallback(VARIABLE_CONSTANTS.EVENT.BEFORE_UPDATE, variable, this.getDataFilterObj(clonedFields), options);
178
+ // if filterFields are updated or modified inside the onBeforeUpdate event then in device use these fields to filter.
179
+ var updateFilterFields = isObject(output) ? getClonedObject(output) : undefined;
180
+ if (output === false) {
181
+ $queue.process(variable);
182
+ // $rootScope.$emit('toggle-variable-state', variable, false);
183
+ triggerFn(error, 'Call stopped from the event: ' + VARIABLE_CONSTANTS.EVENT.BEFORE_UPDATE);
184
+ return Promise.reject('Call stopped from the event: ' + VARIABLE_CONSTANTS.EVENT.BEFORE_UPDATE);
185
+ }
186
+ variable.canUpdate = false;
187
+ tableOptions = LiveVariableUtils.prepareTableOptions(variable, options, isObject(output) ? output : clonedFields);
188
+ // if tableOptions object has query then set the dbOperation to 'searchTableDataWithQuery'
189
+ if (options.searchWithQuery) {
190
+ dbOperation = 'searchTableDataWithQuery';
191
+ requestData = tableOptions.query ? ('q=' + tableOptions.query) : '';
192
+ }
193
+ else {
194
+ dbOperation = (tableOptions.filter && tableOptions.filter.length) ? 'searchTableData' : 'readTableData';
195
+ requestData = tableOptions.filter;
196
+ }
197
+ dbOperationOptions = {
198
+ 'projectID': $rootScope.project.id,
199
+ 'service': variable.getPrefabName() ? '' : 'services',
200
+ 'dataModelName': variable.liveSource,
201
+ 'entityName': variable.type,
202
+ 'page': options.page || 1,
203
+ 'size': options.pagesize || (CONSTANTS.isRunMode ? (variable.maxResults || 20) : (variable.designMaxResults || 20)),
204
+ 'sort': tableOptions.sort,
205
+ 'data': requestData,
206
+ 'filter': LiveVariableUtils.getWhereClauseGenerator(variable, options, updateFilterFields),
207
+ // 'filterMeta': tableOptions.filter,
208
+ 'url': variable.getPrefabName() ? ($rootScope.project.deployedUrl + '/prefabs/' + variable.getPrefabName()) : $rootScope.project.deployedUrl
209
+ };
210
+ getEntitySuccess = function (response, resolve) {
211
+ if (response && (response.type || response.status)) {
212
+ response = response.body || response.data;
213
+ dataObj.data = response.content;
214
+ dataObj.pagination = omit(response, 'content');
215
+ var advancedOptions_1 = _this.prepareCallbackOptions(response, { pagination: dataObj.pagination });
216
+ if ((response && response.error) || !response || !isArray(response.content)) {
217
+ _this.handleError(variable, error, response.error, options, advancedOptions_1);
218
+ return Promise.reject(response.error);
219
+ }
220
+ decodeData(response.content);
221
+ LiveVariableUtils.processBlobColumns(response.content, variable);
222
+ if (!options.skipDataSetUpdate) {
223
+ // EVENT: ON_RESULT
224
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.RESULT, variable, dataObj.data, advancedOptions_1);
225
+ // EVENT: ON_PREPARESETDATA
226
+ newDataSet = initiateCallback(VARIABLE_CONSTANTS.EVENT.PREPARE_SETDATA, variable, dataObj.data, advancedOptions_1);
227
+ if (newDataSet) {
228
+ // setting newDataSet as the response to service variable onPrepareSetData
229
+ dataObj.data = newDataSet;
230
+ }
231
+ /* update the dataSet against the variable */
232
+ _this.updateDataset(variable, dataObj.data, variable.propertiesMap, dataObj.pagination);
233
+ _this.setVariableOptions(variable, options);
234
+ // watchers should get triggered before calling onSuccess event.
235
+ // so that any variable/widget depending on this variable's data is updated
236
+ variable.notify(VariableEvents.AFTER_INVOKE, [_this, dataObj.data]);
237
+ setTimeout(function () {
238
+ // if callback function is provided, send the data to the callback
239
+ triggerFn(success, dataObj.data, variable.propertiesMap, dataObj.pagination);
240
+ // EVENT: ON_SUCCESS
241
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.SUCCESS, variable, dataObj.data, advancedOptions_1);
242
+ // EVENT: ON_CAN_UPDATE
243
+ variable.canUpdate = true;
244
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.CAN_UPDATE, variable, dataObj.data, advancedOptions_1);
245
+ });
246
+ }
247
+ return resolve({ data: dataObj.data, pagination: dataObj.pagination });
248
+ }
249
+ };
250
+ getEntityError = function (e, reject) {
251
+ _this.setVariableOptions(variable, options);
252
+ _this.handleError(variable, error, e.error, extend(options, { errorDetails: e.details }));
253
+ return reject(e.error);
254
+ };
255
+ /* if it is a prefab variable (used in a normal project), modify the url */
256
+ /*Fetch the table data*/
257
+ return new Promise(function (resolve, reject) {
258
+ _this.makeCall(variable, dbOperation, dbOperationOptions).then(function (response) {
259
+ getEntitySuccess(response, resolve);
260
+ }, function (err) {
261
+ getEntityError(err, reject);
262
+ });
263
+ });
264
+ };
265
+ LiveVariableManager.prototype.performCUD = function (operation, variable, options, success, error) {
266
+ var _this = this;
267
+ options = options || {};
268
+ options.inputFields = options.inputFields || getClonedObject(variable.inputFields);
269
+ return $queue.submit(variable).then(function () {
270
+ _this.notifyInflight(variable, !options.skipToggleState);
271
+ return _this.doCUD(operation, variable, options, success, error)
272
+ .then(function (response) {
273
+ $queue.process(variable);
274
+ _this.notifyInflight(variable, false, response);
275
+ return Promise.resolve(response);
276
+ }, function (err) {
277
+ $queue.process(variable);
278
+ _this.notifyInflight(variable, false, err);
279
+ return Promise.reject(err);
280
+ });
281
+ }, error);
282
+ };
283
+ LiveVariableManager.prototype.doCUD = function (action, variable, options, success, error) {
284
+ var _this = this;
285
+ var projectID = $rootScope.project.id || $rootScope.projectName, primaryKey = LiveVariableUtils.getPrimaryKey(variable), isFormDataSupported = (window.File && window.FileReader && window.FileList && window.Blob);
286
+ var dbName, compositeId = '', rowObject = {}, prevData, compositeKeysData = {}, prevCompositeKeysData = {}, id, columnName, clonedFields, output, onCUDerror, onCUDsuccess, inputFields = options.inputFields || variable.inputFields;
287
+ // EVENT: ON_BEFORE_UPDATE
288
+ clonedFields = getClonedObject(inputFields);
289
+ output = initiateCallback(VARIABLE_CONSTANTS.EVENT.BEFORE_UPDATE, variable, clonedFields, options);
290
+ if (output === false) {
291
+ // $rootScope.$emit('toggle-variable-state', variable, false);
292
+ triggerFn(error);
293
+ return Promise.reject('Call stopped from the event: ' + VARIABLE_CONSTANTS.EVENT.BEFORE_UPDATE);
294
+ }
295
+ inputFields = isObject(output) ? output : clonedFields;
296
+ variable.canUpdate = false;
297
+ if (options.row) {
298
+ rowObject = options.row;
299
+ // For datetime types, convert the value to the format accepted by backend
300
+ forEach(rowObject, function (value, key) {
301
+ var fieldType = LiveVariableUtils.getFieldType(key, variable);
302
+ var fieldValue;
303
+ if (isDateTimeType(fieldType)) {
304
+ fieldValue = formatDate(value, fieldType, variable.dateFormatter);
305
+ rowObject[key] = fieldValue;
306
+ }
307
+ else if (isArray(value) && LiveVariableUtils.isStringType(fieldType)) {
308
+ // Construct ',' separated string if param is not array type but value is an array
309
+ fieldValue = join(value, ',');
310
+ rowObject[key] = fieldValue;
311
+ }
312
+ });
313
+ // Merge inputFields along with dataObj while making Insert/Update/Delete
314
+ forEach(inputFields, function (attrValue, attrName) {
315
+ if ((isDefined(attrValue) && attrValue !== '') && (!isDefined(rowObject[attrName]) || rowObject[attrName] === '')) {
316
+ rowObject[attrName] = attrValue;
317
+ }
318
+ });
319
+ }
320
+ else {
321
+ forEach(inputFields, function (fieldValue, fieldName) {
322
+ var fieldType;
323
+ var primaryKeys = variable.propertiesMap.primaryFields || variable.propertiesMap.primaryKeys;
324
+ if (!isUndefined(fieldValue) && fieldValue !== '') {
325
+ /*For delete action, the inputFields need to be set in the request URL. Hence compositeId is set.
326
+ * For insert action inputFields need to be set in the request data. Hence rowObject is set.
327
+ * For update action, both need to be set.*/
328
+ if (action === 'deleteTableData') {
329
+ compositeId = fieldValue;
330
+ }
331
+ if (action === 'updateTableData') {
332
+ primaryKeys.forEach(function (key) {
333
+ if (fieldName === key) {
334
+ compositeId = fieldValue;
335
+ }
336
+ });
337
+ }
338
+ if (action !== 'deleteTableData' || LiveVariableUtils.isCompositeKey(primaryKey)) {
339
+ fieldType = LiveVariableUtils.getFieldType(fieldName, variable);
340
+ if (isDateTimeType(fieldType)) {
341
+ fieldValue = formatDate(fieldValue, fieldType, variable.dateFormatter);
342
+ }
343
+ else if (isArray(fieldValue) && LiveVariableUtils.isStringType(fieldType)) {
344
+ // Construct ',' separated string if param is not array type but value is an array
345
+ fieldValue = join(fieldValue, ',');
346
+ }
347
+ rowObject[fieldName] = fieldValue;
348
+ }
349
+ // for related entities, clear the blob type fields
350
+ if (isObject(fieldValue) && !isArray(fieldValue)) {
351
+ forEach(fieldValue, function (val, key) {
352
+ if (LiveVariableUtils.getFieldType(fieldName, variable, key) === 'blob') {
353
+ fieldValue[key] = val === null ? val : '';
354
+ }
355
+ });
356
+ }
357
+ }
358
+ });
359
+ }
360
+ switch (action) {
361
+ case 'updateTableData':
362
+ prevData = options.prevData || {};
363
+ /*Construct the "requestData" based on whether the table associated with the live-variable has a composite key or not.*/
364
+ if (LiveVariableUtils.isCompositeKey(primaryKey)) {
365
+ if (LiveVariableUtils.isNoPrimaryKey(primaryKey)) {
366
+ prevCompositeKeysData = prevData || options.rowData || rowObject;
367
+ compositeKeysData = rowObject;
368
+ }
369
+ else {
370
+ primaryKey.forEach(function (key) {
371
+ compositeKeysData[key] = rowObject[key];
372
+ // In case of periodic update for Business temporal fields, passing updated field data.
373
+ if (options.period) {
374
+ prevCompositeKeysData[key] = rowObject[key];
375
+ }
376
+ else {
377
+ prevCompositeKeysData[key] = prevData[key] || (options.rowData && options.rowData[key]) || rowObject[key];
378
+ }
379
+ });
380
+ }
381
+ options.row = compositeKeysData;
382
+ options.compositeKeysData = prevCompositeKeysData;
383
+ }
384
+ else {
385
+ primaryKey.forEach(function (key) {
386
+ if (key.indexOf('.') === -1) {
387
+ id = prevData[key] || (options.rowData && options.rowData[key]) || rowObject[key];
388
+ }
389
+ else {
390
+ columnName = key.split('.');
391
+ id = prevData[columnName[0]][columnName[1]];
392
+ }
393
+ });
394
+ options.id = id;
395
+ options.row = rowObject;
396
+ }
397
+ break;
398
+ case 'deleteTableData':
399
+ /*Construct the "requestData" based on whether the table associated with the live-variable has a composite key or not.*/
400
+ if (LiveVariableUtils.isCompositeKey(primaryKey)) {
401
+ if (LiveVariableUtils.isNoPrimaryKey(primaryKey)) {
402
+ compositeKeysData = rowObject;
403
+ }
404
+ else {
405
+ primaryKey.forEach(function (key) {
406
+ compositeKeysData[key] = rowObject[key];
407
+ });
408
+ }
409
+ options.compositeKeysData = compositeKeysData;
410
+ }
411
+ else if (!isEmpty(rowObject)) {
412
+ primaryKey.forEach(function (key) {
413
+ if (key.indexOf('.') === -1) {
414
+ id = rowObject[key];
415
+ }
416
+ else {
417
+ columnName = key.split('.');
418
+ id = rowObject[columnName[0]][columnName[1]];
419
+ }
420
+ });
421
+ options.id = id;
422
+ }
423
+ break;
424
+ default:
425
+ break;
426
+ }
427
+ // If table has blob column then send multipart data
428
+ if ((action === 'updateTableData' || action === 'insertTableData') && LiveVariableUtils.hasBlob(variable) && isFormDataSupported) {
429
+ if (action === 'updateTableData') {
430
+ action = 'updateMultiPartTableData';
431
+ }
432
+ else {
433
+ action = 'insertMultiPartTableData';
434
+ }
435
+ rowObject = LiveVariableUtils.prepareFormData(variable, rowObject);
436
+ }
437
+ /*Check if "options" have the "compositeKeysData" property.*/
438
+ if (options.compositeKeysData) {
439
+ switch (action) {
440
+ case 'updateTableData':
441
+ action = 'updateCompositeTableData';
442
+ break;
443
+ case 'deleteTableData':
444
+ action = 'deleteCompositeTableData';
445
+ break;
446
+ case 'updateMultiPartTableData':
447
+ action = 'updateMultiPartCompositeTableData';
448
+ break;
449
+ default:
450
+ break;
451
+ }
452
+ compositeId = LiveVariableUtils.getCompositeIDURL(options.compositeKeysData);
453
+ }
454
+ dbName = variable.liveSource;
455
+ /*Set the "data" in the request to "undefined" if there is no data.
456
+ * This handles cases such as "Delete" requests where data should not be passed.*/
457
+ if (isEmpty(rowObject) && action === 'deleteTableData') {
458
+ rowObject = undefined;
459
+ }
460
+ if ((action === 'updateCompositeTableData' || action === 'deleteCompositeTableData') && options.period) {
461
+ // capitalize first character
462
+ action = 'period' + action.charAt(0).toUpperCase() + action.substr(1);
463
+ }
464
+ var dbOperations = {
465
+ 'projectID': projectID,
466
+ 'service': variable._prefabName ? '' : 'services',
467
+ 'dataModelName': dbName,
468
+ 'entityName': variable.type,
469
+ 'id': !isUndefined(options.id) ? encodeURIComponent(options.id) : compositeId,
470
+ 'data': rowObject,
471
+ 'url': variable._prefabName ? ($rootScope.project.deployedUrl + '/prefabs/' + variable._prefabName) : $rootScope.project.deployedUrl
472
+ };
473
+ onCUDerror = function (response, reject) {
474
+ var errMsg = response.error;
475
+ var advancedOptions = _this.prepareCallbackOptions(response);
476
+ // EVENT: ON_RESULT
477
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.RESULT, variable, errMsg, advancedOptions);
478
+ // EVENT: ON_ERROR
479
+ if (!options.skipNotification) {
480
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.ERROR, variable, errMsg, advancedOptions);
481
+ }
482
+ // EVENT: ON_CAN_UPDATE
483
+ variable.canUpdate = true;
484
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.CAN_UPDATE, variable, errMsg, advancedOptions);
485
+ triggerFn(error, errMsg);
486
+ reject(errMsg);
487
+ };
488
+ onCUDsuccess = function (data, resolve) {
489
+ var response = data.body || data.data;
490
+ var advancedOptions = _this.prepareCallbackOptions(data);
491
+ $queue.process(variable);
492
+ /* if error received on making call, call error callback */
493
+ if (response && response.error) {
494
+ // EVENT: ON_RESULT
495
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.RESULT, variable, response, advancedOptions);
496
+ // EVENT: ON_ERROR
497
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.ERROR, variable, response.error, advancedOptions);
498
+ // EVENT: ON_CAN_UPDATE
499
+ variable.canUpdate = true;
500
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.CAN_UPDATE, variable, response.error, advancedOptions);
501
+ triggerFn(error, response.error);
502
+ return Promise.reject(response.error);
503
+ }
504
+ // EVENT: ON_RESULT
505
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.RESULT, variable, response, advancedOptions);
506
+ if (variable.operation !== 'read') {
507
+ // EVENT: ON_PREPARESETDATA
508
+ var newDataSet = initiateCallback(VARIABLE_CONSTANTS.EVENT.PREPARE_SETDATA, variable, response, advancedOptions);
509
+ if (newDataSet) {
510
+ // setting newDataSet as the response to service variable onPrepareSetData
511
+ response = newDataSet;
512
+ }
513
+ variable.dataSet = response;
514
+ }
515
+ // watchers should get triggered before calling onSuccess event.
516
+ // so that any variable/widget depending on this variable's data is updated
517
+ variable.notify(VariableEvents.AFTER_INVOKE, [_this, response]);
518
+ setTimeout(function () {
519
+ // EVENT: ON_SUCCESS
520
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.SUCCESS, variable, response, advancedOptions);
521
+ // EVENT: ON_CAN_UPDATE
522
+ variable.canUpdate = true;
523
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.CAN_UPDATE, variable, response, advancedOptions);
524
+ });
525
+ triggerFn(success, response);
526
+ resolve(response);
527
+ };
528
+ return new Promise(function (resolve, reject) {
529
+ _this.makeCall(variable, action, dbOperations).then(function (data) {
530
+ onCUDsuccess(data, resolve);
531
+ }, function (response) {
532
+ onCUDerror(response, reject);
533
+ });
534
+ });
535
+ };
536
+ LiveVariableManager.prototype.aggregateData = function (deployedUrl, variable, options, success, error) {
537
+ var _this = this;
538
+ var tableOptions, dbOperationOptions, aggregateDataSuccess, aggregateDataError;
539
+ var dbOperation = 'executeAggregateQuery';
540
+ options = options || {};
541
+ options.skipEncode = true;
542
+ if (variable.filterFields) {
543
+ tableOptions = LiveVariableUtils.prepareTableOptions(variable, options);
544
+ options.aggregations.filter = tableOptions.query;
545
+ }
546
+ dbOperationOptions = {
547
+ 'dataModelName': variable.liveSource,
548
+ 'entityName': variable.type,
549
+ 'page': options.page || 1,
550
+ 'size': options.size || variable.maxResults,
551
+ 'sort': options.sort || '',
552
+ 'url': deployedUrl,
553
+ 'data': options.aggregations
554
+ };
555
+ aggregateDataSuccess = function (response, resolve) {
556
+ if (response && response.type) {
557
+ if ((response && response.error) || !response) {
558
+ triggerFn(error, response.error);
559
+ return;
560
+ }
561
+ triggerFn(success, response);
562
+ resolve(response);
563
+ }
564
+ };
565
+ aggregateDataError = function (errorMsg, reject) {
566
+ triggerFn(error, errorMsg);
567
+ reject(errorMsg);
568
+ };
569
+ return new Promise(function (resolve, reject) {
570
+ _this.makeCall(variable, dbOperation, dbOperationOptions).then(function (response) {
571
+ aggregateDataSuccess(response, resolve);
572
+ }, function (err) {
573
+ aggregateDataError(err, reject);
574
+ });
575
+ });
576
+ };
577
+ // *********************************************************** PUBLIC ***********************************************************//
578
+ /**
579
+ * Makes http call for a Live Variable against the configured DB Entity.
580
+ * Gets the paginated records against the entity
581
+ * @param variable
582
+ * @param options
583
+ * @param success
584
+ * @param error
585
+ * @returns {Promise<any>}: will be resolved on successful data fetch
586
+ */
587
+ LiveVariableManager.prototype.listRecords = function (variable, options, success, error) {
588
+ var _this = this;
589
+ options = options || {};
590
+ options.filterFields = options.filterFields || getClonedObject(variable.filterFields);
591
+ return $queue.submit(variable).then(function () {
592
+ _this.notifyInflight(variable, !options.skipToggleState, undefined, options);
593
+ return _this.getEntityData(variable, options, success, error)
594
+ .then(function (response) {
595
+ $queue.process(variable);
596
+ _this.notifyInflight(variable, false, response);
597
+ return Promise.resolve(response);
598
+ }, function (err) {
599
+ $queue.process(variable);
600
+ _this.notifyInflight(variable, false, err);
601
+ return Promise.reject(err);
602
+ });
603
+ }, error);
604
+ };
605
+ /**
606
+ * Makes a POST http call for a Live Variable against the configured DB Entity.
607
+ * Sends a Table record object with the request body
608
+ * the record is inserted into the entity at the backend
609
+ * @param variable
610
+ * @param options
611
+ * @param success
612
+ * @param error
613
+ * @returns {Promise<any>}: will be resolved on successful data fetch
614
+ */
615
+ LiveVariableManager.prototype.insertRecord = function (variable, options, success, error) {
616
+ return this.performCUD('insertTableData', variable, options, success, error);
617
+ };
618
+ /**
619
+ * Makes a PUT http call for a Live Variable against the configured DB Entity.
620
+ * Sends a Table record object with the request body against the primary key of an existing record
621
+ * the record is updated into the entity at the backend
622
+ * @param variable
623
+ * @param options
624
+ * @param success
625
+ * @param error
626
+ * @returns {Promise<any>}: will be resolved on successful data fetch
627
+ */
628
+ LiveVariableManager.prototype.updateRecord = function (variable, options, success, error) {
629
+ return this.performCUD('updateTableData', variable, options, success, error);
630
+ };
631
+ /**
632
+ * Makes a DELETE http call for a Live Variable against the configured DB Entity.
633
+ * Sends the primary key of an existing record
634
+ * the record is deleted from the entity at the backend
635
+ * @param variable
636
+ * @param options
637
+ * @param success
638
+ * @param error
639
+ * @returns {Promise<any>}: will be resolved on successful data fetch
640
+ */
641
+ LiveVariableManager.prototype.deleteRecord = function (variable, options, success, error) {
642
+ return this.performCUD('deleteTableData', variable, options, success, error);
643
+ };
644
+ /**
645
+ * sets the value against passed key on the "inputFields" object in the variable
646
+ * @param variable
647
+ * @param key: can be:
648
+ * - a string e.g. "username"
649
+ * - an object, e.g. {"username": "john", "ssn": "11111"}
650
+ * @param val
651
+ * - if key is string, the value against it (for that data type)
652
+ * - if key is object, not required
653
+ * @param options
654
+ * @returns {any}
655
+ */
656
+ LiveVariableManager.prototype.setInput = function (variable, key, val, options) {
657
+ variable.inputFields = variable.inputFields || {};
658
+ return setInput(variable.inputFields, key, val, options);
659
+ };
660
+ /**
661
+ * sets the value against passed key on the "filterFields" object in the variable
662
+ * @param variable
663
+ * @param key: can be:
664
+ * - a string e.g. "username"
665
+ * - an object, e.g. {"username": "john", "ssn": "11111"}
666
+ * @param val
667
+ * - if key is string, the value against it (for that data type)
668
+ * - if key is object, not required
669
+ * @param options
670
+ * @returns {any}
671
+ */
672
+ LiveVariableManager.prototype.setFilter = function (variable, key, val) {
673
+ var paramObj = {}, targetObj = {};
674
+ if (isObject(key)) {
675
+ paramObj = key;
676
+ }
677
+ else {
678
+ paramObj[key] = val;
679
+ }
680
+ if (!variable.filterExpressions || isEmpty(variable.filterExpressions)) {
681
+ variable.filterExpressions = { 'condition': 'AND', 'rules': [] };
682
+ }
683
+ targetObj = variable.filterExpressions;
684
+ // find the existing criteria if present or else return null. Find the first one and return.
685
+ // If the user wants to set a different object, then he has to use the getCriteria API defined
686
+ // on the dataFilter object passed to the onBeforeListRecords
687
+ function getExistingCriteria(filterField) {
688
+ var existingCriteria = null;
689
+ LiveVariableUtils.traverseFilterExpressions(targetObj, function (filterExpressions, criteria) {
690
+ if (filterField === criteria.target) {
691
+ return existingCriteria = criteria;
692
+ }
693
+ });
694
+ return existingCriteria;
695
+ }
696
+ forEach(paramObj, function (paramVal, paramKey) {
697
+ var existingCriteria = getExistingCriteria(paramKey);
698
+ if (existingCriteria !== null) {
699
+ existingCriteria.value = paramVal;
700
+ }
701
+ else {
702
+ targetObj.rules.push({
703
+ target: paramKey,
704
+ type: '',
705
+ matchMode: '',
706
+ value: paramVal,
707
+ required: false
708
+ });
709
+ }
710
+ });
711
+ return targetObj;
712
+ };
713
+ /**
714
+ * Makes a file download call for a table
715
+ * @param variable
716
+ * @param options
717
+ */
718
+ LiveVariableManager.prototype.download = function (variable, options, successHandler, errorHandler) {
719
+ var _this = this;
720
+ options = options || {};
721
+ var tableOptions, dbOperationOptions, downloadSuccess, downloadError;
722
+ var data = {};
723
+ var dbOperation = 'exportTableData';
724
+ var projectID = $rootScope.project.id || $rootScope.projectName;
725
+ options.data.searchWithQuery = true; // For export, query api is used. So set this flag to true
726
+ options.data.skipEncode = true;
727
+ tableOptions = LiveVariableUtils.prepareTableOptions(variable, options.data, undefined);
728
+ data.query = tableOptions.query ? tableOptions.query : '';
729
+ data.exportSize = options.data.exportSize;
730
+ data.exportType = options.data.exportType;
731
+ data.fields = formatExportExpression(options.data.fields);
732
+ if (options.data.fileName) {
733
+ data.fileName = options.data.fileName;
734
+ }
735
+ dbOperationOptions = {
736
+ 'projectID': projectID,
737
+ 'service': variable.getPrefabName() ? '' : 'services',
738
+ 'dataModelName': variable.liveSource,
739
+ 'entityName': variable.type,
740
+ 'sort': tableOptions.sort,
741
+ 'url': variable.getPrefabName() ? ($rootScope.project.deployedUrl + '/prefabs/' + variable.getPrefabName()) : $rootScope.project.deployedUrl,
742
+ 'data': data,
743
+ 'filter': LiveVariableUtils.getWhereClauseGenerator(variable, options)
744
+ // 'filterMeta' : tableOptions.filter
745
+ };
746
+ downloadSuccess = function (response, resolve) {
747
+ if (response && response.type) {
748
+ window.location.href = response.body.result;
749
+ triggerFn(successHandler, response);
750
+ resolve(response);
751
+ }
752
+ };
753
+ downloadError = function (err, reject) {
754
+ var opt = _this.prepareCallbackOptions(err.details);
755
+ initiateCallback(VARIABLE_CONSTANTS.EVENT.ERROR, variable, err.error, opt);
756
+ triggerFn(errorHandler, err.error);
757
+ reject(err);
758
+ };
759
+ return new Promise(function (resolve, reject) {
760
+ _this.makeCall(variable, dbOperation, dbOperationOptions).then(function (response) {
761
+ downloadSuccess(response, resolve);
762
+ }, function (error) {
763
+ downloadError(error, reject);
764
+ });
765
+ });
766
+ };
767
+ /**
768
+ * gets primary keys against the passed related Table
769
+ * @param variable
770
+ * @param relatedField
771
+ * @returns {any}
772
+ */
773
+ LiveVariableManager.prototype.getRelatedTablePrimaryKeys = function (variable, relatedField) {
774
+ var primaryKeys, result, relatedCols;
775
+ if (!variable.propertiesMap) {
776
+ return;
777
+ }
778
+ result = find(variable.propertiesMap.columns || [], { 'fieldName': relatedField });
779
+ // if related field name passed, get its type from columns inside the current field
780
+ if (result) {
781
+ relatedCols = result.columns;
782
+ primaryKeys = map(filter(relatedCols, 'isPrimaryKey'), 'fieldName');
783
+ if (primaryKeys.length) {
784
+ return primaryKeys;
785
+ }
786
+ if (relatedCols && relatedCols.length) {
787
+ relatedCols = find(relatedCols, { 'isRelated': false });
788
+ return relatedCols && relatedCols.fieldName;
789
+ }
790
+ }
791
+ };
792
+ /**
793
+ * Makes HTTP call to get the data for related entity of a field in an entity
794
+ * @param variable
795
+ * @param columnName
796
+ * @param options
797
+ * @param success
798
+ * @param error
799
+ */
800
+ LiveVariableManager.prototype.getRelatedTableData = function (variable, columnName, options, success, error) {
801
+ var _this = this;
802
+ var projectID = $rootScope.project.id || $rootScope.projectName;
803
+ var relatedTable = find(variable.relatedTables, function (table) { return table.relationName === columnName || table.columnName === columnName; }); // Comparing column name to support the old projects
804
+ var selfRelatedCols = map(filter(variable.relatedTables, function (o) { return o.type === variable.type; }), 'relationName');
805
+ var filterFields = [];
806
+ var orderBy, filterOptions, query, action, dbOperationOptions, getRelatedTableDataSuccess, getRelatedTableDataError;
807
+ forEach(options.filterFields, function (value, key) {
808
+ value.fieldName = key;
809
+ value.type = LiveVariableUtils.getFieldType(columnName, variable, key);
810
+ /**
811
+ * for 'in' mode we are taking the input as comma separated values and for between in ui there are two different fields
812
+ * but these are processed and merged into a single value with comma as separator. For these conditions like 'in' and 'between',
813
+ * for building the query, the function expects the values to be an array
814
+ */
815
+ if (value.filterCondition === DB_CONSTANTS.DATABASE_MATCH_MODES.in.toLowerCase() || value.filterCondition === DB_CONSTANTS.DATABASE_MATCH_MODES.between.toLowerCase()) {
816
+ value.value = value.value.split(',');
817
+ }
818
+ filterFields.push(value);
819
+ });
820
+ filterOptions = LiveVariableUtils.getFilterOptions(variable, filterFields, options);
821
+ query = LiveVariableUtils.getSearchQuery(filterOptions, ' ' + (options.logicalOp || 'AND') + ' ', variable.ignoreCase);
822
+ if (options.filterExpr) {
823
+ var _clonedFields = getClonedObject(isObject(options.filterExpr) ? options.filterExpr : JSON.parse(options.filterExpr));
824
+ LiveVariableUtils.processFilterFields(_clonedFields.rules, variable, options);
825
+ var filterExpQuery = LiveVariableUtils.generateSearchQuery(_clonedFields.rules, _clonedFields.condition, variable.ignoreCase, options.skipEncode);
826
+ if (query !== '') {
827
+ if (filterExpQuery !== '') {
828
+ query = '(' + query + ') AND (' + filterExpQuery + ')';
829
+ }
830
+ }
831
+ else if (filterExpQuery !== '') {
832
+ query = filterExpQuery;
833
+ }
834
+ }
835
+ query = query ? ('q=' + query) : '';
836
+ action = 'searchTableDataWithQuery';
837
+ orderBy = isEmpty(options.orderBy) ? '' : 'sort=' + options.orderBy;
838
+ dbOperationOptions = {
839
+ projectID: projectID,
840
+ service: variable.getPrefabName() ? '' : 'services',
841
+ dataModelName: variable.liveSource,
842
+ entityName: relatedTable ? relatedTable.type : '',
843
+ page: options.page || 1,
844
+ size: options.pagesize || undefined,
845
+ url: variable.getPrefabName() ? ($rootScope.project.deployedUrl + '/prefabs/' + variable.getPrefabName()) : $rootScope.project.deployedUrl,
846
+ data: query || '',
847
+ filter: LiveVariableUtils.getWhereClauseGenerator(variable, options),
848
+ sort: orderBy
849
+ };
850
+ getRelatedTableDataSuccess = function (res, resolve) {
851
+ if (res && (res.type || res.status)) {
852
+ var response = res.body || res.data;
853
+ /*Remove the self related columns from the data. As backend is restricting the self related column to one level, In liveform select, dataset and datavalue object
854
+ * equality does not work. So, removing the self related columns to acheive the quality*/
855
+ var data = map(response.content, function (o) { return omit(o, selfRelatedCols); });
856
+ var pagination = Object.assign({}, response);
857
+ delete pagination.content;
858
+ decodeData(data);
859
+ var result = { data: data, pagination: pagination };
860
+ triggerFn(success, result);
861
+ resolve(result);
862
+ }
863
+ };
864
+ getRelatedTableDataError = function (errMsg, reject) {
865
+ triggerFn(error, errMsg);
866
+ reject(errMsg);
867
+ };
868
+ return new Promise(function (resolve, reject) {
869
+ _this.makeCall(variable, action, dbOperationOptions).then(function (response) {
870
+ getRelatedTableDataSuccess(response, resolve);
871
+ }, function (err) {
872
+ getRelatedTableDataError(err, reject);
873
+ });
874
+ });
875
+ };
876
+ /**
877
+ * Gets the distinct records for an entity
878
+ * @param variable
879
+ * @param options
880
+ * @param success
881
+ * @param error
882
+ */
883
+ LiveVariableManager.prototype.getDistinctDataByFields = function (variable, options, success, error) {
884
+ var _this = this;
885
+ var dbOperation = 'getDistinctDataByFields';
886
+ var projectID = $rootScope.project.id || $rootScope.projectName;
887
+ var requestData = {};
888
+ var sort;
889
+ var tableOptions, dbOperationOptions, getDistinctDataByFieldsSuccess, getDistinctDataByFieldsError;
890
+ options.skipEncode = true;
891
+ options.operation = 'read';
892
+ options = options || {};
893
+ tableOptions = LiveVariableUtils.prepareTableOptions(variable, options);
894
+ if (tableOptions.query) {
895
+ requestData.filter = tableOptions.query;
896
+ }
897
+ requestData.groupByFields = isArray(options.fields) ? options.fields : [options.fields];
898
+ sort = options.sort || requestData.groupByFields[0] + ' asc';
899
+ sort = sort ? 'sort=' + sort : '';
900
+ dbOperationOptions = {
901
+ 'projectID': projectID,
902
+ 'service': variable.getPrefabName() ? '' : 'services',
903
+ 'dataModelName': variable.liveSource,
904
+ 'entityName': options.entityName || variable.type,
905
+ 'page': options.page || 1,
906
+ 'size': options.pagesize,
907
+ 'sort': sort,
908
+ 'data': requestData,
909
+ 'filter': LiveVariableUtils.getWhereClauseGenerator(variable, options),
910
+ 'url': variable.getPrefabName() ? ($rootScope.project.deployedUrl + '/prefabs/' + variable.getPrefabName()) : $rootScope.project.deployedUrl
911
+ };
912
+ getDistinctDataByFieldsSuccess = function (response, resolve) {
913
+ if (response && response.type) {
914
+ if ((response && response.error) || !response) {
915
+ triggerFn(error, response.error);
916
+ return Promise.reject(response.error);
917
+ }
918
+ var result = response.body;
919
+ var pagination = Object.assign({}, response.body);
920
+ delete pagination.content;
921
+ result = { data: result.content, pagination: pagination };
922
+ triggerFn(success, result);
923
+ resolve(result);
924
+ }
925
+ };
926
+ getDistinctDataByFieldsError = function (errorMsg, reject) {
927
+ triggerFn(error, errorMsg);
928
+ reject(errorMsg);
929
+ };
930
+ return new Promise(function (resolve, reject) {
931
+ _this.makeCall(variable, dbOperation, dbOperationOptions).then(function (response) {
932
+ getDistinctDataByFieldsSuccess(response, resolve);
933
+ }, function () {
934
+ getDistinctDataByFieldsError(error, reject);
935
+ });
936
+ });
937
+ };
938
+ /*Function to get the aggregated data based on the fields chosen*/
939
+ LiveVariableManager.prototype.getAggregatedData = function (variable, options, success, error) {
940
+ var deployedURL = appManager.getDeployedURL();
941
+ if (deployedURL) {
942
+ return this.aggregateData(deployedURL, variable, options, success, error);
943
+ }
944
+ };
945
+ LiveVariableManager.prototype.defineFirstLastRecord = function (variable) {
946
+ if (variable.operation === 'read') {
947
+ Object.defineProperty(variable, 'firstRecord', {
948
+ 'configurable': true,
949
+ 'get': function () {
950
+ return get(variable.dataSet, 'data[0]', {});
951
+ }
952
+ });
953
+ Object.defineProperty(variable, 'lastRecord', {
954
+ 'configurable': true,
955
+ 'get': function () {
956
+ var data = get(variable.dataSet, 'data', []);
957
+ return data[data.length - 1];
958
+ }
959
+ });
960
+ }
961
+ };
962
+ LiveVariableManager.prototype.getPrimaryKey = function (variable) {
963
+ return LiveVariableUtils.getPrimaryKey(variable);
964
+ };
965
+ // Returns the search query params.
966
+ LiveVariableManager.prototype.prepareRequestParams = function (options) {
967
+ var requestParams;
968
+ var searchKeys = split(options.searchKey, ','), matchModes = split(options.matchMode, ','), formFields = {};
969
+ forEach(searchKeys, function (colName, index) {
970
+ formFields[colName] = {
971
+ value: options.query,
972
+ logicalOp: 'AND',
973
+ matchMode: matchModes[index] || matchModes[0] || 'startignorecase'
974
+ };
975
+ });
976
+ requestParams = {
977
+ filterFields: formFields,
978
+ page: options.page,
979
+ pagesize: options.limit || options.pagesize,
980
+ skipDataSetUpdate: true, // dont update the actual variable dataset,
981
+ skipToggleState: true, // Dont change the variable toggle state as this is a independent call
982
+ inFlightBehavior: 'executeAll',
983
+ logicalOp: 'OR',
984
+ orderBy: options.orderby ? replace(options.orderby, /:/g, ' ') : ''
985
+ };
986
+ if (options.onBeforeservicecall) {
987
+ options.onBeforeservicecall(formFields);
988
+ }
989
+ return requestParams;
990
+ };
991
+ /**
992
+ * Gets the filtered records based on searchKey
993
+ * @param variable
994
+ * @param options contains the searchKey and queryText
995
+ * @param success
996
+ * @param error
997
+ * @returns {Promise<any>}
998
+ */
999
+ LiveVariableManager.prototype.searchRecords = function (variable, options, success, error) {
1000
+ var requestParams = this.prepareRequestParams(options);
1001
+ return this.listRecords(variable, requestParams, success, error);
1002
+ };
1003
+ /**
1004
+ * used in onBeforeUpdate call - called last in the function - used in old Variables using dataBinding.
1005
+ * This function migrates the old data dataBinding to filterExpressions equivalent format
1006
+ * @param variable
1007
+ * @param inputData
1008
+ * @private
1009
+ */
1010
+ LiveVariableManager.prototype.upgradeInputDataToFilterExpressions = function (variable, response, inputData) {
1011
+ if (isObject(response)) {
1012
+ inputData = response;
1013
+ inputData.condition = 'AND';
1014
+ inputData.rules = [];
1015
+ }
1016
+ /**
1017
+ * if the user deletes a particular criteria, we need to remove this form our data aswell.
1018
+ * so we are keeping a copy of it and the emptying the existing object and now fill it with the
1019
+ * user set criteria. If its just modified, change the data and push it tohe rules or else just add a new criteria
1020
+ */
1021
+ var clonedRules = cloneDeep(inputData.rules);
1022
+ inputData.rules = [];
1023
+ forEach(inputData, function (valueObj, key) {
1024
+ if (key !== 'condition' && key !== 'rules') {
1025
+ var filteredObj = find(clonedRules, function (o) { return o.target === key; });
1026
+ // if the key is found update the value, else create a new rule obj and add it to the existing rules
1027
+ if (filteredObj) {
1028
+ filteredObj.value = valueObj.value;
1029
+ filteredObj.matchMode = valueObj.matchMode || valueObj.filterCondition || filteredObj.matchMode || '';
1030
+ inputData.rules.push(filteredObj);
1031
+ }
1032
+ else {
1033
+ inputData.rules.push({
1034
+ 'target': key,
1035
+ 'type': '',
1036
+ 'matchMode': valueObj.matchMode || valueObj.filterCondition || '',
1037
+ 'value': valueObj.value,
1038
+ 'required': false
1039
+ });
1040
+ }
1041
+ delete inputData[key];
1042
+ }
1043
+ });
1044
+ return inputData;
1045
+ };
1046
+ /**
1047
+ * used in onBeforeUpdate call - called first in the function - used in old Variables using dataBinding.
1048
+ * This function migrates the filterExpressions object to flat map structure
1049
+ * @param variable
1050
+ * @param inputData
1051
+ * @private
1052
+ */
1053
+ LiveVariableManager.prototype.downgradeFilterExpressionsToInputData = function (variable, inputData) {
1054
+ if (inputData.hasOwnProperty('getFilterFields')) {
1055
+ inputData = inputData.getFilterFields();
1056
+ }
1057
+ forEach(inputData.rules, function (ruleObj) {
1058
+ if (!isNil(ruleObj.target) && ruleObj.target !== '') {
1059
+ inputData[ruleObj.target] = {
1060
+ 'value': ruleObj.value,
1061
+ 'matchMode': ruleObj.matchMode
1062
+ };
1063
+ }
1064
+ });
1065
+ return inputData;
1066
+ };
1067
+ LiveVariableManager.prototype.cancel = function (variable, options) {
1068
+ if ($queue.requestsQueue.has(variable) && variable._observable) {
1069
+ variable._observable.unsubscribe();
1070
+ $queue.process(variable);
1071
+ // notify inflight variable
1072
+ this.notifyInflight(variable, false);
1073
+ }
1074
+ };
1075
+ return LiveVariableManager;
1076
+ }(BaseVariableManager));
1077
+ export { LiveVariableManager };
1078
+ //# sourceMappingURL=live-variable.manager.js.map