@easyquery/core 7.2.3-rc03 → 7.2.4-beta03

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 (140) hide show
  1. package/dist/bundles/easyquery.core.js +9353 -9335
  2. package/dist/bundles/easyquery.core.js.map +1 -1
  3. package/dist/bundles/easyquery.core.min.js +1 -1
  4. package/dist/bundles/easyquery.core.min.js.map +1 -1
  5. package/dist/lib/common/eq_services.d.ts +56 -56
  6. package/dist/lib/common/eq_services.js +159 -159
  7. package/dist/lib/common/query_param.d.ts +25 -25
  8. package/dist/lib/common/query_param.js +1 -0
  9. package/dist/lib/common/tree.d.ts +10 -10
  10. package/dist/lib/common/tree.js +57 -57
  11. package/dist/lib/data/eq_aggr_container.d.ts +24 -24
  12. package/dist/lib/data/eq_aggr_container.js +108 -108
  13. package/dist/lib/data/eq_aggr_container.js.map +1 -1
  14. package/dist/lib/data/eq_data_loader.d.ts +8 -8
  15. package/dist/lib/data/eq_data_loader.js +49 -49
  16. package/dist/lib/data/eq_data_loader.js.map +1 -1
  17. package/dist/lib/data/google_data_converter.d.ts +82 -82
  18. package/dist/lib/data/google_data_converter.js +173 -173
  19. package/dist/lib/data/google_data_converter.js.map +1 -1
  20. package/dist/lib/dm/aggr_function.d.ts +27 -27
  21. package/dist/lib/dm/aggr_function.js +42 -42
  22. package/dist/lib/dm/data_model.d.ts +330 -330
  23. package/dist/lib/dm/data_model.js +934 -932
  24. package/dist/lib/dm/data_model.js.map +1 -1
  25. package/dist/lib/dm/dto/af_data.d.ts +16 -16
  26. package/dist/lib/dm/dto/af_data.js +1 -0
  27. package/dist/lib/dm/dto/dm_data.d.ts +34 -34
  28. package/dist/lib/dm/dto/dm_data.js +1 -0
  29. package/dist/lib/dm/dto/entity_data.d.ts +37 -37
  30. package/dist/lib/dm/dto/entity_data.js +1 -0
  31. package/dist/lib/dm/dto/operator_data.d.ts +44 -44
  32. package/dist/lib/dm/dto/operator_data.js +1 -0
  33. package/dist/lib/dm/dto/ve_data.d.ts +10 -10
  34. package/dist/lib/dm/dto/ve_data.js +1 -0
  35. package/dist/lib/dm/entity.d.ts +71 -71
  36. package/dist/lib/dm/entity.js +90 -88
  37. package/dist/lib/dm/entity.js.map +1 -1
  38. package/dist/lib/dm/link.d.ts +7 -7
  39. package/dist/lib/dm/link.js +1 -0
  40. package/dist/lib/dm/operator.d.ts +80 -80
  41. package/dist/lib/dm/operator.js +93 -93
  42. package/dist/lib/dm/value_editor.d.ts +16 -16
  43. package/dist/lib/dm/value_editor.js +43 -41
  44. package/dist/lib/dm/value_editor.js.map +1 -1
  45. package/dist/lib/eqs/eqs_data_fetcher.d.ts +7 -7
  46. package/dist/lib/eqs/eqs_data_fetcher.js +36 -36
  47. package/dist/lib/eqs/eqs_exporter.d.ts +10 -10
  48. package/dist/lib/eqs/eqs_exporter.js +57 -54
  49. package/dist/lib/eqs/eqs_exporter.js.map +1 -1
  50. package/dist/lib/eqs/eqs_model_loader.d.ts +7 -7
  51. package/dist/lib/eqs/eqs_model_loader.js +42 -40
  52. package/dist/lib/eqs/eqs_model_loader.js.map +1 -1
  53. package/dist/lib/eqs/eqs_query_file_loader.d.ts +9 -9
  54. package/dist/lib/eqs/eqs_query_file_loader.js +54 -54
  55. package/dist/lib/eqs/eqs_query_file_loader.js.map +1 -1
  56. package/dist/lib/eqs/eqs_query_synchronizer.d.ts +7 -7
  57. package/dist/lib/eqs/eqs_query_synchronizer.js +23 -23
  58. package/dist/lib/eqs/eqs_value_list_resolver.d.ts +7 -7
  59. package/dist/lib/eqs/eqs_value_list_resolver.js +28 -28
  60. package/dist/lib/export/exporter.d.ts +16 -16
  61. package/dist/lib/export/exporter.js +1 -0
  62. package/dist/lib/i18n/text_resources.d.ts +1 -1
  63. package/dist/lib/i18n/text_resources.js +26 -26
  64. package/dist/lib/i18n/text_resources.js.map +1 -1
  65. package/dist/lib/main/action.d.ts +13 -13
  66. package/dist/lib/main/action.js +5 -5
  67. package/dist/lib/main/context.d.ts +342 -342
  68. package/dist/lib/main/context.js +1439 -1438
  69. package/dist/lib/main/context.js.map +1 -1
  70. package/dist/lib/main/context_options.d.ts +145 -145
  71. package/dist/lib/main/context_options.js +1 -0
  72. package/dist/lib/main/data_fetcher.d.ts +46 -46
  73. package/dist/lib/main/data_fetcher.js +1 -0
  74. package/dist/lib/main/eq_actions.d.ts +14 -14
  75. package/dist/lib/main/eq_actions.js +15 -15
  76. package/dist/lib/main/list_cache.d.ts +8 -8
  77. package/dist/lib/main/list_cache.js +1 -0
  78. package/dist/lib/main/model_loader.d.ts +21 -21
  79. package/dist/lib/main/model_loader.js +32 -32
  80. package/dist/lib/main/model_storage.d.ts +13 -13
  81. package/dist/lib/main/model_storage.js +17 -17
  82. package/dist/lib/main/query_file_loader.d.ts +15 -15
  83. package/dist/lib/main/query_file_loader.js +1 -0
  84. package/dist/lib/main/query_storage.d.ts +58 -58
  85. package/dist/lib/main/query_storage.js +124 -124
  86. package/dist/lib/main/query_synchronizer.d.ts +9 -9
  87. package/dist/lib/main/query_synchronizer.js +1 -0
  88. package/dist/lib/main/value_list_resolver.d.ts +18 -18
  89. package/dist/lib/main/value_list_resolver.js +1 -0
  90. package/dist/lib/main/widget.d.ts +74 -74
  91. package/dist/lib/main/widget.js +101 -101
  92. package/dist/lib/public_api.d.ts +58 -58
  93. package/dist/lib/public_api.js +59 -42
  94. package/dist/lib/public_api.js.map +1 -1
  95. package/dist/lib/query/condition.d.ts +97 -97
  96. package/dist/lib/query/condition.js +331 -331
  97. package/dist/lib/query/descriptors.d.ts +36 -36
  98. package/dist/lib/query/descriptors.js +1 -0
  99. package/dist/lib/query/dto/condition_data.d.ts +38 -38
  100. package/dist/lib/query/dto/condition_data.js +1 -0
  101. package/dist/lib/query/dto/expression_data.d.ts +32 -32
  102. package/dist/lib/query/dto/expression_data.js +1 -0
  103. package/dist/lib/query/dto/query_column_data.d.ts +28 -28
  104. package/dist/lib/query/dto/query_column_data.js +1 -0
  105. package/dist/lib/query/dto/query_data.d.ts +27 -27
  106. package/dist/lib/query/dto/query_data.js +1 -0
  107. package/dist/lib/query/expression.d.ts +69 -69
  108. package/dist/lib/query/expression.js +202 -202
  109. package/dist/lib/query/query.d.ts +410 -410
  110. package/dist/lib/query/query.js +1393 -1391
  111. package/dist/lib/query/query.js.map +1 -1
  112. package/dist/lib/query/query_column.d.ts +70 -70
  113. package/dist/lib/query/query_column.js +157 -157
  114. package/dist/lib/query/query_events.d.ts +29 -29
  115. package/dist/lib/query/query_events.js +19 -19
  116. package/dist/lib/types/cond_part.d.ts +6 -6
  117. package/dist/lib/types/cond_part.js +7 -7
  118. package/dist/lib/types/cond_tag.d.ts +12 -12
  119. package/dist/lib/types/cond_tag.js +13 -13
  120. package/dist/lib/types/data_kind.d.ts +15 -15
  121. package/dist/lib/types/data_kind.js +16 -16
  122. package/dist/lib/types/eq_editor_tag.d.ts +17 -17
  123. package/dist/lib/types/eq_editor_tag.js +20 -20
  124. package/dist/lib/types/expr_tag.d.ts +19 -19
  125. package/dist/lib/types/expr_tag.js +20 -20
  126. package/dist/lib/types/link_type.d.ts +17 -17
  127. package/dist/lib/types/link_type.js +18 -18
  128. package/dist/lib/types/widget_group.d.ts +17 -17
  129. package/dist/lib/types/widget_group.js +18 -18
  130. package/dist/lib/utils/constants.d.ts +36 -36
  131. package/dist/lib/utils/constants.js +50 -50
  132. package/dist/lib/utils/format_parser.d.ts +40 -40
  133. package/dist/lib/utils/format_parser.js +87 -87
  134. package/dist/lib/utils/utils.d.ts +34 -34
  135. package/dist/lib/utils/utils.js +102 -102
  136. package/dist/lib/utils/version_info.d.ts +9 -9
  137. package/dist/lib/utils/version_info.js +12 -12
  138. package/dist/lib/utils/version_info.js.map +1 -1
  139. package/package.json +16 -16
  140. package/webpack.config.js +6 -5
