@easyquery/core 7.2.3 → 7.2.4-rc01

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