@@ -1,1439 +1,1440 @@
1
- var __assign = (this && this.__assign) || function () {
2
- __assign = Object.assign || function(t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
- t[p] = s[p];
7
- }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
11
- };
12
- import { EasyDataTable, EventEmitter, utils as dataUtils } from '@easydata/core';
13
- import { i18n } from '@easydata/core';
14
- import { EqServiceProvider } from '../common/eq_services';
15
- import { QueryChangePart } from '../query/query_events';
16
- import { EqActionResult } from './action';
17
- import { WidgetGroup } from '../types/widget_group';
18
- import { equtils } from '../utils/utils';
19
- import { EqAction } from './eq_actions';
20
- import { EqServerExporter } from '../eqs/eqs_exporter';
21
- import { EasyQueryDataLoader } from '../data/eq_data_loader';
22
- /**
23
- * Encapsulates all information about EasyQuery components on some webpage
24
- * and provides some basic operation over those components
25
- * Each context includes the following main components:
26
- * - one data model,
27
- * - one query,
28
- * - one result set
29
- * - several UI widgets.
30
- */
31
- var EqContext = /** @class */ (function () {
32
- function EqContext() {
33
- var _this = this;
34
- this.servicesInitialized = false;
35
- this.internalListCache = {};
36
- this.loadModelOnStart = true;
37
- this.loadQueryOnStart = false;
38
- this.useStoredQueryOnFetch = false;
39
- this.debugMode = false;
40
- this._backendInfo = {
41
- type: 'EQN-ANC',
42
- subType: 'asp-net-core-razor'
43
- };
44
- //----------- endpoint processing functions --------------
45
- this.endpointVarsRegex = /\{.*?\}/g;
46
- this.elasticPaging = false;
47
- this._predefinedListRequestHandlers = {
48
- '_DSDE': function (params, onResult) {
49
- var data = _this.getModel().getAllDateMacros()
50
- .map(function (macroId) {
51
- return { id: '${{' + macroId + '}}', text: i18n.getText(macroId) };
52
- });
53
- onResult(data);
54
- return true;
55
- },
56
- '_DSTE': function (params, onResult) {
57
- var data = _this.getModel().getAllTimeMacros()
58
- .map(function (macroId) {
59
- return { id: '${{' + macroId + '}}', text: i18n.getText(macroId) };
60
- });
61
- onResult(data);
62
- return true;
63
- }
64
- };
65
- this._listRequestHandler = function (options, onResult) {
66
- if (options == null || !options.listName)
67
- return;
68
- var query = _this.getQuery();
69
- var params = dataUtils.assign({ listName: options.listName }, options.editorParams);
70
- var reqParams = {};
71
- var attrPattern = /@{{(.+?)}}/;
72
- for (var prop in params) {
73
- if (!params[prop])
74
- continue;
75
- var match = params[prop].match(attrPattern);
76
- if (match) {
77
- var paramValue = query.getOneValueForAttr(match[1]);
78
- if (!paramValue) {
79
- paramValue = '';
80
- }
81
- reqParams[prop] = params[prop].replace(attrPattern, paramValue);
82
- }
83
- }
84
- var requestParams = {
85
- listName: reqParams.listName,
86
- editorId: options.editorId,
87
- queryParams: reqParams
88
- };
89
- var list = _this.getListFromCache(options);
90
- if (list && list.length > 0) {
91
- onResult(list);
92
- return;
93
- }
94
- var processed = false;
95
- var predefinedHandler = _this._predefinedListRequestHandlers[options.editorId];
96
- if (predefinedHandler) {
97
- processed = predefinedHandler(options, onResult);
98
- }
99
- if (!processed && _this.clientListRequestHandler) {
100
- processed = _this.clientListRequestHandler(options, onResult);
101
- }
102
- if (!processed) {
103
- _this.loadValueList({
104
- params: requestParams,
105
- success: function (data) {
106
- if (data) {
107
- _this.addListToCache(options, data);
108
- }
109
- onResult(data);
110
- },
111
- error: function (message) {
112
- onResult(null);
113
- }
114
- });
115
- }
116
- };
117
- this.baseEndpoint = 'api/easyquery';
118
- this.eqServices = new EqServiceProvider(this);
119
- this.widgets = new Array();
120
- this.eventEmitter = new EventEmitter(this);
121
- this.exporters = new Map();
122
- this.endpoints = new Map();
123
- this.dataLoader = new EasyQueryDataLoader(this);
124
- this.resultTable = new EasyDataTable({
125
- loader: this.dataLoader,
126
- onUpdate: this.onResultTableUpdate.bind(this)
127
- });
128
- this.resultTable.id = 'ResultTable';
129
- this.errorHandlerId = this.addEventListener('error', function (context, status) {
130
- status.result = EqActionResult.Error;
131
- var msgTitle = status.action ? status.action + ' error' : 'Error';
132
- var msgText = status.text ? status.text : '';
133
- if (status.sourceError && status.sourceError.message !== msgText) {
134
- msgText += '\n' + status.sourceError;
135
- }
136
- console.error(msgTitle + ': ' + msgText);
137
- });
138
- }
139
- EqContext.prototype.getServices = function () {
140
- return this.eqServices;
141
- };
142
- EqContext.prototype.registerExporter = function (format, resolver) {
143
- this.exporters.set(format, resolver);
144
- };
145
- EqContext.prototype.registerServerExporter = function (format, responseType) {
146
- this.registerExporter(format, function (context) {
147
- var exporter = new EqServerExporter(context);
148
- exporter.setFormat(format, responseType);
149
- return exporter;
150
- });
151
- };
152
- EqContext.prototype.getExporter = function (format) {
153
- var resolver = this.exporters.get(format);
154
- if (resolver) {
155
- return resolver(this);
156
- }
157
- return null;
158
- };
159
- EqContext.prototype.getExportFormats = function () {
160
- return Array.from(this.exporters.keys());
161
- };
162
- EqContext.prototype.addDefaultExporters = function () {
163
- this.registerServerExporter('csv', '');
164
- this.registerServerExporter('excel-html', '');
165
- };
166
- EqContext.prototype.resolveEndpoint = function (endpointKey, options) {
167
- options = options || {};
168
- var result = this.endpoints.get(endpointKey);
169
- if (!result) {
170
- throw endpointKey + ' endpoint is not defined';
171
- }
172
- var matches = result.match(this.endpointVarsRegex);
173
- if (matches) {
174
- for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {
175
- var match = matches_1[_i];
176
- var opt = match.substring(1, match.length - 1);
177
- var optVal = options[opt];
178
- if (!optVal) {
179
- if (opt == 'modelId') {
180
- optVal = this.getModel().getId();
181
- }
182
- else if (opt == 'queryId') {
183
- optVal = this.getQuery().getId();
184
- }
185
- else {
186
- throw "Parameter [" + opt + "] is not defined";
187
- }
188
- }
189
- result = result.replace(match, optVal);
190
- }
191
- }
192
- return result;
193
- };
194
- EqContext.prototype.setEndpoint = function (key, value) {
195
- this.endpoints.set(key, value);
196
- };
197
- EqContext.prototype.setEnpointIfNotExist = function (key, value) {
198
- if (!this.endpoints.has(key))
199
- this.endpoints.set(key, value);
200
- };
201
- EqContext.prototype.setDefaultEndpoints = function (endpointBase) {
202
- this.setEnpointIfNotExist('GetModel', equtils.combinePath(endpointBase, 'models/{modelId}'));
203
- this.setEnpointIfNotExist('GetQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries/{queryId}'));
204
- this.setEnpointIfNotExist('SaveQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries/{queryId}'));
205
- this.setEnpointIfNotExist('SyncQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries/{queryId}/sync'));
206
- this.setEnpointIfNotExist('NewQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries'));
207
- this.setEnpointIfNotExist('RemoveQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries/{queryId}'));
208
- this.setEnpointIfNotExist('GetQueryList', equtils.combinePath(endpointBase, 'models/{modelId}/queries'));
209
- this.setEnpointIfNotExist('FetchData', equtils.combinePath(endpointBase, 'models/{modelId}/fetch'));
210
- this.setEnpointIfNotExist('GetValueList', equtils.combinePath(endpointBase, 'models/{modelId}/valuelists/{listId}'));
211
- this.setEnpointIfNotExist('ExportResult', equtils.combinePath(endpointBase, 'models/{modelId}/export/{format}'));
212
- this.setEnpointIfNotExist('GetQueryFile', equtils.combinePath(endpointBase, 'models/{modelId}/getqueryfile/{format}'));
213
- this.setEnpointIfNotExist('UploadQueryFile', equtils.combinePath(endpointBase, 'models/{modelId}/uploadqueryfile'));
214
- };
215
- EqContext.prototype.initStart = function () {
216
- this.servicesInitialized = true;
217
- };
218
- /**
219
- * Initializes the context
220
- * @param options
221
- */
222
- EqContext.prototype.init = function (options) {
223
- var _this = this;
224
- if (!this.servicesInitialized)
225
- this.initStart();
226
- options = options || {};
227
- if (typeof (options.debugMode) !== 'undefined') {
228
- this.debugMode = options.debugMode;
229
- }
230
- if (typeof (options.chunkSize) !== 'undefined') {
231
- this.resultTable.chunkSize = options.chunkSize;
232
- }
233
- if (typeof (options.elasticPaging) !== 'undefined') {
234
- this.elasticPaging = options.elasticPaging;
235
- }
236
- if (options.listCache) {
237
- this.setExternalListCache(options.listCache);
238
- }
239
- if (options.locale) {
240
- i18n.setCurrentLocale(options.locale);
241
- }
242
- if (options.localeSettings) {
243
- i18n.updateLocaleSettings(options.localeSettings);
244
- }
245
- if (options.endpoint) {
246
- this.baseEndpoint = options.endpoint;
247
- console.warn('The `endpoint` option is deprecated.\n'
248
- + 'Please use `context.useEndpoint(endpointURL)` function instead.');
249
- }
250
- this.setDefaultEndpoints(this.baseEndpoint);
251
- if (options.modelStorageResolver) {
252
- var eqServices = this.getServices();
253
- eqServices.registerModelStorageResolver(options.modelStorageResolver);
254
- }
255
- this.loadQueryOnStart = false;
256
- if (options.loadQueryOnStart) {
257
- this.loadQueryOnStart = options.loadQueryOnStart;
258
- }
259
- this.loadModelOnStart = true;
260
- if (typeof options.loadModelOnStart !== 'undefined') {
261
- this.loadModelOnStart = options.loadModelOnStart;
262
- }
263
- if (options.handlers) {
264
- if (options.handlers.onInit) {
265
- this.addEventListener('ready', options.handlers.onInit);
266
- }
267
- if (options.handlers.afterLoadModel) {
268
- this.addEventListener('loadModel', options.handlers.afterLoadModel);
269
- }
270
- if (options.handlers.afterLoadQuery) {
271
- this.addEventListener('loadQuery', options.handlers.afterLoadQuery);
272
- }
273
- if (options.handlers.afterSyncQuery) {
274
- this.addEventListener('syncQuery', options.handlers.afterSyncQuery);
275
- }
276
- if (options.handlers.afterFetchData) {
277
- this.addEventListener('fetchData', options.handlers.afterFetchData);
278
- }
279
- if (options.handlers.afterExportResult) {
280
- this.addEventListener('exportResult', options.handlers.afterExportResult);
281
- }
282
- if (options.handlers.onProcessStart) {
283
- this.addEventListener('processStart', options.handlers.onProcessStart);
284
- }
285
- if (options.handlers.onProcessEnd) {
286
- this.addEventListener('processEnd', options.handlers.onProcessEnd);
287
- }
288
- if (options.handlers.onError) {
289
- this.removeEventListener('error', this.errorHandlerId);
290
- this.addEventListener('error', options.handlers.onError);
291
- }
292
- if (options.handlers.onListRequest) {
293
- this.clientListRequestHandler = options.handlers.onListRequest;
294
- }
295
- if (options.handlers.beforeLoadModel) {
296
- this.beforeLoadModel = options.handlers.beforeLoadModel;
297
- }
298
- if (options.handlers.beforeLoadQuery) {
299
- this.beforeLoadQuery = options.handlers.beforeLoadQuery;
300
- }
301
- if (options.handlers.beforeSyncQuery) {
302
- this.beforeSyncQuery = options.handlers.beforeSyncQuery;
303
- }
304
- if (options.handlers.beforeFetchData) {
305
- this.beforeFetchData = options.handlers.beforeFetchData;
306
- }
307
- if (options.handlers.beforeExportResult) {
308
- this.beforeExportResult = options.handlers.beforeExportResult;
309
- }
310
- }
311
- this.initialQuery = options.initialQuery;
312
- this.defaultQueryId = options.defaultQueryId || '';
313
- this.defaultModelId = options.defaultModelId || '__default';
314
- var modelLoader = this.eqServices.getModelLoader();
315
- modelLoader.init(options);
316
- var queryStorage = this.eqServices.getQueryStorage();
317
- queryStorage.init(options);
318
- if (options.useDefaultExporters !== false) {
319
- this.addDefaultExporters();
320
- }
321
- if (options.serverExporters) {
322
- for (var _i = 0, _a = options.serverExporters; _i < _a.length; _i++) {
323
- var format = _a[_i];
324
- var responseType = format == 'csv' || format == 'excel-html' ? '' : 'arraybuffer';
325
- this.registerServerExporter(format, responseType);
326
- }
327
- }
328
- var query = this.getQuery();
329
- if (options.defaultQueryId) {
330
- query.setId(options.defaultQueryId);
331
- }
332
- //init widgets
333
- this.widgets.forEach(function (widget) {
334
- var widgetOptions = {};
335
- if (options.widgets && options.widgets[widget.getWidgetType()]) {
336
- widgetOptions = options.widgets[widget.getWidgetType()];
337
- }
338
- widget.init(_this, widgetOptions);
339
- });
340
- if (this.loadModelOnStart) {
341
- this.loadDefaultModel();
342
- }
343
- else {
344
- this.fireEvent('ready');
345
- }
346
- };
347
- Object.defineProperty(EqContext.prototype, "backendInfo", {
348
- get: function () {
349
- return this._backendInfo;
350
- },
351
- enumerable: true,
352
- configurable: true
353
- });
354
- /**
355
- * Sets endpoint for all EasyQuery actions. Should be called before `init` and
356
- * `useEnterprise` methods
357
- * @param endpoint
358
- * @example
359
- * ```
360
- * view.getContext()
361
- * .useEndpoint('/api/easyquery')
362
- * .useEnterprise(function () {
363
- * view.init();
364
- * });
365
- * ```
366
- */
367
- EqContext.prototype.useEndpoint = function (endpoint) {
368
- this.baseEndpoint = endpoint;
369
- return this;
370
- };
371
- /**
372
- * Allows to specify the type of backend service.
373
- *
374
- * @param backendInfo - the structure that contains information about the app used on the backend
375
- * Possible values for `ptag` property: 'EQN-ANC' - ASP.NET Core or 'EQN-ASP' - for ASP.NET 4 backend
376
- */
377
- EqContext.prototype.useBackend = function (backendInfo) {
378
- if (backendInfo.type) {
379
- this._backendInfo.type = backendInfo.type;
380
- }
381
- if (backendInfo.subType) {
382
- this._backendInfo.subType = backendInfo.subType;
383
- }
384
- else {
385
- switch (this._backendInfo.type) {
386
- case 'EQN-ANC':
387
- this._backendInfo.subType = 'asp-net-core-razor';
388
- break;
389
- case 'EQN-ASP':
390
- this._backendInfo.subType = 'asp-net-4-mvc';
391
- break;
392
- default:
393
- this._backendInfo.subType = 'other';
394
- break;
395
- }
396
- }
397
- return this;
398
- };
399
- /**
400
- * Add a new widget to the context.
401
- * After that the widget will start to receive messages from other context components.
402
- * @param widget
403
- */
404
- EqContext.prototype.addWidget = function (widget) {
405
- this.widgets.push(widget);
406
- };
407
- /**
408
- * Returns all widgets with current type.
409
- * @param widgetType The widget type
410
- */
411
- EqContext.prototype.getAllWidgetsByType = function (widgetType) {
412
- return this.widgets
413
- .filter(function (widget) { return widget.getWidgetType() === widgetType; });
414
- };
415
- /**
416
- * Returns first registerd widget with current type
417
- * @param widgetType The widget type
418
- */
419
- EqContext.prototype.getWidgetByType = function (widgetType) {
420
- var widgets = this.getAllWidgetsByType(widgetType);
421
- return widgets.length > 0 ? widgets[0] : null;
422
- };
423
- /**
424
- * This method is called automatically when some change was made either in context's data model or query
425
- * @param groups
426
- */
427
- EqContext.prototype.refreshWidgets = function (groups) {
428
- if (groups === void 0) { groups = WidgetGroup.All; }
429
- this.widgets.forEach(function (widget) {
430
- if (widget.belongsToGroup(groups)) {
431
- widget.refresh();
432
- }
433
- });
434
- };
435
- /**
436
- * Register a new handler for 'query changed' event
437
- * @param callback
438
- */
439
- EqContext.prototype.addQueryChangedCallback = function (callback) {
440
- this.getQuery().addChangedCallback(callback);
441
- };
442
- /**
443
- * Removes the function from the list of registerd handlers for 'query changed' event
444
- * @param callback
445
- */
446
- EqContext.prototype.removeQueryChangedCallback = function (callback) {
447
- this.getQuery().removeChangedCallback(callback);
448
- };
449
- /**
450
- * Creates a new query object using the current instance of EqServices
451
- */
452
- EqContext.prototype.createQuery = function () {
453
- return this.eqServices.createQuery();
454
- };
455
- /**
456
- * Gets the current query
457
- */
458
- EqContext.prototype.getQuery = function () {
459
- if (!this.query) {
460
- if (!this.servicesInitialized) {
461
- throw new Error("Can't create query until the context is initialized");
462
- }
463
- this.query = this.createQuery();
464
- }
465
- return this.query;
466
- };
467
- /**
468
- * Gets the current data model
469
- */
470
- EqContext.prototype.getModel = function () {
471
- if (!this.dataModel) {
472
- this.dataModel = this.eqServices.createDataModel();
473
- }
474
- return this.dataModel;
475
- };
476
- /**
477
- * Sets the content of the current data model
478
- */
479
- EqContext.prototype.loadModelFromData = function (modelPlainData) {
480
- this.getQuery().loadModelData(modelPlainData);
481
- this.dataModel = this.getQuery().getModel();
482
- };
483
- /**
484
- * Sets the ID of the default model
485
- * @param modelId
486
- */
487
- EqContext.prototype.setDefaultModelId = function (modelId) {
488
- this.defaultModelId = modelId;
489
- };
490
- /**
491
- * Notifies context components about starting of some long process (e.g. model loading)
492
- * This method raises onProcessStart event in the context and all its widgets
493
- * @param message
494
- * @param groups
495
- */
496
- EqContext.prototype.startProcess = function (message, groups) {
497
- this.eventEmitter.fire('processStart', message);
498
- this.widgets.forEach(function (widget) {
499
- if (widget.belongsToGroup(groups)) {
500
- widget.onProcessStart();
501
- }
502
- });
503
- };
504
- /**
505
- * Notifies all context components about the finishing of some long process
506
- * @param status
507
- * @param groups
508
- */
509
- EqContext.prototype.endProcess = function (status, groups) {
510
- this.eventEmitter.fire('processEnd', status);
511
- if (status.result === EqActionResult.Error) {
512
- this.throwError(status);
513
- }
514
- this.widgets.forEach(function (widget) {
515
- if (widget.belongsToGroup(groups)) {
516
- widget.onProcessEnd();
517
- }
518
- });
519
- };
520
- /**
521
- * Throws the error passed in the function parameter.
522
- * If onError event handler is defined - we call that method.
523
- * Otherwise - just place the error message to the browser console.
524
- * @param error
525
- */
526
- EqContext.prototype.throwError = function (status) {
527
- status.result = EqActionResult.Error;
528
- this.eventEmitter.fire('error', status);
529
- };
530
- /**
531
- * If `defaultModelId` property is define - this method calls `loadModel` function in the broker
532
- * to load the model with such ID.
533
- */
534
- EqContext.prototype.loadDefaultModel = function () {
535
- var _this = this;
536
- this.loadModel({
537
- modelId: this.defaultModelId,
538
- silent: true,
539
- success: function () {
540
- _this.refreshWidgets(WidgetGroup.Model);
541
- var query = _this.getQuery();
542
- _this.fireEvent('initialModelLoad');
543
- if (_this.initialQuery) {
544
- query.loadFromData(_this.initialQuery, {
545
- changeStatus: false
546
- });
547
- }
548
- if (_this.loadQueryOnStart) {
549
- _this.loadQuery({
550
- queryId: _this.defaultQueryId,
551
- modelId: _this.defaultModelId,
552
- success: function () {
553
- _this.refreshWidgets(WidgetGroup.Query);
554
- //if we load query on start - then we should call 'ready' event only after its successful loading
555
- _this.fireEvent('ready');
556
- }
557
- });
558
- }
559
- else {
560
- _this.refreshWidgets(WidgetGroup.Query);
561
- _this.fireEvent('ready');
562
- }
563
- }
564
- });
565
- };
566
- /**
567
- * Clears the content of the current query
568
- */
569
- EqContext.prototype.clearQuery = function () {
570
- var query = this.getQuery();
571
- query.clear();
572
- query.fireChangedEvent({
573
- part: QueryChangePart.All
574
- });
575
- };
576
- /**
577
- * Clears all query results (the data set and the statement, if any)
578
- */
579
- EqContext.prototype.clearResult = function () {
580
- this.resultTable.clear(); // do not set resultTable to null. Just clear
581
- this.resultStatement = null;
582
- this.resultContent = null;
583
- };
584
- /**
585
- * Sets the external 'list cache' provider - an object which implements `ExternalListCache` inteface
586
- * @param cache
587
- */
588
- EqContext.prototype.setExternalListCache = function (cache) {
589
- this.externalListCache = cache;
590
- };
591
- EqContext.prototype.getListFromCache = function (params) {
592
- var key = this.getListCacheKey(params);
593
- if (this.externalListCache) {
594
- return this.externalListCache.get(key);
595
- }
596
- else {
597
- return this.internalListCache[key];
598
- }
599
- };
600
- EqContext.prototype.getListCacheKey = function (params) {
601
- var key = params.listName == 'SQL' ? 'SQL_' + params.editorId : params.listName;
602
- if (params.queryParams) {
603
- key += '_' + Object.keys(params.queryParams).filter(function (k) { return k != 'listName'; })
604
- .map(function (k) { return params.queryParams[k]; })
605
- .join('_');
606
- }
607
- return key;
608
- };
609
- EqContext.prototype.addListToCache = function (params, list) {
610
- var key = this.getListCacheKey(params);
611
- if (this.externalListCache) {
612
- this.externalListCache.set(key, list);
613
- }
614
- else {
615
- this.internalListCache[key] = list;
616
- }
617
- };
618
- /**
619
- * Clears the current list cache.
620
- */
621
- EqContext.prototype.resetListCache = function () {
622
- if (this.externalListCache) {
623
- this.externalListCache.clear();
624
- }
625
- else {
626
- this.internalListCache = {};
627
- }
628
- };
629
- /**
630
- * Gets the handler for 'GetList' requests
631
- */
632
- EqContext.prototype.getListRequestHandler = function () {
633
- return this._listRequestHandler;
634
- };
635
- /**
636
- * Adds the translations of the EasyQuery messages for some locale
637
- * @param locale - the ISO code of the locale (like `en` or `uk`)
638
- * @param localeInfo - Locale settings and translations of EasyQuery texts and messages.
639
- * We expected an object with the struture of LocaleInfo interface here.
640
- */
641
- EqContext.prototype.addLocale = function (locale, localeInfo) {
642
- i18n.addLocale(locale, localeInfo);
643
- };
644
- EqContext.prototype.addEventListener = function (eventType, handler) {
645
- var _this = this;
646
- return this.eventEmitter.subscribe(eventType, function (event) { return handler(_this, event.data); });
647
- };
648
- /**
649
- * Remove event handler for event type .
650
- * @param eventType The event type.
651
- * @param handlerId The handler id.
652
- */
653
- EqContext.prototype.removeEventListener = function (eventType, handlerId) {
654
- this.eventEmitter.unsubscribe(eventType, handlerId);
655
- };
656
- EqContext.prototype.fireEvent = function (eventType, data) {
657
- this.eventEmitter.fire(eventType, data);
658
- };
659
- EqContext.prototype.getBaseEndpoint = function () {
660
- return this.baseEndpoint;
661
- };
662
- /**
663
- * Sends a `loadValueList` requesthe server and processes the response.
664
- * @param options A map of options to pass to `loadValueList` function.
665
- */
666
- EqContext.prototype.loadValueList = function (options) {
667
- var _this = this;
668
- options = options || {};
669
- this.startProcess({
670
- action: EqAction.GetValueList,
671
- text: 'Loading values'
672
- }, WidgetGroup.Result);
673
- var valueListResolver = this.eqServices.getValueListResolver();
674
- valueListResolver.loadValueList(options)
675
- .then(function (values) {
676
- _this.endProcess({
677
- result: EqActionResult.Success,
678
- action: EqAction.GetValueList,
679
- text: 'Values loaded'
680
- }, WidgetGroup.Result);
681
- if (options.success) {
682
- options.success(values);
683
- }
684
- })
685
- .catch(function (error) {
686
- var editorId = options && options.params ? options.params.editorId : 'undefined';
687
- var errorMessage = "Can't load the value list for editor " + editorId + ".\n " + error.message;
688
- _this.endProcess({
689
- result: EqActionResult.Error,
690
- action: EqAction.GetValueList,
691
- text: errorMessage,
692
- sourceError: error
693
- }, WidgetGroup.Result);
694
- if (options.error) {
695
- options.error(errorMessage, 'GetValueList');
696
- }
697
- });
698
- };
699
- /**
700
- * Starts the process of the model loading.
701
- * This method can initiate a request to EasyQueryServer backend or get the model from OData or GraphQL endpoint
702
- * The content of the `options` parameter depends on concrete loader implementation.
703
- * @param options A map of options to pass to `loadModel` function (can be ommited)
704
- * @example
705
- * context.loadModel()
706
- * .then(model => {
707
- * alert("Model loaded!");
708
- * });
709
- */
710
- EqContext.prototype.loadModel = function (options) {
711
- var _this = this;
712
- if (this.beforeLoadModel) {
713
- this.beforeLoadModel(this, options);
714
- }
715
- var modelId = options.modelId || '__default';
716
- var silent = options.silent || false;
717
- this.startProcess({
718
- action: EqAction.LoadModel,
719
- text: 'Loading model: ' + modelId
720
- }, WidgetGroup.Model);
721
- var modelLoader = this.eqServices.getModelLoader();
722
- return modelLoader.startModelLoading(options)
723
- .then(function (value) {
724
- if (value) {
725
- _this.loadModelFromData(value);
726
- if (_this.dataModel.isEmpty()) {
727
- console.warn("Empty model has been loaded. Model ID: " + _this.dataModel.getId());
728
- }
729
- }
730
- else {
731
- console.warn('Model has not been changed.');
732
- }
733
- _this.fireEvent('loadModel');
734
- _this.endProcess({
735
- result: EqActionResult.Success,
736
- action: EqAction.LoadModel,
737
- text: 'Model loaded: ' + modelId
738
- }, WidgetGroup.Model);
739
- if (!silent) {
740
- _this.clearQuery();
741
- _this.clearResult();
742
- _this.refreshWidgets();
743
- }
744
- if (options.success) {
745
- options.success(_this.getModel());
746
- }
747
- return _this.getModel();
748
- })
749
- .catch(function (error) {
750
- var errorMessage = "Can't load model " + modelId + ".\n " + error.message;
751
- _this.endProcess({
752
- result: EqActionResult.Error,
753
- action: EqAction.LoadModel,
754
- text: errorMessage,
755
- sourceError: error
756
- }, WidgetGroup.Model);
757
- if (options.error) {
758
- options.error(errorMessage, "LoadModel");
759
- }
760
- return _this.getModel();
761
- });
762
- };
763
- EqContext.prototype.callWhenModelLoaded = function (callFunc) {
764
- var modelLoader = this.eqServices.getModelLoader();
765
- modelLoader.getModelPromise().then(function () {
766
- callFunc();
767
- });
768
- };
769
- /**
770
- * Loads the query
771
- * @param options
772
- * The content of the `options` parameter depends on `QueryStorage` implementation.
773
- * Usually it contains `success`, `error` callbacks and `queryId` property of the query to load.
774
- * @example
775
- * context.loadQuery({
776
- * queryId: "query-id"
777
- * });
778
- */
779
- EqContext.prototype.loadQuery = function (options) {
780
- var _this = this;
781
- options = options || {};
782
- var modelLoader = this.eqServices.getModelLoader();
783
- this.clearResult();
784
- modelLoader.getModelPromise()
785
- .then(function () {
786
- options = options || {};
787
- var queryId = options.queryId;
788
- var silent = options.silent || false;
789
- if (_this.beforeLoadQuery) {
790
- _this.beforeLoadQuery(_this, options);
791
- }
792
- _this.startProcess({
793
- action: EqAction.LoadQuery,
794
- text: "Query loading: " + queryId
795
- }, WidgetGroup.Query);
796
- var queryStorage = _this.eqServices.getQueryStorage();
797
- queryStorage.loadQuery(options)
798
- .then(function (data) {
799
- if (data) {
800
- _this.query.loadFromData(data, {
801
- validate: false
802
- });
803
- }
804
- _this.fireEvent('loadQuery');
805
- _this.endProcess({
806
- result: EqActionResult.Success,
807
- action: EqAction.LoadQuery,
808
- text: 'Query loaded: ' + queryId
809
- }, WidgetGroup.Query);
810
- _this.query.resetModified();
811
- if (!silent) {
812
- _this.query.fireChangedEvent({
813
- part: QueryChangePart.Properties,
814
- wasModified: _this.query.isModified()
815
- });
816
- _this.refreshWidgets();
817
- }
818
- if (options.success) {
819
- options.success(_this.query);
820
- }
821
- })
822
- .catch(function (error) {
823
- var query = _this.getQuery();
824
- error.message = "Can't load query [" + query.getId() + "]\n" + (error.message || "");
825
- if (options.error) {
826
- options.error(error.message, EqAction.LoadQuery);
827
- }
828
- _this.endProcess({
829
- result: EqActionResult.Error,
830
- action: EqAction.LoadQuery,
831
- text: error.message,
832
- sourceError: error
833
- }, WidgetGroup.Query);
834
- });
835
- })
836
- .catch(function (error) {
837
- console.error(error);
838
- });
839
- };
840
- /**
841
- * Loads the list of queries available for the current user.
842
- * @param options
843
- * The content of the `options` parameter depends on `QueryStorage` implementation.
844
- * Usually it contains `success`, `error` callbacks
845
- */
846
- EqContext.prototype.loadQueryList = function (options) {
847
- var _this = this;
848
- var modelLoader = this.eqServices.getModelLoader();
849
- modelLoader.getModelPromise()
850
- .then(function () {
851
- _this.startQueryListLoading(options);
852
- })
853
- .catch(function (error) {
854
- var errorMessage = "Can't load the list of available queries.\n " + error.message;
855
- _this.throwError({
856
- action: EqAction.LoadQueryList,
857
- text: errorMessage,
858
- sourceError: error
859
- });
860
- });
861
- };
862
- EqContext.prototype.startQueryListLoading = function (options) {
863
- var _this = this;
864
- options = options || {};
865
- var queryStorage = this.eqServices.getQueryStorage();
866
- var queryListLoadingPromise = queryStorage.getQueryList(options);
867
- queryListLoadingPromise
868
- .then(function (queries) {
869
- if (options.success) {
870
- options.success(queries);
871
- }
872
- })
873
- .catch(function (error) {
874
- var errorMessage = "Can't load the list of available queries.\n " + error.message;
875
- if (options.error) {
876
- options.error(errorMessage, 'LoadQueryList');
877
- }
878
- else {
879
- _this.throwError({
880
- action: EqAction.LoadQueryList,
881
- text: errorMessage,
882
- sourceError: error
883
- });
884
- }
885
- });
886
- };
887
- /**
888
- * Creates a new query and returns its content back to the client-side.
889
- * @param options
890
- * The content of the `options` parameter depends on `QueryStorage` implementation.
891
- * Usually it contains `success`, `error` callbacks and `silent` option
892
- * @example
893
- * context.newQuery({
894
- * silent: true
895
- * });
896
- */
897
- EqContext.prototype.newQuery = function (options) {
898
- var _this = this;
899
- options = options || {};
900
- var clearQuery = typeof options.clearQuery !== 'undefined' ? options.clearQuery : true;
901
- this.query.reset(clearQuery);
902
- if (options.queryId) {
903
- this.query.setId(options.queryId);
904
- }
905
- if (options.name) {
906
- this.query.setName(options.name);
907
- }
908
- if (options.description) {
909
- this.query.setDescription(options.description);
910
- }
911
- var silent = options.silent || false;
912
- var useStorage = true;
913
- if (typeof options.useStorage !== 'undefined') {
914
- useStorage = options.useStorage;
915
- }
916
- var onNewQuery = function () {
917
- var query = _this.getQuery();
918
- query.isNewbie = true;
919
- if (!silent) {
920
- query.fireChangedEvent({
921
- part: QueryChangePart.All,
922
- wasModified: query.isModified()
923
- });
924
- }
925
- };
926
- if (useStorage) {
927
- this.startProcess({
928
- action: EqAction.NewQuery,
929
- text: 'New query creation...'
930
- }, WidgetGroup.Query);
931
- var queryStorage = this.eqServices.getQueryStorage();
932
- queryStorage.newQuery(options)
933
- .then(function (queryData) {
934
- if (queryData) {
935
- _this.query.loadFromData(queryData);
936
- }
937
- _this.endProcess({
938
- result: EqActionResult.Success,
939
- action: EqAction.NewQuery,
940
- text: 'A new query has been created'
941
- }, WidgetGroup.Query);
942
- onNewQuery();
943
- if (options.success) {
944
- options.success();
945
- }
946
- })
947
- .catch(function (error) {
948
- var errorMessage = "Can't create a new query.\n" + error.message;
949
- _this.endProcess({
950
- result: EqActionResult.Error,
951
- action: EqAction.NewQuery,
952
- text: errorMessage,
953
- sourceError: error
954
- }, WidgetGroup.Query);
955
- if (options.error) {
956
- options.error(errorMessage, "NewQuery");
957
- }
958
- });
959
- }
960
- else {
961
- onNewQuery();
962
- }
963
- return this.query;
964
- };
965
- /**
966
- * Saves the current query to some storage on the server-side.
967
- * @param options
968
- * The content of the `options` parameter depends on `QueryStorage` implementation.
969
- * Usually it contains `success` and `error` callbacks
970
- */
971
- EqContext.prototype.saveQuery = function (options) {
972
- var _this = this;
973
- options = options || {};
974
- var query = this.getQuery();
975
- this.startProcess({
976
- action: EqAction.SaveQuery,
977
- text: 'Query saving: ' + query.getId()
978
- }, WidgetGroup.Query);
979
- var queryStorage = this.eqServices.getQueryStorage();
980
- queryStorage.saveQuery(options)
981
- .then(function (data) {
982
- _this.endProcess({
983
- action: EqAction.SaveQuery,
984
- result: EqActionResult.Success,
985
- text: "Query saved: " + query.getId()
986
- }, WidgetGroup.Query);
987
- if (data) {
988
- query.loadFromData(data);
989
- }
990
- query.resetModified();
991
- query.isNewbie = false;
992
- if (options.success) {
993
- options.success();
994
- }
995
- })
996
- .catch(function (error) {
997
- var errorMessage = "Can't save query " + query.getId() + ".\n " + error.message;
998
- _this.endProcess({
999
- action: EqAction.SaveQuery,
1000
- result: EqActionResult.Error,
1001
- text: errorMessage,
1002
- sourceError: error
1003
- }, WidgetGroup.Query);
1004
- if (options.error) {
1005
- options.error(errorMessage, EqAction.SaveQuery);
1006
- }
1007
- });
1008
- };
1009
- /**
1010
- * Removes the current query from some storage on the server-side.
1011
- * @param options
1012
- * The content of the `options` parameter depends on `QueryStorage` implementation.
1013
- * Usually it contains `success` and `error` callbacks
1014
- */
1015
- EqContext.prototype.removeQuery = function (options) {
1016
- var _this = this;
1017
- options = options || {};
1018
- var query = this.getQuery();
1019
- this.startProcess({
1020
- action: EqAction.RemoveQuery,
1021
- text: 'Query deleting: ' + query.getId()
1022
- }, WidgetGroup.Query);
1023
- var queryStorage = this.eqServices.getQueryStorage();
1024
- queryStorage.removeQuery(options)
1025
- .then(function () {
1026
- query.reset();
1027
- _this.endProcess({
1028
- action: EqAction.RemoveQuery,
1029
- result: EqActionResult.Success,
1030
- text: "Query deleted: " + query.getId()
1031
- }, WidgetGroup.Query);
1032
- if (options.success) {
1033
- options.success();
1034
- }
1035
- })
1036
- .catch(function (error) {
1037
- var errorMessage = "Can't remove query " + query.getId() + ".\n " + error.message;
1038
- _this.endProcess({
1039
- action: EqAction.RemoveQuery,
1040
- result: EqActionResult.Error,
1041
- text: errorMessage,
1042
- sourceError: error
1043
- }, WidgetGroup.Query);
1044
- if (options.error) {
1045
- options.error(errorMessage, 'RemoveQuery');
1046
- }
1047
- });
1048
- };
1049
- /**
1050
- * Syncronizes the current query.
1051
- * @param options
1052
- * The content of the `options` parameter depends on `QuerySyncronizer` implementation.
1053
- * Usually it contains `success` and `error` callbacks
1054
- */
1055
- EqContext.prototype.syncQuery = function (options) {
1056
- var _this = this;
1057
- options = options || {};
1058
- var query = this.getQuery();
1059
- if (this.beforeSyncQuery) {
1060
- this.beforeSyncQuery(this, options);
1061
- }
1062
- this.startProcess({
1063
- action: EqAction.SyncQuery,
1064
- text: 'Query syncing: ' + query.getId()
1065
- }, WidgetGroup.Query);
1066
- var querySyncrhonizer = this.eqServices.getQuerySynchronizer();
1067
- querySyncrhonizer.syncQuery(options)
1068
- .then(function (result) {
1069
- _this.resultStatement = result && result.statement
1070
- ? result.statement
1071
- : '';
1072
- _this.fireEvent('syncQuery');
1073
- _this.refreshWidgets(WidgetGroup.Statement);
1074
- _this.endProcess({
1075
- result: EqActionResult.Success,
1076
- action: EqAction.SyncQuery,
1077
- text: 'Query synced: ' + query.getId()
1078
- }, WidgetGroup.Query);
1079
- if (result) {
1080
- if (result.querySaved) {
1081
- var q = result.query;
1082
- if (q) {
1083
- query.setId(q.id);
1084
- query.setName(q.name);
1085
- query.setDescription(q.desc);
1086
- query.extraData = q.extraData;
1087
- }
1088
- query.resetModified();
1089
- _this.refreshWidgets(WidgetGroup.QueryStatus);
1090
- }
1091
- if (options.success) {
1092
- options.success(result);
1093
- }
1094
- }
1095
- })
1096
- .catch(function (error) {
1097
- var errorMessage = "Can't synchronize query " + query.getId() + ".\n " + error.message;
1098
- _this.endProcess({
1099
- result: EqActionResult.Error,
1100
- action: EqAction.SyncQuery,
1101
- text: errorMessage,
1102
- sourceError: error
1103
- }, WidgetGroup.Query);
1104
- if (options.error) {
1105
- options.error(errorMessage, 'SyncQuery');
1106
- }
1107
- });
1108
- };
1109
- /**
1110
- * Fetches the data (usuall by executing current query) and processes the result.
1111
- * @param options
1112
- * The `options` parameter in addition to the options defined in FetchDataOptions structure may also contain `success` and `error` callbacks.
1113
- * @example
1114
- * context.fetchData({ success: function(result) {
1115
- * //do whatever you want with the result
1116
- * }})
1117
- *
1118
- */
1119
- EqContext.prototype.fetchData = function (options) {
1120
- var _this = this;
1121
- options = options || {};
1122
- var elasticPaging = typeof (options.elasticPaging) !== 'undefined'
1123
- ? options.elasticPaging
1124
- : this.elasticPaging;
1125
- this.resultTable.elasticChunks = elasticPaging;
1126
- options.chunk = options.chunk ||
1127
- {
1128
- offset: 0,
1129
- limit: this.resultTable.chunkSize,
1130
- needTotal: !elasticPaging
1131
- };
1132
- if (this.debugMode) {
1133
- options.debug = 'Fetching the result set. Initial chunk';
1134
- }
1135
- if (!this.query.tryValidate({
1136
- checkExpressions: true
1137
- })) {
1138
- return;
1139
- }
1140
- //just to support the old way of catching "group fetch" operation finish
1141
- if (options.groupFetchSuccess) {
1142
- this.afterGroupFetch = options.groupFetchSuccess;
1143
- }
1144
- if (this.resultTable.elasticChunks) {
1145
- options.chunk.limit++;
1146
- }
1147
- this.fetchDataChunk(__assign(__assign({}, options), { success: function (result) {
1148
- if (result.statement) {
1149
- _this.resultStatement = result.statement;
1150
- _this.refreshWidgets(WidgetGroup.Statement);
1151
- }
1152
- var aggrCalculator = _this.getServices().getAggregatesCalculator();
1153
- aggrCalculator.reset();
1154
- _this.resultContent = result;
1155
- if (result.resultSet) {
1156
- _this.resultTable.clear();
1157
- _this.resultTable.id = _this.query.getId();
1158
- var resultSet = result.resultSet;
1159
- for (var _i = 0, _a = resultSet.cols; _i < _a.length; _i++) {
1160
- var col = _a[_i];
1161
- _this.resultTable.columns.add(col);
1162
- }
1163
- if (result.meta && typeof (result.meta.totalRecords) !== 'undefined') {
1164
- _this.resultTable.setTotal(result.meta.totalRecords);
1165
- }
1166
- var count = resultSet.rows.length;
1167
- if (_this.resultTable.elasticChunks && count === options.chunk.limit) {
1168
- resultSet.rows.splice(resultSet.rows.length - 1, 1);
1169
- }
1170
- for (var _b = 0, _c = resultSet.rows; _b < _c.length; _b++) {
1171
- var row = _c[_b];
1172
- _this.resultTable.addRow(row);
1173
- }
1174
- if (_this.resultTable.elasticChunks) {
1175
- _this.resultTable['total'] = (count < options.chunk.limit)
1176
- ? resultSet.rows.length
1177
- : 0;
1178
- }
1179
- _this.resultTable.fireUpdated();
1180
- }
1181
- if (options.success) {
1182
- options.success(result);
1183
- }
1184
- } }));
1185
- };
1186
- EqContext.prototype.getQueryFile = function (options) {
1187
- var _this = this;
1188
- var query = this.getQuery();
1189
- this.startProcess({
1190
- action: EqAction.GetQueryFile,
1191
- text: 'Getting query file: ' + query.getId()
1192
- }, WidgetGroup.Query);
1193
- var queryFileLoader = this.getServices().getQueryFileLoader();
1194
- queryFileLoader.getQueryFile(options)
1195
- .then(function () {
1196
- _this.endProcess({
1197
- result: EqActionResult.Success,
1198
- action: EqAction.GetQueryFile,
1199
- text: 'Getting query file: ' + query.getId()
1200
- }, WidgetGroup.Result);
1201
- if (options.success) {
1202
- options.success();
1203
- }
1204
- })
1205
- .catch(function (error) {
1206
- var errorMessage = "Can't get file for query " + query.getId() + ".\n " + error.message;
1207
- _this.endProcess({
1208
- result: EqActionResult.Error,
1209
- action: EqAction.GetQueryFile,
1210
- text: errorMessage,
1211
- sourceError: error
1212
- }, WidgetGroup.Query);
1213
- if (options.error) {
1214
- options.error(errorMessage, 'GetQueryFile');
1215
- }
1216
- });
1217
- };
1218
- EqContext.prototype.uploadQueryFile = function (options) {
1219
- var _this = this;
1220
- var query = this.getQuery();
1221
- this.startProcess({
1222
- action: EqAction.UploadQueryFile,
1223
- text: 'Uploading query file: ' + query.getId()
1224
- }, WidgetGroup.Query);
1225
- var queryFileLoader = this.getServices().getQueryFileLoader();
1226
- queryFileLoader.uploadQueryFile(options)
1227
- .then(function (data) {
1228
- query.loadFromData(data);
1229
- _this.fireEvent('loadQuery');
1230
- _this.refreshWidgets();
1231
- _this.endProcess({
1232
- result: EqActionResult.Success,
1233
- action: EqAction.UploadQueryFile,
1234
- text: 'Uploading query file: ' + query.getId()
1235
- }, WidgetGroup.Result);
1236
- if (options.success) {
1237
- options.success();
1238
- }
1239
- })
1240
- .catch(function (error) {
1241
- var errorMessage = "Can't upload a file for query " + query.getId() + ".\n " + error.message;
1242
- _this.endProcess({
1243
- result: EqActionResult.Error,
1244
- action: EqAction.UploadQueryFile,
1245
- text: errorMessage,
1246
- sourceError: error
1247
- }, WidgetGroup.Query);
1248
- if (options.error) {
1249
- options.error(errorMessage, 'UploadQueryFile');
1250
- }
1251
- });
1252
- };
1253
- EqContext.prototype.fetchDataChunk = function (options) {
1254
- var _this = this;
1255
- var queryId = this.getQuery().getId();
1256
- var fetchOptions = options || {};
1257
- if (this.useStoredQueryOnFetch) {
1258
- fetchOptions.queryId = this.query.getId();
1259
- }
1260
- if (this.beforeFetchData) {
1261
- this.beforeFetchData(this, fetchOptions);
1262
- }
1263
- this.startProcess({
1264
- action: EqAction.FetchData,
1265
- text: 'Fetching data for the query: ' + queryId
1266
- }, WidgetGroup.Result);
1267
- var dataFetcher = this.eqServices.getDataFetcher();
1268
- dataFetcher.fetchData(fetchOptions)
1269
- .then(function (result) {
1270
- if (result.statement) {
1271
- _this.resultStatement = result.statement;
1272
- }
1273
- _this.resultContent = result;
1274
- // we need to call success callback before firing fetchData,
1275
- // because otherwise, it won't update the result table
1276
- // in the context before afterFetchData callback is called.
1277
- if (fetchOptions.success) {
1278
- fetchOptions.success(result);
1279
- }
1280
- _this.fireEvent('fetchData');
1281
- _this.endProcess({
1282
- result: EqActionResult.Success,
1283
- action: EqAction.FetchData,
1284
- text: 'Data fetching is finished for the query: ' + queryId
1285
- }, WidgetGroup.Result);
1286
- })
1287
- .catch(function (error) {
1288
- var errorMessage = "Data fetching error for the query " + queryId + ". \n" + error.message;
1289
- _this.endProcess({
1290
- result: EqActionResult.Error,
1291
- action: EqAction.FetchData,
1292
- text: errorMessage,
1293
- sourceError: error
1294
- }, WidgetGroup.Result);
1295
- if (fetchOptions.error) {
1296
- fetchOptions.error(errorMessage, EqAction.FetchData);
1297
- }
1298
- });
1299
- };
1300
- EqContext.prototype.onResultTableUpdate = function () {
1301
- var _this = this;
1302
- var aggrSettings = this.query.getAggregationSettings();
1303
- var calculator = this.getServices().getAggregatesCalculator();
1304
- if (aggrSettings.needAggrCalculation() && calculator.needRecalculation()) {
1305
- calculator.calculate({
1306
- maxLevel: aggrSettings.getGroups().length + 1,
1307
- resultObtained: function (result, level) {
1308
- if (_this.afterGroupFetch) {
1309
- _this.afterGroupFetch(result);
1310
- }
1311
- },
1312
- errorOccurred: function (error) {
1313
- var errorMessage = "Data fetching error on group level " + error.level + " query. \n" + error.message;
1314
- _this.throwError({
1315
- action: EqAction.FetchData,
1316
- text: errorMessage,
1317
- sourceError: error
1318
- });
1319
- }
1320
- });
1321
- }
1322
- };
1323
- /**
1324
- * Fetches the data for a drill-down query (if defined) and processes the result.
1325
- * @param options
1326
- */
1327
- EqContext.prototype.fetchDrillDownData = function (options) {
1328
- var _this = this;
1329
- options = options || {};
1330
- options.chunk = options.chunk ||
1331
- {
1332
- offset: 0,
1333
- limit: this.resultTable.chunkSize,
1334
- needTotal: true
1335
- };
1336
- var query = options.query;
1337
- var queryId = query.getId();
1338
- this.startProcess({
1339
- action: EqAction.FetchData,
1340
- text: 'DrillDown executing: ' + queryId
1341
- }, WidgetGroup.Result);
1342
- var queryExecutor = this.eqServices.getDataFetcher();
1343
- queryExecutor.fetchData(options)
1344
- .then(function (result) {
1345
- _this.endProcess({
1346
- result: EqActionResult.Success,
1347
- action: EqAction.FetchData,
1348
- text: 'DrillDown execution error: ' + queryId
1349
- }, WidgetGroup.Result);
1350
- if (options.success) {
1351
- options.success(result);
1352
- }
1353
- })
1354
- .catch(function (error) {
1355
- var errorMessage = "Drill-down data fetching error for query " + queryId + ". \n" + error.message;
1356
- _this.endProcess({
1357
- result: EqActionResult.Error,
1358
- action: EqAction.FetchData,
1359
- text: errorMessage,
1360
- }, WidgetGroup.Result);
1361
- if (options.error) {
1362
- options.error(errorMessage, 'DrillDown');
1363
- }
1364
- else {
1365
- _this.throwError({
1366
- action: EqAction.FetchData,
1367
- text: errorMessage
1368
- });
1369
- }
1370
- });
1371
- };
1372
- /**
1373
- * Fetches the data for defined by this context and exports them to the specified format.
1374
- * @param options
1375
- * The content of the `options` parameter depends on `EqExporter` implementation.
1376
- * Usually it contains `format` property which defines the format of the exported data (e.g. `csv`),
1377
- * and `success` and `error` callbacks
1378
- * @example
1379
- * context.exportResult({
1380
- * format: csv
1381
- * });
1382
- *
1383
- */
1384
- EqContext.prototype.exportResult = function (options) {
1385
- var _this = this;
1386
- options = options || {};
1387
- if (this.beforeExportResult) {
1388
- this.beforeExportResult(this, options);
1389
- }
1390
- var format = options.format;
1391
- if (format) {
1392
- var exporter = this.getExporter(format);
1393
- if (exporter) {
1394
- var queryId_1 = this.getQuery().getId();
1395
- if (this.useStoredQueryOnFetch) {
1396
- options.queryId = queryId_1;
1397
- }
1398
- this.startProcess({
1399
- action: EqAction.ExportResult,
1400
- text: 'Exporting result for query: ' + queryId_1
1401
- }, WidgetGroup.Result);
1402
- var localeSettings = i18n.getLocaleSettings();
1403
- options.settings = localeSettings;
1404
- var aggrSettings = this.query.getAggregationSettings();
1405
- if (aggrSettings.hasAggregates()
1406
- && (aggrSettings.hasGrandTotals() || aggrSettings.hasGroups())) {
1407
- options.aggregates = aggrSettings.saveToData();
1408
- }
1409
- exporter.export(options)
1410
- .then(function (result) {
1411
- _this.fireEvent('exportResult');
1412
- _this.endProcess({
1413
- result: EqActionResult.Success,
1414
- action: EqAction.ExportResult,
1415
- text: "The result set for query [" + queryId_1 + "] has been successfully exported"
1416
- }, WidgetGroup.Result);
1417
- if (options.success) {
1418
- options.success();
1419
- }
1420
- })
1421
- .catch(function (error) {
1422
- var errorMessage = "Error on exporting data for query " + queryId_1 + ". \n" + error.message;
1423
- _this.endProcess({
1424
- result: EqActionResult.Error,
1425
- action: EqAction.ExportResult,
1426
- text: errorMessage,
1427
- sourceError: error
1428
- }, WidgetGroup.Result);
1429
- if (options.error) {
1430
- options.error(errorMessage, 'ExportResult');
1431
- }
1432
- });
1433
- }
1434
- }
1435
- };
1436
- return EqContext;
1437
- }());
1438
- export { EqContext };
1
+ var __assign = (this && this.__assign) || function () {
2
+ __assign = Object.assign || function(t) {
3
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
4
+ s = arguments[i];
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
+ t[p] = s[p];
7
+ }
8
+ return t;
9
+ };
10
+ return __assign.apply(this, arguments);
11
+ };
12
+ import { EasyDataTable, EventEmitter, utils as dataUtils } from '@easydata/core';
13
+ import { i18n } from '@easydata/core';
14
+ import { EqServiceProvider } from '../common/eq_services';
15
+ import { QueryChangePart } from '../query/query_events';
16
+ import { EqActionResult } from './action';
17
+ import { WidgetGroup } from '../types/widget_group';
18
+ import { equtils } from '../utils/utils';
19
+ import { EqAction } from './eq_actions';
20
+ import { EqServerExporter } from '../eqs/eqs_exporter';
21
+ import { EasyQueryDataLoader } from '../data/eq_data_loader';
22
+ /**
23
+ * Encapsulates all information about EasyQuery components on some webpage
24
+ * and provides some basic operation over those components
25
+ * Each context includes the following main components:
26
+ * - one data model,
27
+ * - one query,
28
+ * - one result set
29
+ * - several UI widgets.
30
+ */
31
+ var EqContext = /** @class */ (function () {
32
+ function EqContext() {
33
+ var _this = this;
34
+ this.servicesInitialized = false;
35
+ this.internalListCache = {};
36
+ this.loadModelOnStart = true;
37
+ this.loadQueryOnStart = false;
38
+ this.useStoredQueryOnFetch = false;
39
+ this.debugMode = false;
40
+ this._backendInfo = {
41
+ type: 'EQN-ANC',
42
+ subType: 'asp-net-core-razor'
43
+ };
44
+ //----------- endpoint processing functions --------------
45
+ this.endpointVarsRegex = /\{.*?\}/g;
46
+ this.elasticPaging = false;
47
+ this._predefinedListRequestHandlers = {
48
+ '_DSDE': function (params, onResult) {
49
+ var data = _this.getModel().getAllDateMacros()
50
+ .map(function (macroId) {
51
+ return { id: '${{' + macroId + '}}', text: i18n.getText(macroId) };
52
+ });
53
+ onResult(data);
54
+ return true;
55
+ },
56
+ '_DSTE': function (params, onResult) {
57
+ var data = _this.getModel().getAllTimeMacros()
58
+ .map(function (macroId) {
59
+ return { id: '${{' + macroId + '}}', text: i18n.getText(macroId) };
60
+ });
61
+ onResult(data);
62
+ return true;
63
+ }
64
+ };
65
+ this._listRequestHandler = function (options, onResult) {
66
+ if (options == null || !options.listName)
67
+ return;
68
+ var query = _this.getQuery();
69
+ var params = dataUtils.assign({ listName: options.listName }, options.editorParams);
70
+ var reqParams = {};
71
+ var attrPattern = /@{{(.+?)}}/;
72
+ for (var prop in params) {
73
+ if (!params[prop])
74
+ continue;
75
+ var match = params[prop].match(attrPattern);
76
+ if (match) {
77
+ var paramValue = query.getOneValueForAttr(match[1]);
78
+ if (!paramValue) {
79
+ paramValue = '';
80
+ }
81
+ reqParams[prop] = params[prop].replace(attrPattern, paramValue);
82
+ }
83
+ }
84
+ var requestParams = {
85
+ listName: reqParams.listName,
86
+ editorId: options.editorId,
87
+ queryParams: reqParams
88
+ };
89
+ var list = _this.getListFromCache(options);
90
+ if (list && list.length > 0) {
91
+ onResult(list);
92
+ return;
93
+ }
94
+ var processed = false;
95
+ var predefinedHandler = _this._predefinedListRequestHandlers[options.editorId];
96
+ if (predefinedHandler) {
97
+ processed = predefinedHandler(options, onResult);
98
+ }
99
+ if (!processed && _this.clientListRequestHandler) {
100
+ processed = _this.clientListRequestHandler(options, onResult);
101
+ }
102
+ if (!processed) {
103
+ _this.loadValueList({
104
+ params: requestParams,
105
+ success: function (data) {
106
+ if (data) {
107
+ _this.addListToCache(options, data);
108
+ }
109
+ onResult(data);
110
+ },
111
+ error: function (message) {
112
+ onResult(null);
113
+ }
114
+ });
115
+ }
116
+ };
117
+ this.baseEndpoint = 'api/easyquery';
118
+ this.eqServices = new EqServiceProvider(this);
119
+ this.widgets = new Array();
120
+ this.eventEmitter = new EventEmitter(this);
121
+ this.exporters = new Map();
122
+ this.endpoints = new Map();
123
+ this.dataLoader = new EasyQueryDataLoader(this);
124
+ this.resultTable = new EasyDataTable({
125
+ loader: this.dataLoader,
126
+ onUpdate: this.onResultTableUpdate.bind(this)
127
+ });
128
+ this.resultTable.id = 'ResultTable';
129
+ this.errorHandlerId = this.addEventListener('error', function (context, status) {
130
+ status.result = EqActionResult.Error;
131
+ var msgTitle = status.action ? status.action + ' error' : 'Error';
132
+ var msgText = status.text ? status.text : '';
133
+ if (status.sourceError && status.sourceError.message !== msgText) {
134
+ msgText += '\n' + status.sourceError;
135
+ }
136
+ console.error(msgTitle + ': ' + msgText);
137
+ });
138
+ }
139
+ EqContext.prototype.getServices = function () {
140
+ return this.eqServices;
141
+ };
142
+ EqContext.prototype.registerExporter = function (format, resolver) {
143
+ this.exporters.set(format, resolver);
144
+ };
145
+ EqContext.prototype.registerServerExporter = function (format, responseType) {
146
+ this.registerExporter(format, function (context) {
147
+ var exporter = new EqServerExporter(context);
148
+ exporter.setFormat(format, responseType);
149
+ return exporter;
150
+ });
151
+ };
152
+ EqContext.prototype.getExporter = function (format) {
153
+ var resolver = this.exporters.get(format);
154
+ if (resolver) {
155
+ return resolver(this);
156
+ }
157
+ return null;
158
+ };
159
+ EqContext.prototype.getExportFormats = function () {
160
+ return Array.from(this.exporters.keys());
161
+ };
162
+ EqContext.prototype.addDefaultExporters = function () {
163
+ this.registerServerExporter('csv', '');
164
+ this.registerServerExporter('excel-html', '');
165
+ };
166
+ EqContext.prototype.resolveEndpoint = function (endpointKey, options) {
167
+ options = options || {};
168
+ var result = this.endpoints.get(endpointKey);
169
+ if (!result) {
170
+ throw endpointKey + ' endpoint is not defined';
171
+ }
172
+ var matches = result.match(this.endpointVarsRegex);
173
+ if (matches) {
174
+ for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {
175
+ var match = matches_1[_i];
176
+ var opt = match.substring(1, match.length - 1);
177
+ var optVal = options[opt];
178
+ if (!optVal) {
179
+ if (opt == 'modelId') {
180
+ optVal = this.getModel().getId();
181
+ }
182
+ else if (opt == 'queryId') {
183
+ optVal = this.getQuery().getId();
184
+ }
185
+ else {
186
+ throw "Parameter [".concat(opt, "] is not defined");
187
+ }
188
+ }
189
+ result = result.replace(match, optVal);
190
+ }
191
+ }
192
+ return result;
193
+ };
194
+ EqContext.prototype.setEndpoint = function (key, value) {
195
+ this.endpoints.set(key, value);
196
+ };
197
+ EqContext.prototype.setEnpointIfNotExist = function (key, value) {
198
+ if (!this.endpoints.has(key))
199
+ this.endpoints.set(key, value);
200
+ };
201
+ EqContext.prototype.setDefaultEndpoints = function (endpointBase) {
202
+ this.setEnpointIfNotExist('GetModel', equtils.combinePath(endpointBase, 'models/{modelId}'));
203
+ this.setEnpointIfNotExist('GetQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries/{queryId}'));
204
+ this.setEnpointIfNotExist('SaveQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries/{queryId}'));
205
+ this.setEnpointIfNotExist('SyncQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries/{queryId}/sync'));
206
+ this.setEnpointIfNotExist('NewQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries'));
207
+ this.setEnpointIfNotExist('RemoveQuery', equtils.combinePath(endpointBase, 'models/{modelId}/queries/{queryId}'));
208
+ this.setEnpointIfNotExist('GetQueryList', equtils.combinePath(endpointBase, 'models/{modelId}/queries'));
209
+ this.setEnpointIfNotExist('FetchData', equtils.combinePath(endpointBase, 'models/{modelId}/fetch'));
210
+ this.setEnpointIfNotExist('GetValueList', equtils.combinePath(endpointBase, 'models/{modelId}/valuelists/{listId}'));
211
+ this.setEnpointIfNotExist('ExportResult', equtils.combinePath(endpointBase, 'models/{modelId}/export/{format}'));
212
+ this.setEnpointIfNotExist('GetQueryFile', equtils.combinePath(endpointBase, 'models/{modelId}/getqueryfile/{format}'));
213
+ this.setEnpointIfNotExist('UploadQueryFile', equtils.combinePath(endpointBase, 'models/{modelId}/uploadqueryfile'));
214
+ };
215
+ EqContext.prototype.initStart = function () {
216
+ this.servicesInitialized = true;
217
+ };
218
+ /**
219
+ * Initializes the context
220
+ * @param options
221
+ */
222
+ EqContext.prototype.init = function (options) {
223
+ var _this = this;
224
+ if (!this.servicesInitialized)
225
+ this.initStart();
226
+ options = options || {};
227
+ if (typeof (options.debugMode) !== 'undefined') {
228
+ this.debugMode = options.debugMode;
229
+ }
230
+ if (typeof (options.chunkSize) !== 'undefined') {
231
+ this.resultTable.chunkSize = options.chunkSize;
232
+ }
233
+ if (typeof (options.elasticPaging) !== 'undefined') {
234
+ this.elasticPaging = options.elasticPaging;
235
+ }
236
+ if (options.listCache) {
237
+ this.setExternalListCache(options.listCache);
238
+ }
239
+ if (options.locale) {
240
+ i18n.setCurrentLocale(options.locale);
241
+ }
242
+ if (options.localeSettings) {
243
+ i18n.updateLocaleSettings(options.localeSettings);
244
+ }
245
+ if (options.endpoint) {
246
+ this.baseEndpoint = options.endpoint;
247
+ console.warn('The `endpoint` option is deprecated.\n'
248
+ + 'Please use `context.useEndpoint(endpointURL)` function instead.');
249
+ }
250
+ this.setDefaultEndpoints(this.baseEndpoint);
251
+ if (options.modelStorageResolver) {
252
+ var eqServices = this.getServices();
253
+ eqServices.registerModelStorageResolver(options.modelStorageResolver);
254
+ }
255
+ this.loadQueryOnStart = false;
256
+ if (options.loadQueryOnStart) {
257
+ this.loadQueryOnStart = options.loadQueryOnStart;
258
+ }
259
+ this.loadModelOnStart = true;
260
+ if (typeof options.loadModelOnStart !== 'undefined') {
261
+ this.loadModelOnStart = options.loadModelOnStart;
262
+ }
263
+ if (options.handlers) {
264
+ if (options.handlers.onInit) {
265
+ this.addEventListener('ready', options.handlers.onInit);
266
+ }
267
+ if (options.handlers.afterLoadModel) {
268
+ this.addEventListener('loadModel', options.handlers.afterLoadModel);
269
+ }
270
+ if (options.handlers.afterLoadQuery) {
271
+ this.addEventListener('loadQuery', options.handlers.afterLoadQuery);
272
+ }
273
+ if (options.handlers.afterSyncQuery) {
274
+ this.addEventListener('syncQuery', options.handlers.afterSyncQuery);
275
+ }
276
+ if (options.handlers.afterFetchData) {
277
+ this.addEventListener('fetchData', options.handlers.afterFetchData);
278
+ }
279
+ if (options.handlers.afterExportResult) {
280
+ this.addEventListener('exportResult', options.handlers.afterExportResult);
281
+ }
282
+ if (options.handlers.onProcessStart) {
283
+ this.addEventListener('processStart', options.handlers.onProcessStart);
284
+ }
285
+ if (options.handlers.onProcessEnd) {
286
+ this.addEventListener('processEnd', options.handlers.onProcessEnd);
287
+ }
288
+ if (options.handlers.onError) {
289
+ this.removeEventListener('error', this.errorHandlerId);
290
+ this.addEventListener('error', options.handlers.onError);
291
+ }
292
+ if (options.handlers.onListRequest) {
293
+ this.clientListRequestHandler = options.handlers.onListRequest;
294
+ }
295
+ if (options.handlers.beforeLoadModel) {
296
+ this.beforeLoadModel = options.handlers.beforeLoadModel;
297
+ }
298
+ if (options.handlers.beforeLoadQuery) {
299
+ this.beforeLoadQuery = options.handlers.beforeLoadQuery;
300
+ }
301
+ if (options.handlers.beforeSyncQuery) {
302
+ this.beforeSyncQuery = options.handlers.beforeSyncQuery;
303
+ }
304
+ if (options.handlers.beforeFetchData) {
305
+ this.beforeFetchData = options.handlers.beforeFetchData;
306
+ }
307
+ if (options.handlers.beforeExportResult) {
308
+ this.beforeExportResult = options.handlers.beforeExportResult;
309
+ }
310
+ }
311
+ this.initialQuery = options.initialQuery;
312
+ this.defaultQueryId = options.defaultQueryId || '';
313
+ this.defaultModelId = options.defaultModelId || '__default';
314
+ var modelLoader = this.eqServices.getModelLoader();
315
+ modelLoader.init(options);
316
+ var queryStorage = this.eqServices.getQueryStorage();
317
+ queryStorage.init(options);
318
+ if (options.useDefaultExporters !== false) {
319
+ this.addDefaultExporters();
320
+ }
321
+ if (options.serverExporters) {
322
+ this.exporters.clear();
323
+ for (var _i = 0, _a = options.serverExporters; _i < _a.length; _i++) {
324
+ var format = _a[_i];
325
+ var responseType = format == 'csv' || format == 'excel-html' ? '' : 'arraybuffer';
326
+ this.registerServerExporter(format, responseType);
327
+ }
328
+ }
329
+ var query = this.getQuery();
330
+ if (options.defaultQueryId) {
331
+ query.setId(options.defaultQueryId);
332
+ }
333
+ //init widgets
334
+ this.widgets.forEach(function (widget) {
335
+ var widgetOptions = {};
336
+ if (options.widgets && options.widgets[widget.getWidgetType()]) {
337
+ widgetOptions = options.widgets[widget.getWidgetType()];
338
+ }
339
+ widget.init(_this, widgetOptions);
340
+ });
341
+ if (this.loadModelOnStart) {
342
+ this.loadDefaultModel();
343
+ }
344
+ else {
345
+ this.fireEvent('ready');
346
+ }
347
+ };
348
+ Object.defineProperty(EqContext.prototype, "backendInfo", {
349
+ get: function () {
350
+ return this._backendInfo;
351
+ },
352
+ enumerable: false,
353
+ configurable: true
354
+ });
355
+ /**
356
+ * Sets endpoint for all EasyQuery actions. Should be called before `init` and
357
+ * `useEnterprise` methods
358
+ * @param endpoint
359
+ * @example
360
+ * ```
361
+ * view.getContext()
362
+ * .useEndpoint('/api/easyquery')
363
+ * .useEnterprise(function () {
364
+ * view.init();
365
+ * });
366
+ * ```
367
+ */
368
+ EqContext.prototype.useEndpoint = function (endpoint) {
369
+ this.baseEndpoint = endpoint;
370
+ return this;
371
+ };
372
+ /**
373
+ * Allows to specify the type of backend service.
374
+ *
375
+ * @param backendInfo - the structure that contains information about the app used on the backend
376
+ * Possible values for `ptag` property: 'EQN-ANC' - ASP.NET Core or 'EQN-ASP' - for ASP.NET 4 backend
377
+ */
378
+ EqContext.prototype.useBackend = function (backendInfo) {
379
+ if (backendInfo.type) {
380
+ this._backendInfo.type = backendInfo.type;
381
+ }
382
+ if (backendInfo.subType) {
383
+ this._backendInfo.subType = backendInfo.subType;
384
+ }
385
+ else {
386
+ switch (this._backendInfo.type) {
387
+ case 'EQN-ANC':
388
+ this._backendInfo.subType = 'asp-net-core-razor';
389
+ break;
390
+ case 'EQN-ASP':
391
+ this._backendInfo.subType = 'asp-net-4-mvc';
392
+ break;
393
+ default:
394
+ this._backendInfo.subType = 'other';
395
+ break;
396
+ }
397
+ }
398
+ return this;
399
+ };
400
+ /**
401
+ * Add a new widget to the context.
402
+ * After that the widget will start to receive messages from other context components.
403
+ * @param widget
404
+ */
405
+ EqContext.prototype.addWidget = function (widget) {
406
+ this.widgets.push(widget);
407
+ };
408
+ /**
409
+ * Returns all widgets with current type.
410
+ * @param widgetType The widget type
411
+ */
412
+ EqContext.prototype.getAllWidgetsByType = function (widgetType) {
413
+ return this.widgets
414
+ .filter(function (widget) { return widget.getWidgetType() === widgetType; });
415
+ };
416
+ /**
417
+ * Returns first registerd widget with current type
418
+ * @param widgetType The widget type
419
+ */
420
+ EqContext.prototype.getWidgetByType = function (widgetType) {
421
+ var widgets = this.getAllWidgetsByType(widgetType);
422
+ return widgets.length > 0 ? widgets[0] : null;
423
+ };
424
+ /**
425
+ * This method is called automatically when some change was made either in context's data model or query
426
+ * @param groups
427
+ */
428
+ EqContext.prototype.refreshWidgets = function (groups) {
429
+ if (groups === void 0) { groups = WidgetGroup.All; }
430
+ this.widgets.forEach(function (widget) {
431
+ if (widget.belongsToGroup(groups)) {
432
+ widget.refresh();
433
+ }
434
+ });
435
+ };
436
+ /**
437
+ * Register a new handler for 'query changed' event
438
+ * @param callback
439
+ */
440
+ EqContext.prototype.addQueryChangedCallback = function (callback) {
441
+ this.getQuery().addChangedCallback(callback);
442
+ };
443
+ /**
444
+ * Removes the function from the list of registerd handlers for 'query changed' event
445
+ * @param callback
446
+ */
447
+ EqContext.prototype.removeQueryChangedCallback = function (callback) {
448
+ this.getQuery().removeChangedCallback(callback);
449
+ };
450
+ /**
451
+ * Creates a new query object using the current instance of EqServices
452
+ */
453
+ EqContext.prototype.createQuery = function () {
454
+ return this.eqServices.createQuery();
455
+ };
456
+ /**
457
+ * Gets the current query
458
+ */
459
+ EqContext.prototype.getQuery = function () {
460
+ if (!this.query) {
461
+ if (!this.servicesInitialized) {
462
+ throw new Error("Can't create query until the context is initialized");
463
+ }
464
+ this.query = this.createQuery();
465
+ }
466
+ return this.query;
467
+ };
468
+ /**
469
+ * Gets the current data model
470
+ */
471
+ EqContext.prototype.getModel = function () {
472
+ if (!this.dataModel) {
473
+ this.dataModel = this.eqServices.createDataModel();
474
+ }
475
+ return this.dataModel;
476
+ };
477
+ /**
478
+ * Sets the content of the current data model
479
+ */
480
+ EqContext.prototype.loadModelFromData = function (modelPlainData) {
481
+ this.getQuery().loadModelData(modelPlainData);
482
+ this.dataModel = this.getQuery().getModel();
483
+ };
484
+ /**
485
+ * Sets the ID of the default model
486
+ * @param modelId
487
+ */
488
+ EqContext.prototype.setDefaultModelId = function (modelId) {
489
+ this.defaultModelId = modelId;
490
+ };
491
+ /**
492
+ * Notifies context components about starting of some long process (e.g. model loading)
493
+ * This method raises onProcessStart event in the context and all its widgets
494
+ * @param message
495
+ * @param groups
496
+ */
497
+ EqContext.prototype.startProcess = function (message, groups) {
498
+ this.eventEmitter.fire('processStart', message);
499
+ this.widgets.forEach(function (widget) {
500
+ if (widget.belongsToGroup(groups)) {
501
+ widget.onProcessStart();
502
+ }
503
+ });
504
+ };
505
+ /**
506
+ * Notifies all context components about the finishing of some long process
507
+ * @param status
508
+ * @param groups
509
+ */
510
+ EqContext.prototype.endProcess = function (status, groups) {
511
+ this.eventEmitter.fire('processEnd', status);
512
+ if (status.result === EqActionResult.Error) {
513
+ this.throwError(status);
514
+ }
515
+ this.widgets.forEach(function (widget) {
516
+ if (widget.belongsToGroup(groups)) {
517
+ widget.onProcessEnd();
518
+ }
519
+ });
520
+ };
521
+ /**
522
+ * Throws the error passed in the function parameter.
523
+ * If onError event handler is defined - we call that method.
524
+ * Otherwise - just place the error message to the browser console.
525
+ * @param error
526
+ */
527
+ EqContext.prototype.throwError = function (status) {
528
+ status.result = EqActionResult.Error;
529
+ this.eventEmitter.fire('error', status);
530
+ };
531
+ /**
532
+ * If `defaultModelId` property is define - this method calls `loadModel` function in the broker
533
+ * to load the model with such ID.
534
+ */
535
+ EqContext.prototype.loadDefaultModel = function () {
536
+ var _this = this;
537
+ this.loadModel({
538
+ modelId: this.defaultModelId,
539
+ silent: true,
540
+ success: function () {
541
+ _this.refreshWidgets(WidgetGroup.Model);
542
+ var query = _this.getQuery();
543
+ _this.fireEvent('initialModelLoad');
544
+ if (_this.initialQuery) {
545
+ query.loadFromData(_this.initialQuery, {
546
+ changeStatus: false
547
+ });
548
+ }
549
+ if (_this.loadQueryOnStart) {
550
+ _this.loadQuery({
551
+ queryId: _this.defaultQueryId,
552
+ modelId: _this.defaultModelId,
553
+ success: function () {
554
+ _this.refreshWidgets(WidgetGroup.Query);
555
+ //if we load query on start - then we should call 'ready' event only after its successful loading
556
+ _this.fireEvent('ready');
557
+ }
558
+ });
559
+ }
560
+ else {
561
+ _this.refreshWidgets(WidgetGroup.Query);
562
+ _this.fireEvent('ready');
563
+ }
564
+ }
565
+ });
566
+ };
567
+ /**
568
+ * Clears the content of the current query
569
+ */
570
+ EqContext.prototype.clearQuery = function () {
571
+ var query = this.getQuery();
572
+ query.clear();
573
+ query.fireChangedEvent({
574
+ part: QueryChangePart.All
575
+ });
576
+ };
577
+ /**
578
+ * Clears all query results (the data set and the statement, if any)
579
+ */
580
+ EqContext.prototype.clearResult = function () {
581
+ this.resultTable.clear(); // do not set resultTable to null. Just clear
582
+ this.resultStatement = null;
583
+ this.resultContent = null;
584
+ };
585
+ /**
586
+ * Sets the external 'list cache' provider - an object which implements `ExternalListCache` inteface
587
+ * @param cache
588
+ */
589
+ EqContext.prototype.setExternalListCache = function (cache) {
590
+ this.externalListCache = cache;
591
+ };
592
+ EqContext.prototype.getListFromCache = function (params) {
593
+ var key = this.getListCacheKey(params);
594
+ if (this.externalListCache) {
595
+ return this.externalListCache.get(key);
596
+ }
597
+ else {
598
+ return this.internalListCache[key];
599
+ }
600
+ };
601
+ EqContext.prototype.getListCacheKey = function (params) {
602
+ var key = params.listName == 'SQL' ? 'SQL_' + params.editorId : params.listName;
603
+ if (params.queryParams) {
604
+ key += '_' + Object.keys(params.queryParams).filter(function (k) { return k != 'listName'; })
605
+ .map(function (k) { return params.queryParams[k]; })
606
+ .join('_');
607
+ }
608
+ return key;
609
+ };
610
+ EqContext.prototype.addListToCache = function (params, list) {
611
+ var key = this.getListCacheKey(params);
612
+ if (this.externalListCache) {
613
+ this.externalListCache.set(key, list);
614
+ }
615
+ else {
616
+ this.internalListCache[key] = list;
617
+ }
618
+ };
619
+ /**
620
+ * Clears the current list cache.
621
+ */
622
+ EqContext.prototype.resetListCache = function () {
623
+ if (this.externalListCache) {
624
+ this.externalListCache.clear();
625
+ }
626
+ else {
627
+ this.internalListCache = {};
628
+ }
629
+ };
630
+ /**
631
+ * Gets the handler for 'GetList' requests
632
+ */
633
+ EqContext.prototype.getListRequestHandler = function () {
634
+ return this._listRequestHandler;
635
+ };
636
+ /**
637
+ * Adds the translations of the EasyQuery messages for some locale
638
+ * @param locale - the ISO code of the locale (like `en` or `uk`)
639
+ * @param localeInfo - Locale settings and translations of EasyQuery texts and messages.
640
+ * We expected an object with the struture of LocaleInfo interface here.
641
+ */
642
+ EqContext.prototype.addLocale = function (locale, localeInfo) {
643
+ i18n.addLocale(locale, localeInfo);
644
+ };
645
+ EqContext.prototype.addEventListener = function (eventType, handler) {
646
+ var _this = this;
647
+ return this.eventEmitter.subscribe(eventType, function (event) { return handler(_this, event.data); });
648
+ };
649
+ /**
650
+ * Remove event handler for event type .
651
+ * @param eventType The event type.
652
+ * @param handlerId The handler id.
653
+ */
654
+ EqContext.prototype.removeEventListener = function (eventType, handlerId) {
655
+ this.eventEmitter.unsubscribe(eventType, handlerId);
656
+ };
657
+ EqContext.prototype.fireEvent = function (eventType, data) {
658
+ this.eventEmitter.fire(eventType, data);
659
+ };
660
+ EqContext.prototype.getBaseEndpoint = function () {
661
+ return this.baseEndpoint;
662
+ };
663
+ /**
664
+ * Sends a `loadValueList` requesthe server and processes the response.
665
+ * @param options A map of options to pass to `loadValueList` function.
666
+ */
667
+ EqContext.prototype.loadValueList = function (options) {
668
+ var _this = this;
669
+ options = options || {};
670
+ this.startProcess({
671
+ action: EqAction.GetValueList,
672
+ text: 'Loading values'
673
+ }, WidgetGroup.Result);
674
+ var valueListResolver = this.eqServices.getValueListResolver();
675
+ valueListResolver.loadValueList(options)
676
+ .then(function (values) {
677
+ _this.endProcess({
678
+ result: EqActionResult.Success,
679
+ action: EqAction.GetValueList,
680
+ text: 'Values loaded'
681
+ }, WidgetGroup.Result);
682
+ if (options.success) {
683
+ options.success(values);
684
+ }
685
+ })
686
+ .catch(function (error) {
687
+ var editorId = options && options.params ? options.params.editorId : 'undefined';
688
+ var errorMessage = "Can't load the value list for editor ".concat(editorId, ".\n ").concat(error.message);
689
+ _this.endProcess({
690
+ result: EqActionResult.Error,
691
+ action: EqAction.GetValueList,
692
+ text: errorMessage,
693
+ sourceError: error
694
+ }, WidgetGroup.Result);
695
+ if (options.error) {
696
+ options.error(errorMessage, 'GetValueList');
697
+ }
698
+ });
699
+ };
700
+ /**
701
+ * Starts the process of the model loading.
702
+ * This method can initiate a request to EasyQueryServer backend or get the model from OData or GraphQL endpoint
703
+ * The content of the `options` parameter depends on concrete loader implementation.
704
+ * @param options A map of options to pass to `loadModel` function (can be ommited)
705
+ * @example
706
+ * context.loadModel()
707
+ * .then(model => {
708
+ * alert("Model loaded!");
709
+ * });
710
+ */
711
+ EqContext.prototype.loadModel = function (options) {
712
+ var _this = this;
713
+ if (this.beforeLoadModel) {
714
+ this.beforeLoadModel(this, options);
715
+ }
716
+ var modelId = options.modelId || '__default';
717
+ var silent = options.silent || false;
718
+ this.startProcess({
719
+ action: EqAction.LoadModel,
720
+ text: 'Loading model: ' + modelId
721
+ }, WidgetGroup.Model);
722
+ var modelLoader = this.eqServices.getModelLoader();
723
+ return modelLoader.startModelLoading(options)
724
+ .then(function (value) {
725
+ if (value) {
726
+ _this.loadModelFromData(value);
727
+ if (_this.dataModel.isEmpty()) {
728
+ console.warn("Empty model has been loaded. Model ID: ".concat(_this.dataModel.getId()));
729
+ }
730
+ }
731
+ else {
732
+ console.warn('Model has not been changed.');
733
+ }
734
+ _this.fireEvent('loadModel');
735
+ _this.endProcess({
736
+ result: EqActionResult.Success,
737
+ action: EqAction.LoadModel,
738
+ text: 'Model loaded: ' + modelId
739
+ }, WidgetGroup.Model);
740
+ if (!silent) {
741
+ _this.clearQuery();
742
+ _this.clearResult();
743
+ _this.refreshWidgets();
744
+ }
745
+ if (options.success) {
746
+ options.success(_this.getModel());
747
+ }
748
+ return _this.getModel();
749
+ })
750
+ .catch(function (error) {
751
+ var errorMessage = "Can't load model ".concat(modelId, ".\n ").concat(error.message);
752
+ _this.endProcess({
753
+ result: EqActionResult.Error,
754
+ action: EqAction.LoadModel,
755
+ text: errorMessage,
756
+ sourceError: error
757
+ }, WidgetGroup.Model);
758
+ if (options.error) {
759
+ options.error(errorMessage, "LoadModel");
760
+ }
761
+ return _this.getModel();
762
+ });
763
+ };
764
+ EqContext.prototype.callWhenModelLoaded = function (callFunc) {
765
+ var modelLoader = this.eqServices.getModelLoader();
766
+ modelLoader.getModelPromise().then(function () {
767
+ callFunc();
768
+ });
769
+ };
770
+ /**
771
+ * Loads the query
772
+ * @param options
773
+ * The content of the `options` parameter depends on `QueryStorage` implementation.
774
+ * Usually it contains `success`, `error` callbacks and `queryId` property of the query to load.
775
+ * @example
776
+ * context.loadQuery({
777
+ * queryId: "query-id"
778
+ * });
779
+ */
780
+ EqContext.prototype.loadQuery = function (options) {
781
+ var _this = this;
782
+ options = options || {};
783
+ var modelLoader = this.eqServices.getModelLoader();
784
+ this.clearResult();
785
+ modelLoader.getModelPromise()
786
+ .then(function () {
787
+ options = options || {};
788
+ var queryId = options.queryId;
789
+ var silent = options.silent || false;
790
+ if (_this.beforeLoadQuery) {
791
+ _this.beforeLoadQuery(_this, options);
792
+ }
793
+ _this.startProcess({
794
+ action: EqAction.LoadQuery,
795
+ text: "Query loading: " + queryId
796
+ }, WidgetGroup.Query);
797
+ var queryStorage = _this.eqServices.getQueryStorage();
798
+ queryStorage.loadQuery(options)
799
+ .then(function (data) {
800
+ if (data) {
801
+ _this.query.loadFromData(data, {
802
+ validate: false
803
+ });
804
+ }
805
+ _this.fireEvent('loadQuery');
806
+ _this.endProcess({
807
+ result: EqActionResult.Success,
808
+ action: EqAction.LoadQuery,
809
+ text: 'Query loaded: ' + queryId
810
+ }, WidgetGroup.Query);
811
+ _this.query.resetModified();
812
+ if (!silent) {
813
+ _this.query.fireChangedEvent({
814
+ part: QueryChangePart.Properties,
815
+ wasModified: _this.query.isModified()
816
+ });
817
+ _this.refreshWidgets();
818
+ }
819
+ if (options.success) {
820
+ options.success(_this.query);
821
+ }
822
+ })
823
+ .catch(function (error) {
824
+ var query = _this.getQuery();
825
+ error.message = "Can't load query [" + query.getId() + "]\n" + (error.message || "");
826
+ if (options.error) {
827
+ options.error(error.message, EqAction.LoadQuery);
828
+ }
829
+ _this.endProcess({
830
+ result: EqActionResult.Error,
831
+ action: EqAction.LoadQuery,
832
+ text: error.message,
833
+ sourceError: error
834
+ }, WidgetGroup.Query);
835
+ });
836
+ })
837
+ .catch(function (error) {
838
+ console.error(error);
839
+ });
840
+ };
841
+ /**
842
+ * Loads the list of queries available for the current user.
843
+ * @param options
844
+ * The content of the `options` parameter depends on `QueryStorage` implementation.
845
+ * Usually it contains `success`, `error` callbacks
846
+ */
847
+ EqContext.prototype.loadQueryList = function (options) {
848
+ var _this = this;
849
+ var modelLoader = this.eqServices.getModelLoader();
850
+ modelLoader.getModelPromise()
851
+ .then(function () {
852
+ _this.startQueryListLoading(options);
853
+ })
854
+ .catch(function (error) {
855
+ var errorMessage = "Can't load the list of available queries.\n ".concat(error.message);
856
+ _this.throwError({
857
+ action: EqAction.LoadQueryList,
858
+ text: errorMessage,
859
+ sourceError: error
860
+ });
861
+ });
862
+ };
863
+ EqContext.prototype.startQueryListLoading = function (options) {
864
+ var _this = this;
865
+ options = options || {};
866
+ var queryStorage = this.eqServices.getQueryStorage();
867
+ var queryListLoadingPromise = queryStorage.getQueryList(options);
868
+ queryListLoadingPromise
869
+ .then(function (queries) {
870
+ if (options.success) {
871
+ options.success(queries);
872
+ }
873
+ })
874
+ .catch(function (error) {
875
+ var errorMessage = "Can't load the list of available queries.\n ".concat(error.message);
876
+ if (options.error) {
877
+ options.error(errorMessage, 'LoadQueryList');
878
+ }
879
+ else {
880
+ _this.throwError({
881
+ action: EqAction.LoadQueryList,
882
+ text: errorMessage,
883
+ sourceError: error
884
+ });
885
+ }
886
+ });
887
+ };
888
+ /**
889
+ * Creates a new query and returns its content back to the client-side.
890
+ * @param options
891
+ * The content of the `options` parameter depends on `QueryStorage` implementation.
892
+ * Usually it contains `success`, `error` callbacks and `silent` option
893
+ * @example
894
+ * context.newQuery({
895
+ * silent: true
896
+ * });
897
+ */
898
+ EqContext.prototype.newQuery = function (options) {
899
+ var _this = this;
900
+ options = options || {};
901
+ var clearQuery = typeof options.clearQuery !== 'undefined' ? options.clearQuery : true;
902
+ this.query.reset(clearQuery);
903
+ if (options.queryId) {
904
+ this.query.setId(options.queryId);
905
+ }
906
+ if (options.name) {
907
+ this.query.setName(options.name);
908
+ }
909
+ if (options.description) {
910
+ this.query.setDescription(options.description);
911
+ }
912
+ var silent = options.silent || false;
913
+ var useStorage = true;
914
+ if (typeof options.useStorage !== 'undefined') {
915
+ useStorage = options.useStorage;
916
+ }
917
+ var onNewQuery = function () {
918
+ var query = _this.getQuery();
919
+ query.isNewbie = true;
920
+ if (!silent) {
921
+ query.fireChangedEvent({
922
+ part: QueryChangePart.All,
923
+ wasModified: query.isModified()
924
+ });
925
+ }
926
+ };
927
+ if (useStorage) {
928
+ this.startProcess({
929
+ action: EqAction.NewQuery,
930
+ text: 'New query creation...'
931
+ }, WidgetGroup.Query);
932
+ var queryStorage = this.eqServices.getQueryStorage();
933
+ queryStorage.newQuery(options)
934
+ .then(function (queryData) {
935
+ if (queryData) {
936
+ _this.query.loadFromData(queryData);
937
+ }
938
+ _this.endProcess({
939
+ result: EqActionResult.Success,
940
+ action: EqAction.NewQuery,
941
+ text: 'A new query has been created'
942
+ }, WidgetGroup.Query);
943
+ onNewQuery();
944
+ if (options.success) {
945
+ options.success();
946
+ }
947
+ })
948
+ .catch(function (error) {
949
+ var errorMessage = "Can't create a new query.\n".concat(error.message);
950
+ _this.endProcess({
951
+ result: EqActionResult.Error,
952
+ action: EqAction.NewQuery,
953
+ text: errorMessage,
954
+ sourceError: error
955
+ }, WidgetGroup.Query);
956
+ if (options.error) {
957
+ options.error(errorMessage, "NewQuery");
958
+ }
959
+ });
960
+ }
961
+ else {
962
+ onNewQuery();
963
+ }
964
+ return this.query;
965
+ };
966
+ /**
967
+ * Saves the current query to some storage on the server-side.
968
+ * @param options
969
+ * The content of the `options` parameter depends on `QueryStorage` implementation.
970
+ * Usually it contains `success` and `error` callbacks
971
+ */
972
+ EqContext.prototype.saveQuery = function (options) {
973
+ var _this = this;
974
+ options = options || {};
975
+ var query = this.getQuery();
976
+ this.startProcess({
977
+ action: EqAction.SaveQuery,
978
+ text: 'Query saving: ' + query.getId()
979
+ }, WidgetGroup.Query);
980
+ var queryStorage = this.eqServices.getQueryStorage();
981
+ queryStorage.saveQuery(options)
982
+ .then(function (data) {
983
+ _this.endProcess({
984
+ action: EqAction.SaveQuery,
985
+ result: EqActionResult.Success,
986
+ text: "Query saved: " + query.getId()
987
+ }, WidgetGroup.Query);
988
+ if (data) {
989
+ query.loadFromData(data);
990
+ }
991
+ query.resetModified();
992
+ query.isNewbie = false;
993
+ if (options.success) {
994
+ options.success();
995
+ }
996
+ })
997
+ .catch(function (error) {
998
+ var errorMessage = "Can't save query ".concat(query.getId(), ".\n ").concat(error.message);
999
+ _this.endProcess({
1000
+ action: EqAction.SaveQuery,
1001
+ result: EqActionResult.Error,
1002
+ text: errorMessage,
1003
+ sourceError: error
1004
+ }, WidgetGroup.Query);
1005
+ if (options.error) {
1006
+ options.error(errorMessage, EqAction.SaveQuery);
1007
+ }
1008
+ });
1009
+ };
1010
+ /**
1011
+ * Removes the current query from some storage on the server-side.
1012
+ * @param options
1013
+ * The content of the `options` parameter depends on `QueryStorage` implementation.
1014
+ * Usually it contains `success` and `error` callbacks
1015
+ */
1016
+ EqContext.prototype.removeQuery = function (options) {
1017
+ var _this = this;
1018
+ options = options || {};
1019
+ var query = this.getQuery();
1020
+ this.startProcess({
1021
+ action: EqAction.RemoveQuery,
1022
+ text: 'Query deleting: ' + query.getId()
1023
+ }, WidgetGroup.Query);
1024
+ var queryStorage = this.eqServices.getQueryStorage();
1025
+ queryStorage.removeQuery(options)
1026
+ .then(function () {
1027
+ query.reset();
1028
+ _this.endProcess({
1029
+ action: EqAction.RemoveQuery,
1030
+ result: EqActionResult.Success,
1031
+ text: "Query deleted: " + query.getId()
1032
+ }, WidgetGroup.Query);
1033
+ if (options.success) {
1034
+ options.success();
1035
+ }
1036
+ })
1037
+ .catch(function (error) {
1038
+ var errorMessage = "Can't remove query ".concat(query.getId(), ".\n ").concat(error.message);
1039
+ _this.endProcess({
1040
+ action: EqAction.RemoveQuery,
1041
+ result: EqActionResult.Error,
1042
+ text: errorMessage,
1043
+ sourceError: error
1044
+ }, WidgetGroup.Query);
1045
+ if (options.error) {
1046
+ options.error(errorMessage, 'RemoveQuery');
1047
+ }
1048
+ });
1049
+ };
1050
+ /**
1051
+ * Syncronizes the current query.
1052
+ * @param options
1053
+ * The content of the `options` parameter depends on `QuerySyncronizer` implementation.
1054
+ * Usually it contains `success` and `error` callbacks
1055
+ */
1056
+ EqContext.prototype.syncQuery = function (options) {
1057
+ var _this = this;
1058
+ options = options || {};
1059
+ var query = this.getQuery();
1060
+ if (this.beforeSyncQuery) {
1061
+ this.beforeSyncQuery(this, options);
1062
+ }
1063
+ this.startProcess({
1064
+ action: EqAction.SyncQuery,
1065
+ text: 'Query syncing: ' + query.getId()
1066
+ }, WidgetGroup.Query);
1067
+ var querySyncrhonizer = this.eqServices.getQuerySynchronizer();
1068
+ querySyncrhonizer.syncQuery(options)
1069
+ .then(function (result) {
1070
+ _this.resultStatement = result && result.statement
1071
+ ? result.statement
1072
+ : '';
1073
+ _this.fireEvent('syncQuery');
1074
+ _this.refreshWidgets(WidgetGroup.Statement);
1075
+ _this.endProcess({
1076
+ result: EqActionResult.Success,
1077
+ action: EqAction.SyncQuery,
1078
+ text: 'Query synced: ' + query.getId()
1079
+ }, WidgetGroup.Query);
1080
+ if (result) {
1081
+ if (result.querySaved) {
1082
+ var q = result.query;
1083
+ if (q) {
1084
+ query.setId(q.id);
1085
+ query.setName(q.name);
1086
+ query.setDescription(q.desc);
1087
+ query.extraData = q.extraData;
1088
+ }
1089
+ query.resetModified();
1090
+ _this.refreshWidgets(WidgetGroup.QueryStatus);
1091
+ }
1092
+ if (options.success) {
1093
+ options.success(result);
1094
+ }
1095
+ }
1096
+ })
1097
+ .catch(function (error) {
1098
+ var errorMessage = "Can't synchronize query ".concat(query.getId(), ".\n ").concat(error.message);
1099
+ _this.endProcess({
1100
+ result: EqActionResult.Error,
1101
+ action: EqAction.SyncQuery,
1102
+ text: errorMessage,
1103
+ sourceError: error
1104
+ }, WidgetGroup.Query);
1105
+ if (options.error) {
1106
+ options.error(errorMessage, 'SyncQuery');
1107
+ }
1108
+ });
1109
+ };
1110
+ /**
1111
+ * Fetches the data (usuall by executing current query) and processes the result.
1112
+ * @param options
1113
+ * The `options` parameter in addition to the options defined in FetchDataOptions structure may also contain `success` and `error` callbacks.
1114
+ * @example
1115
+ * context.fetchData({ success: function(result) {
1116
+ * //do whatever you want with the result
1117
+ * }})
1118
+ *
1119
+ */
1120
+ EqContext.prototype.fetchData = function (options) {
1121
+ var _this = this;
1122
+ options = options || {};
1123
+ var elasticPaging = typeof (options.elasticPaging) !== 'undefined'
1124
+ ? options.elasticPaging
1125
+ : this.elasticPaging;
1126
+ this.resultTable.elasticChunks = elasticPaging;
1127
+ options.chunk = options.chunk ||
1128
+ {
1129
+ offset: 0,
1130
+ limit: this.resultTable.chunkSize,
1131
+ needTotal: !elasticPaging
1132
+ };
1133
+ if (this.debugMode) {
1134
+ options.debug = 'Fetching the result set. Initial chunk';
1135
+ }
1136
+ if (!this.query.tryValidate({
1137
+ checkExpressions: true
1138
+ })) {
1139
+ return;
1140
+ }
1141
+ //just to support the old way of catching "group fetch" operation finish
1142
+ if (options.groupFetchSuccess) {
1143
+ this.afterGroupFetch = options.groupFetchSuccess;
1144
+ }
1145
+ if (this.resultTable.elasticChunks) {
1146
+ options.chunk.limit++;
1147
+ }
1148
+ this.fetchDataChunk(__assign(__assign({}, options), { success: function (result) {
1149
+ if (result.statement) {
1150
+ _this.resultStatement = result.statement;
1151
+ _this.refreshWidgets(WidgetGroup.Statement);
1152
+ }
1153
+ var aggrCalculator = _this.getServices().getAggregatesCalculator();
1154
+ aggrCalculator.reset();
1155
+ _this.resultContent = result;
1156
+ if (result.resultSet) {
1157
+ _this.resultTable.clear();
1158
+ _this.resultTable.id = _this.query.getId();
1159
+ var resultSet = result.resultSet;
1160
+ for (var _i = 0, _a = resultSet.cols; _i < _a.length; _i++) {
1161
+ var col = _a[_i];
1162
+ _this.resultTable.columns.add(col);
1163
+ }
1164
+ if (result.meta && typeof (result.meta.totalRecords) !== 'undefined') {
1165
+ _this.resultTable.setTotal(result.meta.totalRecords);
1166
+ }
1167
+ var count = resultSet.rows.length;
1168
+ if (_this.resultTable.elasticChunks && count === options.chunk.limit) {
1169
+ resultSet.rows.splice(resultSet.rows.length - 1, 1);
1170
+ }
1171
+ for (var _b = 0, _c = resultSet.rows; _b < _c.length; _b++) {
1172
+ var row = _c[_b];
1173
+ _this.resultTable.addRow(row);
1174
+ }
1175
+ if (_this.resultTable.elasticChunks) {
1176
+ _this.resultTable['total'] = (count < options.chunk.limit)
1177
+ ? resultSet.rows.length
1178
+ : 0;
1179
+ }
1180
+ _this.resultTable.fireUpdated();
1181
+ }
1182
+ if (options.success) {
1183
+ options.success(result);
1184
+ }
1185
+ } }));
1186
+ };
1187
+ EqContext.prototype.getQueryFile = function (options) {
1188
+ var _this = this;
1189
+ var query = this.getQuery();
1190
+ this.startProcess({
1191
+ action: EqAction.GetQueryFile,
1192
+ text: 'Getting query file: ' + query.getId()
1193
+ }, WidgetGroup.Query);
1194
+ var queryFileLoader = this.getServices().getQueryFileLoader();
1195
+ queryFileLoader.getQueryFile(options)
1196
+ .then(function () {
1197
+ _this.endProcess({
1198
+ result: EqActionResult.Success,
1199
+ action: EqAction.GetQueryFile,
1200
+ text: 'Getting query file: ' + query.getId()
1201
+ }, WidgetGroup.Query);
1202
+ if (options.success) {
1203
+ options.success();
1204
+ }
1205
+ })
1206
+ .catch(function (error) {
1207
+ var errorMessage = "Can't get file for query ".concat(query.getId(), ".\n ").concat(error.message);
1208
+ _this.endProcess({
1209
+ result: EqActionResult.Error,
1210
+ action: EqAction.GetQueryFile,
1211
+ text: errorMessage,
1212
+ sourceError: error
1213
+ }, WidgetGroup.Query);
1214
+ if (options.error) {
1215
+ options.error(errorMessage, 'GetQueryFile');
1216
+ }
1217
+ });
1218
+ };
1219
+ EqContext.prototype.uploadQueryFile = function (options) {
1220
+ var _this = this;
1221
+ var query = this.getQuery();
1222
+ this.startProcess({
1223
+ action: EqAction.UploadQueryFile,
1224
+ text: 'Uploading query file: ' + query.getId()
1225
+ }, WidgetGroup.Query);
1226
+ var queryFileLoader = this.getServices().getQueryFileLoader();
1227
+ queryFileLoader.uploadQueryFile(options)
1228
+ .then(function (data) {
1229
+ query.loadFromData(data);
1230
+ _this.fireEvent('loadQuery');
1231
+ _this.refreshWidgets();
1232
+ _this.endProcess({
1233
+ result: EqActionResult.Success,
1234
+ action: EqAction.UploadQueryFile,
1235
+ text: 'Uploading query file: ' + query.getId()
1236
+ }, WidgetGroup.Query);
1237
+ if (options.success) {
1238
+ options.success();
1239
+ }
1240
+ })
1241
+ .catch(function (error) {
1242
+ var errorMessage = "Can't upload a file for query ".concat(query.getId(), ".\n ").concat(error.message);
1243
+ _this.endProcess({
1244
+ result: EqActionResult.Error,
1245
+ action: EqAction.UploadQueryFile,
1246
+ text: errorMessage,
1247
+ sourceError: error
1248
+ }, WidgetGroup.Query);
1249
+ if (options.error) {
1250
+ options.error(errorMessage, 'UploadQueryFile');
1251
+ }
1252
+ });
1253
+ };
1254
+ EqContext.prototype.fetchDataChunk = function (options) {
1255
+ var _this = this;
1256
+ var queryId = this.getQuery().getId();
1257
+ var fetchOptions = options || {};
1258
+ if (this.useStoredQueryOnFetch) {
1259
+ fetchOptions.queryId = this.query.getId();
1260
+ }
1261
+ if (this.beforeFetchData) {
1262
+ this.beforeFetchData(this, fetchOptions);
1263
+ }
1264
+ this.startProcess({
1265
+ action: EqAction.FetchData,
1266
+ text: 'Fetching data for the query: ' + queryId
1267
+ }, WidgetGroup.Result);
1268
+ var dataFetcher = this.eqServices.getDataFetcher();
1269
+ dataFetcher.fetchData(fetchOptions)
1270
+ .then(function (result) {
1271
+ if (result.statement) {
1272
+ _this.resultStatement = result.statement;
1273
+ }
1274
+ _this.resultContent = result;
1275
+ // we need to call success callback before firing fetchData,
1276
+ // because otherwise, it won't update the result table
1277
+ // in the context before afterFetchData callback is called.
1278
+ if (fetchOptions.success) {
1279
+ fetchOptions.success(result);
1280
+ }
1281
+ _this.fireEvent('fetchData');
1282
+ _this.endProcess({
1283
+ result: EqActionResult.Success,
1284
+ action: EqAction.FetchData,
1285
+ text: 'Data fetching is finished for the query: ' + queryId
1286
+ }, WidgetGroup.Result);
1287
+ })
1288
+ .catch(function (error) {
1289
+ var errorMessage = "Data fetching error for the query ".concat(queryId, ". \n").concat(error.message);
1290
+ _this.endProcess({
1291
+ result: EqActionResult.Error,
1292
+ action: EqAction.FetchData,
1293
+ text: errorMessage,
1294
+ sourceError: error
1295
+ }, WidgetGroup.Result);
1296
+ if (fetchOptions.error) {
1297
+ fetchOptions.error(errorMessage, EqAction.FetchData);
1298
+ }
1299
+ });
1300
+ };
1301
+ EqContext.prototype.onResultTableUpdate = function () {
1302
+ var _this = this;
1303
+ var aggrSettings = this.query.getAggregationSettings();
1304
+ var calculator = this.getServices().getAggregatesCalculator();
1305
+ if (aggrSettings.needAggrCalculation() && calculator.needRecalculation()) {
1306
+ calculator.calculate({
1307
+ maxLevel: aggrSettings.getGroups().length + 1,
1308
+ resultObtained: function (result, level) {
1309
+ if (_this.afterGroupFetch) {
1310
+ _this.afterGroupFetch(result);
1311
+ }
1312
+ },
1313
+ errorOccurred: function (error) {
1314
+ var errorMessage = "Data fetching error on group level ".concat(error.level, " query. \n").concat(error.message);
1315
+ _this.throwError({
1316
+ action: EqAction.FetchData,
1317
+ text: errorMessage,
1318
+ sourceError: error
1319
+ });
1320
+ }
1321
+ });
1322
+ }
1323
+ };
1324
+ /**
1325
+ * Fetches the data for a drill-down query (if defined) and processes the result.
1326
+ * @param options
1327
+ */
1328
+ EqContext.prototype.fetchDrillDownData = function (options) {
1329
+ var _this = this;
1330
+ options = options || {};
1331
+ options.chunk = options.chunk ||
1332
+ {
1333
+ offset: 0,
1334
+ limit: this.resultTable.chunkSize,
1335
+ needTotal: true
1336
+ };
1337
+ var query = options.query;
1338
+ var queryId = query.getId();
1339
+ this.startProcess({
1340
+ action: EqAction.FetchData,
1341
+ text: 'DrillDown executing: ' + queryId
1342
+ }, WidgetGroup.Result);
1343
+ var queryExecutor = this.eqServices.getDataFetcher();
1344
+ queryExecutor.fetchData(options)
1345
+ .then(function (result) {
1346
+ _this.endProcess({
1347
+ result: EqActionResult.Success,
1348
+ action: EqAction.FetchData,
1349
+ text: 'DrillDown execution error: ' + queryId
1350
+ }, WidgetGroup.Result);
1351
+ if (options.success) {
1352
+ options.success(result);
1353
+ }
1354
+ })
1355
+ .catch(function (error) {
1356
+ var errorMessage = "Drill-down data fetching error for query ".concat(queryId, ". \n").concat(error.message);
1357
+ _this.endProcess({
1358
+ result: EqActionResult.Error,
1359
+ action: EqAction.FetchData,
1360
+ text: errorMessage,
1361
+ }, WidgetGroup.Result);
1362
+ if (options.error) {
1363
+ options.error(errorMessage, 'DrillDown');
1364
+ }
1365
+ else {
1366
+ _this.throwError({
1367
+ action: EqAction.FetchData,
1368
+ text: errorMessage
1369
+ });
1370
+ }
1371
+ });
1372
+ };
1373
+ /**
1374
+ * Fetches the data for defined by this context and exports them to the specified format.
1375
+ * @param options
1376
+ * The content of the `options` parameter depends on `EqExporter` implementation.
1377
+ * Usually it contains `format` property which defines the format of the exported data (e.g. `csv`),
1378
+ * and `success` and `error` callbacks
1379
+ * @example
1380
+ * context.exportResult({
1381
+ * format: csv
1382
+ * });
1383
+ *
1384
+ */
1385
+ EqContext.prototype.exportResult = function (options) {
1386
+ var _this = this;
1387
+ options = options || {};
1388
+ if (this.beforeExportResult) {
1389
+ this.beforeExportResult(this, options);
1390
+ }
1391
+ var format = options.format;
1392
+ if (format) {
1393
+ var exporter = this.getExporter(format);
1394
+ if (exporter) {
1395
+ var queryId_1 = this.getQuery().getId();
1396
+ if (this.useStoredQueryOnFetch) {
1397
+ options.queryId = queryId_1;
1398
+ }
1399
+ this.startProcess({
1400
+ action: EqAction.ExportResult,
1401
+ text: 'Exporting result for query: ' + queryId_1
1402
+ }, WidgetGroup.Result);
1403
+ var localeSettings = i18n.getLocaleSettings();
1404
+ options.settings = localeSettings;
1405
+ var aggrSettings = this.query.getAggregationSettings();
1406
+ if (aggrSettings.hasAggregates()
1407
+ && (aggrSettings.hasGrandTotals() || aggrSettings.hasGroups())) {
1408
+ options.aggregates = aggrSettings.saveToData();
1409
+ }
1410
+ exporter.export(options)
1411
+ .then(function (result) {
1412
+ _this.fireEvent('exportResult');
1413
+ _this.endProcess({
1414
+ result: EqActionResult.Success,
1415
+ action: EqAction.ExportResult,
1416
+ text: "The result set for query [".concat(queryId_1, "] has been successfully exported")
1417
+ }, WidgetGroup.Result);
1418
+ if (options.success) {
1419
+ options.success();
1420
+ }
1421
+ })
1422
+ .catch(function (error) {
1423
+ var errorMessage = "Error on exporting data for query ".concat(queryId_1, ". \n").concat(error.message);
1424
+ _this.endProcess({
1425
+ result: EqActionResult.Error,
1426
+ action: EqAction.ExportResult,
1427
+ text: errorMessage,
1428
+ sourceError: error
1429
+ }, WidgetGroup.Result);
1430
+ if (options.error) {
1431
+ options.error(errorMessage, 'ExportResult');
1432
+ }
1433
+ });
1434
+ }
1435
+ }
1436
+ };
1437
+ return EqContext;
1438
+ }());
1439
+ export { EqContext };
1439
1440
  //# sourceMappingURL=context.js.map