@easyquery/core 7.2.3 → 7.2.4-beta03

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/bundles/easyquery.core.js +9353 -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 +57 -54
  49. package/dist/lib/eqs/eqs_exporter.js.map +1 -1
  50. package/dist/lib/eqs/eqs_model_loader.d.ts +7 -7
  51. package/dist/lib/eqs/eqs_model_loader.js +42 -40
  52. package/dist/lib/eqs/eqs_model_loader.js.map +1 -1
  53. package/dist/lib/eqs/eqs_query_file_loader.d.ts +9 -9
  54. package/dist/lib/eqs/eqs_query_file_loader.js +54 -54
  55. package/dist/lib/eqs/eqs_query_file_loader.js.map +1 -1
  56. package/dist/lib/eqs/eqs_query_synchronizer.d.ts +7 -7
  57. package/dist/lib/eqs/eqs_query_synchronizer.js +23 -23
  58. package/dist/lib/eqs/eqs_value_list_resolver.d.ts +7 -7
  59. package/dist/lib/eqs/eqs_value_list_resolver.js +28 -28
  60. package/dist/lib/export/exporter.d.ts +16 -16
  61. package/dist/lib/export/exporter.js +1 -0
  62. package/dist/lib/i18n/text_resources.d.ts +1 -1
  63. package/dist/lib/i18n/text_resources.js +26 -26
  64. package/dist/lib/i18n/text_resources.js.map +1 -1
  65. package/dist/lib/main/action.d.ts +13 -13
  66. package/dist/lib/main/action.js +5 -5
  67. package/dist/lib/main/context.d.ts +342 -342
  68. package/dist/lib/main/context.js +1439 -1439
  69. package/dist/lib/main/context.js.map +1 -1
  70. package/dist/lib/main/context_options.d.ts +145 -145
  71. package/dist/lib/main/context_options.js +1 -0
  72. package/dist/lib/main/data_fetcher.d.ts +46 -46
  73. package/dist/lib/main/data_fetcher.js +1 -0
  74. package/dist/lib/main/eq_actions.d.ts +14 -14
  75. package/dist/lib/main/eq_actions.js +15 -15
  76. package/dist/lib/main/list_cache.d.ts +8 -8
  77. package/dist/lib/main/list_cache.js +1 -0
  78. package/dist/lib/main/model_loader.d.ts +21 -21
  79. package/dist/lib/main/model_loader.js +32 -32
  80. package/dist/lib/main/model_storage.d.ts +13 -13
  81. package/dist/lib/main/model_storage.js +17 -17
  82. package/dist/lib/main/query_file_loader.d.ts +15 -15
  83. package/dist/lib/main/query_file_loader.js +1 -0
  84. package/dist/lib/main/query_storage.d.ts +58 -58
  85. package/dist/lib/main/query_storage.js +124 -124
  86. package/dist/lib/main/query_synchronizer.d.ts +9 -9
  87. package/dist/lib/main/query_synchronizer.js +1 -0
  88. package/dist/lib/main/value_list_resolver.d.ts +18 -18
  89. package/dist/lib/main/value_list_resolver.js +1 -0
  90. package/dist/lib/main/widget.d.ts +74 -74
  91. package/dist/lib/main/widget.js +101 -101
  92. package/dist/lib/public_api.d.ts +58 -58
  93. package/dist/lib/public_api.js +59 -42
  94. package/dist/lib/public_api.js.map +1 -1
  95. package/dist/lib/query/condition.d.ts +97 -97
  96. package/dist/lib/query/condition.js +331 -331
  97. package/dist/lib/query/descriptors.d.ts +36 -36
  98. package/dist/lib/query/descriptors.js +1 -0
  99. package/dist/lib/query/dto/condition_data.d.ts +38 -38
  100. package/dist/lib/query/dto/condition_data.js +1 -0
  101. package/dist/lib/query/dto/expression_data.d.ts +32 -32
  102. package/dist/lib/query/dto/expression_data.js +1 -0
  103. package/dist/lib/query/dto/query_column_data.d.ts +28 -28
  104. package/dist/lib/query/dto/query_column_data.js +1 -0
  105. package/dist/lib/query/dto/query_data.d.ts +27 -27
  106. package/dist/lib/query/dto/query_data.js +1 -0
  107. package/dist/lib/query/expression.d.ts +69 -69
  108. package/dist/lib/query/expression.js +202 -202
  109. package/dist/lib/query/query.d.ts +410 -410
  110. package/dist/lib/query/query.js +1393 -1391
  111. package/dist/lib/query/query.js.map +1 -1
  112. package/dist/lib/query/query_column.d.ts +70 -70
  113. package/dist/lib/query/query_column.js +157 -157
  114. package/dist/lib/query/query_events.d.ts +29 -29
  115. package/dist/lib/query/query_events.js +19 -19
  116. package/dist/lib/types/cond_part.d.ts +6 -6
  117. package/dist/lib/types/cond_part.js +7 -7
  118. package/dist/lib/types/cond_tag.d.ts +12 -12
  119. package/dist/lib/types/cond_tag.js +13 -13
  120. package/dist/lib/types/data_kind.d.ts +15 -15
  121. package/dist/lib/types/data_kind.js +16 -16
  122. package/dist/lib/types/eq_editor_tag.d.ts +17 -17
  123. package/dist/lib/types/eq_editor_tag.js +20 -20
  124. package/dist/lib/types/expr_tag.d.ts +19 -19
  125. package/dist/lib/types/expr_tag.js +20 -20
  126. package/dist/lib/types/link_type.d.ts +17 -17
  127. package/dist/lib/types/link_type.js +18 -18
  128. package/dist/lib/types/widget_group.d.ts +17 -17
  129. package/dist/lib/types/widget_group.js +18 -18
  130. package/dist/lib/utils/constants.d.ts +36 -36
  131. package/dist/lib/utils/constants.js +50 -50
  132. package/dist/lib/utils/format_parser.d.ts +40 -40
  133. package/dist/lib/utils/format_parser.js +87 -87
  134. package/dist/lib/utils/utils.d.ts +34 -34
  135. package/dist/lib/utils/utils.js +102 -102
  136. package/dist/lib/utils/version_info.d.ts +9 -9
  137. package/dist/lib/utils/version_info.js +12 -12
  138. package/dist/lib/utils/version_info.js.map +1 -1
  139. package/package.json +16 -16
  140. package/webpack.config.js +6 -5
@@ -1,1392 +1,1394 @@
1
- var __extends = (this && this.__extends) || (function () {
2
- var extendStatics = function (d, b) {
3
- extendStatics = Object.setPrototypeOf ||
4
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6
- return extendStatics(d, b);
7
- };
8
- return function (d, b) {
9
- extendStatics(d, b);
10
- function __() { this.constructor = d; }
11
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12
- };
13
- })();
14
- import { EventEmitter, utils as dataUtils, AggregationSettings, DataType } from '@easydata/core';
15
- import { i18n } from '@easydata/core';
16
- import { equtils } from '../utils/utils';
17
- import { DataModel } from '../dm/data_model';
18
- import { Expression } from './expression';
19
- import { QueryColumn, SortDirection } from './query_column';
20
- import { Condition } from './condition';
21
- import { DataKind } from '../types/data_kind';
22
- import { LinkType } from '../types/link_type';
23
- import { ExprTag } from '../types/expr_tag';
24
- import { CondTag } from '../types/cond_tag';
25
- import { QueryChangePart } from './query_events';
26
- /**
27
- * The error that appears when the query is not valid
28
- */
29
- var InvalidQueryError = /** @class */ (function (_super) {
30
- __extends(InvalidQueryError, _super);
31
- /**
32
- * Creates an instance of error type.
33
- * @param message The error message
34
- */
35
- function InvalidQueryError(message) {
36
- var _this = _super.call(this, message) || this;
37
- if (Error.captureStackTrace) {
38
- Error.captureStackTrace(_this, InvalidQueryError);
39
- }
40
- _this.name = 'InvalidQueryError';
41
- return _this;
42
- }
43
- return InvalidQueryError;
44
- }(Error));
45
- export { InvalidQueryError };
46
- /**
47
- * Represents Query.
48
- */
49
- var Query = /** @class */ (function () {
50
- /**
51
- * The default constructor.
52
- * @param model The data model.
53
- * @param data JSON representation object.
54
- * @param options The options.
55
- * @throws {InvalidQueryError} The error throws when query is not valid.
56
- */
57
- function Query(model, data, options) {
58
- var _this = this;
59
- /**
60
- * Contains user-defined extra data for current query.
61
- */
62
- this.extraData = {};
63
- this.innerData = {};
64
- this.isNewbie = true;
65
- this._isModified = false;
66
- this._enableAggregation = false;
67
- this.parentQuery = null;
68
- this.drillDowns = [];
69
- this.eventEmitter = new EventEmitter(this);
70
- this.root = new Condition(this, CondTag.Group);
71
- this.extraConditions = new Condition(this, CondTag.Group);
72
- this.columns = new Array();
73
- this.justsorted = new Array();
74
- if (!this.id) {
75
- this.regenerateId();
76
- }
77
- this.setDefaultName();
78
- this.description = "";
79
- this.model = (model) ? model : new DataModel();
80
- if (data) {
81
- this.loadFromData(data);
82
- }
83
- this.attributeExprTag = (options) ? options.attrTag || ExprTag.EntityAttribute : ExprTag.EntityAttribute;
84
- this.clientListRequestHandler = (options) ? options.clientListRequestHandler : new Array();
85
- this.serverListRequestHandler = (options) ? options.serverListRequestHandler : new Array();
86
- this.timezoneOffset = (new Date()).getTimezoneOffset();
87
- this.aggrSettings = new AggregationSettings(this);
88
- if (options) {
89
- this.parentQuery = options.parent;
90
- }
91
- this.addChangedCallback(function (ev) {
92
- if (ev.data
93
- && ((ev.data.part & QueryChangePart.Columns) > 0)
94
- && !ev.data.aggregation) {
95
- if (_this._enableAggregation && _this.updateAggregationSettings()) {
96
- _this.fireChangedEvent({
97
- part: QueryChangePart.Aggregation
98
- });
99
- }
100
- }
101
- });
102
- }
103
- Query.prototype.isModified = function () {
104
- return this._isModified;
105
- };
106
- Query.prototype.resetModified = function () {
107
- this._isModified = false;
108
- };
109
- Object.defineProperty(Query.prototype, "enableAggregation", {
110
- get: function () {
111
- return this._enableAggregation;
112
- },
113
- set: function (value) {
114
- var oldValue = this._enableAggregation;
115
- this._enableAggregation = value;
116
- if (!oldValue && value) {
117
- this.processQueryForAggregation();
118
- var aggrCols = this.columns.filter(function (c) { return c.enabled
119
- && c.expr.tag == ExprTag.AggregateFunction; });
120
- }
121
- if (!this._enableAggregation) {
122
- this.aggrSettings.clear();
123
- }
124
- },
125
- enumerable: true,
126
- configurable: true
127
- });
128
- Query.prototype.updateAggregationSettings = function () {
129
- var hasChanged = false;
130
- var aggrSettings = this.getAggregationSettings();
131
- for (var i = aggrSettings.groups.length - 1; i >= 0; i--) {
132
- var group = aggrSettings.groups[i];
133
- var _loop_1 = function (j) {
134
- var colId = group.columns[j];
135
- if (!this_1.columns.find(function (col) { return col.id === colId; })) {
136
- group.columns.splice(j, 1);
137
- hasChanged = true;
138
- }
139
- };
140
- var this_1 = this;
141
- for (var j = group.columns.length - 1; j >= 0; j--) {
142
- _loop_1(j);
143
- }
144
- if (group.columns.length == 0) {
145
- aggrSettings.groups.slice(i, 1);
146
- }
147
- }
148
- var aggregates = aggrSettings.getAggregates();
149
- var _loop_2 = function (i) {
150
- var aggr = aggregates[i];
151
- if (!this_2.columns.find(function (col) { return col.id === aggr.colId; })) {
152
- aggregates.splice(i, 1);
153
- hasChanged = true;
154
- }
155
- };
156
- var this_2 = this;
157
- for (var i = aggregates.length - 1; i >= 0; i--) {
158
- _loop_2(i);
159
- }
160
- return hasChanged;
161
- };
162
- Query.prototype.createSubQuery = function () {
163
- return new Query(this.model);
164
- };
165
- Query.prototype.useAggregation = function (settingsTuner, silent) {
166
- if (silent === void 0) { silent = false; }
167
- this.aggrSettings.clear();
168
- settingsTuner(this.aggrSettings);
169
- if (this.enableAggregation) {
170
- this.processQueryForAggregation(silent);
171
- }
172
- else if (!silent) {
173
- console.warn('Aggregation is turned off. Turn it on with query.enableAggregation = true');
174
- return;
175
- }
176
- };
177
- Query.prototype.useDefaultAggregation = function () {
178
- var _this = this;
179
- this._enableAggregation = true;
180
- this.useAggregation(function (settings) {
181
- var aggrCols = _this.columns.filter(function (c) { return c.enabled
182
- && c.expr.tag == ExprTag.AggregateFunction; });
183
- if (aggrCols.length) {
184
- // query contains aggregate columns
185
- var colsToGroup = _this.columns.filter(function (c) { return c.enabled
186
- && c.expr.tag == ExprTag.EntityAttribute; });
187
- var aggrsToAdd = [];
188
- for (var _i = 0, aggrCols_1 = aggrCols; _i < aggrCols_1.length; _i++) {
189
- var col = aggrCols_1[_i];
190
- aggrsToAdd.push({ id: col.id, func: col.expr.func });
191
- _this.changeColumnType(col, ExprTag.EntityAttribute);
192
- }
193
- for (var _a = 0, aggrsToAdd_1 = aggrsToAdd; _a < aggrsToAdd_1.length; _a++) {
194
- var aggr = aggrsToAdd_1[_a];
195
- settings.addAggregateColumn(aggr.id, aggr.func);
196
- }
197
- for (var _b = 0, colsToGroup_1 = colsToGroup; _b < colsToGroup_1.length; _b++) {
198
- var col = colsToGroup_1[_b];
199
- settings.addGroup({ columns: [col.id], name: col.caption });
200
- }
201
- settings.addGrandTotals();
202
- _this.fireChangedEvent({
203
- part: QueryChangePart.Columns,
204
- wasModified: false
205
- });
206
- }
207
- else {
208
- // query does not has any aggr columns
209
- var colToAggr = _this.getColumns()
210
- .filter(function (c) { return c.enabled && c.expr.tag == ExprTag.EntityAttribute
211
- && _this.model.getAttributeById(c.expr.value).dataType === DataType.Currency; })[0];
212
- var colToGroup = _this.getColumns()
213
- .filter(function (c) { return c.enabled && c.expr.tag == ExprTag.EntityAttribute
214
- && _this.model.getAttributeById(c.expr.value).dataType === DataType.String; })[0];
215
- if ((!colToAggr && !settings.hasAggregates()) || !colToGroup)
216
- return;
217
- settings.addGrandTotals()
218
- .addAggregateColumn(colToAggr.id, 'SUM')
219
- .addGroup({ columns: [colToGroup.id], name: 'Default' });
220
- }
221
- });
222
- };
223
- Query.prototype.processQueryForAggregation = function (silent) {
224
- if (silent === void 0) { silent = false; }
225
- var aggrSettings = this.getAggregationSettings();
226
- var groups = aggrSettings.getGroups();
227
- if (groups.length > 0) {
228
- var groupColIds = groups[groups.length - 1].columns;
229
- //take the list of grouped columns from the latest group
230
- var groupedCols = [];
231
- var sortedCols = [];
232
- for (var _i = 0, _a = this.getColumns(); _i < _a.length; _i++) {
233
- var col = _a[_i];
234
- if (groupColIds.indexOf(col.id) >= 0) {
235
- groupedCols.push(col);
236
- }
237
- else if (col.sorting != SortDirection.None) {
238
- sortedCols.push(col);
239
- }
240
- }
241
- var sortIndex_1 = 0;
242
- groupedCols.forEach(function (col) {
243
- if (col.sorting == SortDirection.None) {
244
- col.sorting = SortDirection.Ascending;
245
- }
246
- col.sortIndex = sortIndex_1++;
247
- });
248
- sortedCols.forEach(function (col) {
249
- col.sortIndex = sortIndex_1++;
250
- });
251
- if (!silent) {
252
- this.fireChangedEvent({
253
- part: QueryChangePart.Columns,
254
- aggregation: true,
255
- wasModified: false
256
- });
257
- }
258
- }
259
- };
260
- Query.prototype.getAggregationSettings = function () {
261
- return this.aggrSettings;
262
- };
263
- Query.prototype.getColumnIds = function (from, to) {
264
- to = to || from;
265
- return this.columns.slice(from, to - from + 1)
266
- .map(function (c) { return c.id; });
267
- };
268
- /**
269
- * Checks if the columns with IDs passed in function's parameter exist and are valid
270
- */
271
- Query.prototype.validateColumns = function (colIds) {
272
- var enabledColIds = this.columns.filter(function (c) { return c.enabled; }).map(function (c) { return c.id; });
273
- var prevIndex = -1;
274
- for (var _i = 0, colIds_1 = colIds; _i < colIds_1.length; _i++) {
275
- var col = colIds_1[_i];
276
- var index = enabledColIds.indexOf(col);
277
- if (index < 0)
278
- return false;
279
- if (prevIndex > index)
280
- return false;
281
- prevIndex = index;
282
- }
283
- return true;
284
- };
285
- Query.prototype.validateAggregate = function (colId, funcId) {
286
- var col = this.columns.filter(function (c) { return c.enabled && c.id === colId; })[0];
287
- var func = this.model.findAggrFunctionById(funcId);
288
- if (!func || !col || func.appliedTypes.indexOf(col.expr.dataType) < 0)
289
- return false;
290
- return true;
291
- };
292
- Query.prototype.isEx = function () {
293
- return false;
294
- };
295
- /**
296
- * Resets the query: clears all its conditions and columns, regenerate the ID and sets the default name.
297
- * @param silent Indicates whether we need to avoid firing the QueryChanged event.
298
- */
299
- Query.prototype.reset = function (clearQuery) {
300
- if (clearQuery === void 0) { clearQuery = true; }
301
- if (clearQuery) {
302
- this.clear();
303
- }
304
- this.regenerateId();
305
- this.setDefaultName();
306
- this._isModified = false;
307
- this.isNewbie = true;
308
- };
309
- Query.prototype.hasEnabledAggrColumns = function () {
310
- return this.columns.filter(function (col) { return col.enabled
311
- && col.expr.tag === ExprTag.AggregateFunction; }).length > 0;
312
- };
313
- Query.prototype.setDefaultName = function () {
314
- this.setName(i18n.getText('NewQueryName'));
315
- return this.getName();
316
- };
317
- /**
318
- * Validates wether the query corresponds to the model.
319
- * @param options Validate options.
320
- * @throws {InvalidQueryError} If query is not valid.
321
- */
322
- Query.prototype.validate = function (options) {
323
- options = options || {};
324
- var entityAttrNotExistError = "EntityAttribute isn't declared in the model: ";
325
- var wrongExprTag = "The expression has wrond tag: ";
326
- if (!this.model) {
327
- throw new InvalidQueryError("Model is not declared");
328
- }
329
- if (this.columns) {
330
- for (var _i = 0, _a = this.columns; _i < _a.length; _i++) {
331
- var column = _a[_i];
332
- if (column.expr.tag == ExprTag.EntityAttribute
333
- || column.expr.tag === ExprTag.ParentEntityAttribute) {
334
- var attr = this.model.getAttributeById(column.expr.value);
335
- if (!attr) {
336
- throw new InvalidQueryError(entityAttrNotExistError + column.expr.value);
337
- }
338
- }
339
- else if (column.expr.tag === ExprTag.AggregateFunction) {
340
- var attr = this.model.getAttributeById(column.expr.args[0].value);
341
- if (!attr) {
342
- throw new InvalidQueryError(entityAttrNotExistError + column.expr.args[0].value);
343
- }
344
- }
345
- else if (column.expr.tag !== ExprTag.CustomSql) {
346
- throw new InvalidQueryError(wrongExprTag + column.expr.tag);
347
- }
348
- }
349
- }
350
- if (this.root && this.root.getConditions()) {
351
- this.validateConditionGroup(this.root, options);
352
- }
353
- };
354
- Query.prototype.getAggregatedColumns = function () {
355
- return this.getColumns().filter(function (col) { return col.enabled
356
- && col.expr.tag === ExprTag.AggregateFunction; });
357
- };
358
- /**
359
- * Validates wether the query corresponds to the model.
360
- * @param options Validate options.
361
- * @returns `true` if it is valid, otherwise `false`
362
- */
363
- Query.prototype.tryValidate = function (options) {
364
- try {
365
- this.validate(options);
366
- return true;
367
- }
368
- catch (e) {
369
- if (e instanceof InvalidQueryError) {
370
- return false;
371
- }
372
- else {
373
- throw e;
374
- }
375
- }
376
- };
377
- Query.prototype.validateConditionGroup = function (curCond, options) {
378
- if (curCond.isGroup()) {
379
- for (var _i = 0, _a = curCond.getConditions(); _i < _a.length; _i++) {
380
- var condition = _a[_i];
381
- if (!condition.enabled)
382
- continue;
383
- this.validateConditionGroup(condition, options);
384
- }
385
- }
386
- else if (curCond.expressions[0].tag === ExprTag.EntityAttribute) {
387
- var attrId = curCond.expressions[0].value;
388
- var attr = this.model.getAttributeById(attrId);
389
- if (!attr) {
390
- throw new InvalidQueryError("EntityAttribute isn't declared in the model: " + attrId);
391
- }
392
- if (!options.checkExpressions)
393
- return;
394
- for (var i = 1; i < curCond.expressions.length; i++) {
395
- var expr = curCond.expressions[i];
396
- if (expr.tag !== ExprTag.Constant)
397
- continue;
398
- //validate number exprs
399
- if (dataUtils.isNumericType(expr.dataType)) {
400
- if (!expr.value)
401
- continue;
402
- var values = [];
403
- if (expr.kind === DataKind.List) {
404
- values = expr.value.split(/\s*,\s*/);
405
- }
406
- else {
407
- values = [expr.value];
408
- }
409
- for (var _b = 0, values_1 = values; _b < values_1.length; _b++) {
410
- var value = values_1[_b];
411
- var parsedVal = +value;
412
- if (isNaN(parsedVal)) {
413
- throw new InvalidQueryError("Expression constant is NaN in condition:" + curCond.id);
414
- }
415
- if (dataUtils.isIntType(expr.dataType) && parsedVal != parseInt(value, 10)) {
416
- throw new InvalidQueryError("Expression constant is wrong interger in condition: " + curCond.id);
417
- }
418
- }
419
- }
420
- }
421
- }
422
- };
423
- /**
424
- * Sets data to the query.
425
- * @param data JSON representation object or JSON string
426
- * @param changeStatus Indicate whether we should change the "isModified" status (by default == `true`)
427
- */
428
- Query.prototype.loadFromDataOrJson = function (data, options) {
429
- if (data) {
430
- if (typeof data === "string") {
431
- this.loadFromJson(data, options);
432
- }
433
- else {
434
- this.loadFromData(data, options);
435
- }
436
- }
437
- };
438
- /**
439
- * Loads query from JSON.
440
- * @param json The JSON string.
441
- * @param options The options.
442
- * @throws {InvalidQueryError} The error throws when query is not valid.
443
- */
444
- Query.prototype.loadFromJson = function (json, options) {
445
- var data = JSON.parse(json);
446
- this.loadFromData(data, options);
447
- };
448
- /**
449
- * Loads query from data representation.
450
- * @param data The query DTO.
451
- * @param options The options.
452
- * @throws {InvalidQueryError} The error throws when query is not valid.
453
- */
454
- Query.prototype.loadFromData = function (data, options) {
455
- var _this = this;
456
- options = dataUtils.assign({
457
- changeStatus: true,
458
- validate: true
459
- }, options || {});
460
- var noErrors = false;
461
- this.clear();
462
- this.clearDrillDowns();
463
- if (data) {
464
- this.id = data.id;
465
- this.root.loadFromData(this.model, data.root);
466
- if (data.root && data.root.conds) {
467
- for (var i = 0; i < data.root.conds.length; i++) {
468
- var condData = data.root.conds[i];
469
- if (condData.conds && !this.isEx()) {
470
- console.error("Community version doesn't support working with groups.");
471
- continue;
472
- }
473
- var cond = this.createCondition();
474
- cond.loadFromData(this.model, condData);
475
- this.root.addCondition(cond);
476
- }
477
- }
478
- this.name = data.name;
479
- this.description = data.desc;
480
- this.justsorted = [];
481
- if (data.justsortcols) {
482
- for (var i = 0; i < data.justsortcols.length; i++) {
483
- var newCol = this.createColumn(true);
484
- newCol.loadFromData(this.model, data.justsortcols[i]);
485
- this.justsorted.push(newCol);
486
- }
487
- }
488
- if (data.cols) {
489
- for (var i = 0; i < data.cols.length; i++) {
490
- var newCol = this.createColumn();
491
- newCol.loadFromData(this.model, data.cols[i]);
492
- this.columns.push(newCol);
493
- }
494
- }
495
- if (data.extraData) {
496
- this.extraData = data.extraData;
497
- }
498
- this.innerData = data.innerData || this.innerData;
499
- if (this.innerData && this.innerData.aggr) {
500
- this._enableAggregation = this.innerData.aggr.enabled || false;
501
- this.useAggregation(function (settings) {
502
- settings.loadFromData(_this.innerData.aggr);
503
- }, true);
504
- }
505
- if (data.dds && data.dds.length) {
506
- for (var _i = 0, _a = data.dds; _i < _a.length; _i++) {
507
- var dd = _a[_i];
508
- var query = this.addDrillDown();
509
- query.loadFromData(dd);
510
- }
511
- }
512
- }
513
- noErrors = true;
514
- if (noErrors) {
515
- if (options.changeStatus) {
516
- this.isNewbie = false;
517
- this._isModified = false;
518
- }
519
- }
520
- if (options.validate) {
521
- this.validate();
522
- }
523
- };
524
- /**
525
- *
526
- */
527
- Query.prototype.addDrillDown = function () {
528
- var query = this.model.createQuery();
529
- query.parentQuery = this;
530
- this.drillDowns.push(query);
531
- return query;
532
- };
533
- Query.prototype.getDrillDowns = function () {
534
- return this.drillDowns;
535
- };
536
- Query.prototype.getParentQuery = function () {
537
- return this.parentQuery;
538
- };
539
- /**
540
- *
541
- */
542
- Query.prototype.findColumnById = function (colId) {
543
- for (var _i = 0, _a = this.columns; _i < _a.length; _i++) {
544
- var col = _a[_i];
545
- if (col.id === colId)
546
- return col;
547
- }
548
- return null;
549
- };
550
- /**
551
- * Gets DataModel object associated with this query.
552
- * @retruns The data model.
553
- */
554
- Query.prototype.getModel = function () {
555
- return this.model;
556
- };
557
- /**
558
- * Sets DataModel object associated with this query.
559
- * @param model The data model.
560
- */
561
- Query.prototype.setModel = function (model) {
562
- this.model = model;
563
- };
564
- /**
565
- * Loads data model.
566
- * @param model JSON representation object or JSON string.
567
- */
568
- Query.prototype.loadModelData = function (model) {
569
- this.model.setData(model);
570
- };
571
- /**
572
- * Returns JSON representation of this query.
573
- * @retruns JSON string.
574
- */
575
- Query.prototype.toJSON = function () {
576
- return JSON.stringify(this.toJSONData());
577
- };
578
- /**
579
- * Returns JSON representation of this query.
580
- * @retruns JSON representation object.
581
- */
582
- Query.prototype.toJSONData = function () {
583
- var _this = this;
584
- var obj = {
585
- modelId: this.model ? this.model.getId() : null,
586
- modelName: this.model ? this.model.getName() : null
587
- };
588
- obj.id = this.id;
589
- obj.name = this.name;
590
- if (this.description) {
591
- obj.desc = this.description;
592
- }
593
- obj.cols = [];
594
- for (var i = 0; i < this.columns.length; i++) {
595
- obj.cols.push(this.columns[i].saveToData());
596
- }
597
- obj.justsortcols = [];
598
- for (var i = 0; i < this.justsorted.length; i++) {
599
- obj.justsortcols.push(this.justsorted[i].saveToData());
600
- }
601
- if (this.extraData) {
602
- obj.extraData = this.extraData;
603
- }
604
- if (this.innerData) {
605
- obj.innerData = this.innerData;
606
- obj.innerData.aggr = this.aggrSettings.saveToData();
607
- obj.innerData.aggr.enabled = this._enableAggregation;
608
- }
609
- var rootCondToData = function (condGroup) {
610
- var result = condGroup.saveToData();
611
- result.conds = [];
612
- var conditions = condGroup.getConditions();
613
- for (var i = 0; i < conditions.length; i++) {
614
- if (conditions[i].isGroup() && !_this.isEx()) {
615
- console.error("Community version doesn't support working with groups.");
616
- continue;
617
- }
618
- result.conds.push(conditions[i].saveToData());
619
- }
620
- return result;
621
- };
622
- obj.root = rootCondToData(this.root);
623
- obj.extraConds = rootCondToData(this.extraConditions);
624
- if (this.drillDowns.length > 0) {
625
- obj.dds = [];
626
- for (var _i = 0, _a = this.drillDowns; _i < _a.length; _i++) {
627
- var dd = _a[_i];
628
- obj.dds.push(dd.toJSONData());
629
- }
630
- }
631
- obj.timezoneOffset = this.timezoneOffset;
632
- obj.locale = i18n.getCurrentLocale();
633
- return obj;
634
- };
635
- /**
636
- * Checks wether query does not contains any condtion.
637
- * @retruns `true` if query does not contain any condition, otherwise `false`.
638
- */
639
- Query.prototype.isEmptyConditions = function () {
640
- return this.root.isEmpty();
641
- };
642
- /**
643
- * Checks wether query does not contains any column.
644
- * @retruns `true` if query does not contain any column, otherwise `false`.
645
- */
646
- Query.prototype.isEmptyColumns = function () {
647
- return !this.columns || this.columns.length === 0;
648
- };
649
- /**
650
- * Checks wether query does not contains any column and any condition.
651
- * @retruns `true` if query does not contain any column and any condition, otherwise `false`.
652
- */
653
- Query.prototype.isEmpty = function () {
654
- return this.isEmptyColumns() && this.isEmptyConditions();
655
- };
656
- /**
657
- * Clears the query (all conditions, columns, extraData, etc).
658
- */
659
- Query.prototype.clear = function () {
660
- this._enableAggregation = false;
661
- this.aggrSettings.clear();
662
- this.clearColumns();
663
- this.clearConditions();
664
- this.clearExtraConditions();
665
- this.innerData = {};
666
- this.extraData = {};
667
- };
668
- /**
669
- * Clears all columns in query
670
- */
671
- Query.prototype.clearColumns = function () {
672
- this.columns = [];
673
- this.justsorted = [];
674
- };
675
- /**
676
- * Clears all conditions in query.
677
- */
678
- Query.prototype.clearConditions = function () {
679
- this.root.clearConditions();
680
- this.root.linkType = LinkType.All;
681
- this.root.enabled = true;
682
- };
683
- /**
684
- * Clears all extra conditions in query
685
- */
686
- Query.prototype.clearExtraConditions = function () {
687
- this.extraConditions.clearConditions();
688
- };
689
- /**
690
- * Clears all drill downs
691
- */
692
- Query.prototype.clearDrillDowns = function () {
693
- this.drillDowns = [];
694
- };
695
- /**
696
- * Gets query ID.
697
- * @returns The ID>
698
- */
699
- Query.prototype.getId = function () {
700
- return this.id;
701
- };
702
- /**
703
- * Sets query ID.
704
- * @param id New Query ID.
705
- */
706
- Query.prototype.setId = function (id) {
707
- this.id = id;
708
- };
709
- /**
710
- * Regenerates current query ID.
711
- * @param id New Query ID.
712
- */
713
- Query.prototype.regenerateId = function () {
714
- this.id = dataUtils.generateId("quer");
715
- };
716
- /**
717
- * Gets name of the query.
718
- * @retruns The name.
719
- */
720
- Query.prototype.getName = function () {
721
- return this.name;
722
- };
723
- /**
724
- * Sets name of the query
725
- * @param name New name.
726
- */
727
- Query.prototype.setName = function (name) {
728
- this.name = name;
729
- };
730
- /**
731
- * Gets description of the query.
732
- * @retruns The description.
733
- */
734
- Query.prototype.getDescription = function () {
735
- return this.description;
736
- };
737
- /**
738
- * Sets description of the query
739
- * @param description New description.
740
- */
741
- Query.prototype.setDescription = function (description) {
742
- this.description = description;
743
- };
744
- /**
745
- * Get array of columns.
746
- * @retruns Columns.
747
- */
748
- Query.prototype.getColumns = function () {
749
- return this.columns;
750
- };
751
- /**
752
- * Gets array of columns that are used as keys
753
- * for totals.
754
- */
755
- Query.prototype.getUsedInTotalsColumns = function () {
756
- var aggrs = this.getAggregatedColumns();
757
- if (aggrs.length === 0)
758
- return [];
759
- var cols = this.getColumns()
760
- .filter(function (col) { return col.enabled && col.expr.tag === ExprTag.EntityAttribute; });
761
- if (cols.length)
762
- cols.pop();
763
- return cols;
764
- };
765
- /**
766
- * Get array of columns used only in sorting.
767
- * @retruns Columns.
768
- */
769
- Query.prototype.getJustSortedColumns = function () {
770
- return this.justsorted;
771
- };
772
- /**
773
- * Gets array of columns used in sorting
774
- * @retruns Columns
775
- */
776
- Query.prototype.getSortedColumns = function () {
777
- var sortedCols = new Array();
778
- var cols = this.getColumns()
779
- .concat(this.getJustSortedColumns());
780
- for (var i = 0; i < cols.length; i++) {
781
- var col = cols[i];
782
- if (col.sortIndex >= 0) {
783
- sortedCols.push(col);
784
- }
785
- }
786
- sortedCols.sort(function (col1, col2) {
787
- return col1.sortIndex - col2.sortIndex;
788
- });
789
- return sortedCols;
790
- };
791
- /**
792
- * Gets Colummn sorting index.
793
- * @param col The column.
794
- * @retruns The index.
795
- */
796
- Query.prototype.getColumnSortIndex = function (col) {
797
- if (col.sorting != SortDirection.None) {
798
- if (col.sortIndex < 0) {
799
- var cols = this.getColumns()
800
- .concat(this.getJustSortedColumns());
801
- return dataUtils.indexOfArrayItem(cols, col);
802
- }
803
- else {
804
- return col.sortIndex;
805
- }
806
- }
807
- return -1;
808
- };
809
- Query.prototype.createColumn = function (justsorted) {
810
- if (justsorted === void 0) { justsorted = false; }
811
- return new QueryColumn(this, justsorted);
812
- };
813
- Query.prototype.getColumnById = function (id) {
814
- return dataUtils.findItemById(this.columns, id);
815
- };
816
- /**
817
- * Adds a new column with specified parameters
818
- * @param desriptor The descriptor of the new column. Can contain different parameters like:
819
- * `attribute` - a reference to a EntityAttr object,
820
- * `attributeId` - an ID of the entity attribute we need (if we don't indicate `attribute`),
821
- * `index`, sorting`, 'sortIndex` and other
822
- *
823
- * @param author The author of this operation. This parameter is used in EasyQuery widgets only to indicate which of the initiates the change.
824
- * @retruns The column.
825
- * @example
826
- * query.addColumn({
827
- * attributeId: 'Customers.CompanyName',
828
- * sortIndex: SortDirection.Ascending
829
- * }});
830
- */
831
- Query.prototype.addColumn = function (descriptor, author) {
832
- var columns = (descriptor.justsorted)
833
- ? this.justsorted
834
- : this.columns;
835
- var newColumn;
836
- if (descriptor.column) {
837
- newColumn = descriptor.column;
838
- }
839
- else {
840
- newColumn = this.createColumn(descriptor.justsorted);
841
- var attr = void 0;
842
- if (descriptor.attribute) {
843
- attr = descriptor.attribute;
844
- }
845
- else if (descriptor.attributeId) {
846
- attr = this.model.getAttributeById(descriptor.attributeId);
847
- if (!attr) {
848
- throw new Error("Incorrect attribute id (" + descriptor.attributeId + "): addColumn");
849
- }
850
- }
851
- else {
852
- throw new Error('Not enought data for addColumn operation. Need attribute or attributeId');
853
- }
854
- if (!attr.useInResult) {
855
- if (attr.lookupAttr) {
856
- attr = this.model.getAttributeById(attr.lookupAttr);
857
- }
858
- if (!attr || !attr.useInResult) {
859
- throw new Error("Can't use this attribute for a column");
860
- }
861
- }
862
- if (descriptor.aggrFuncId && descriptor.cusomtSql) {
863
- console.warn("Column cannot be created using aggrFuncId and customSql at the same time. " +
864
- "cusomSql will be used.");
865
- }
866
- if (descriptor.cusomtSql) {
867
- newColumn.caption = 'Custom SQL Column';
868
- newColumn.expr.tag = ExprTag.CustomSql;
869
- newColumn.expr.baseAttrId = attr.id;
870
- newColumn.expr.sql = descriptor.cusomtSql;
871
- newColumn.expr.kind = DataKind.Query;
872
- newColumn.expr.dataType = DataType.Unknown;
873
- }
874
- else if (descriptor.aggrFuncId) {
875
- var funcId = descriptor.aggrFuncId;
876
- newColumn.caption = attr.caption + ' '
877
- + this.model.getAggrFunctionCaption(descriptor.aggrFuncId);
878
- newColumn.expr.tag = ExprTag.AggregateFunction;
879
- newColumn.expr.func = descriptor.aggrFuncId;
880
- newColumn.expr.kind = DataKind.Scalar;
881
- newColumn.expr.dataType = funcId == 'COUNT' || funcId == 'CNTDST' ? 4 : attr.dataType;
882
- newColumn.expr.distinct = false;
883
- var arg = new Expression(newColumn);
884
- arg.setValue(attr.id, true);
885
- arg.tag = ExprTag.EntityAttribute;
886
- arg.dataType = attr.dataType;
887
- newColumn.expr.args.push(arg);
888
- }
889
- else {
890
- newColumn.caption = attr.caption;
891
- newColumn.expr.setValue(attr.id, true);
892
- newColumn.expr.tag = ExprTag.EntityAttribute;
893
- newColumn.expr.dataType = attr.dataType;
894
- }
895
- newColumn.caption = descriptor.caption || newColumn.caption;
896
- newColumn.sorting = descriptor.sorting || SortDirection.None;
897
- newColumn.sortIndex = descriptor.sortIndex || -1;
898
- newColumn.enabled = dataUtils.getIfDefined(descriptor.enabled, true);
899
- newColumn.setReadOnly(dataUtils.getIfDefined(descriptor.readonly, false));
900
- }
901
- if (descriptor.index && descriptor.index >= 0 && descriptor.index < columns.length) {
902
- columns.splice(descriptor.index, 0, newColumn);
903
- }
904
- else {
905
- columns.push(newColumn);
906
- }
907
- return newColumn;
908
- };
909
- /**
910
- * Adds a new column with specified index.
911
- * @param column The column or array of columns
912
- * @param index The index of new column
913
- * @param author The author.
914
- * @example
915
- * const column = new Column();
916
- * column.caption = "Company name";
917
- *
918
- * query.addColumn(column, 1)
919
- */
920
- Query.prototype.addColumnObj = function (column, index, author) {
921
- var columns = this.columns;
922
- if (typeof column.length == "undefined") {
923
- if (typeof index == "number") {
924
- columns.splice(index, 0, column);
925
- }
926
- else {
927
- columns.push(column);
928
- }
929
- }
930
- else {
931
- if (typeof index == "number") {
932
- columns.push.apply(columns, [index, 0].concat(column));
933
- }
934
- else {
935
- columns.push.apply(columns, [].concat(column));
936
- }
937
- }
938
- };
939
- /**
940
- * Changes column to Aggregate function, custom expression or simple column.
941
- * @param column The column to change.
942
- * @param tag New column expression tag.
943
- * @param args The arguments (Contains aggregate function id)
944
- */
945
- Query.prototype.changeColumnType = function (column, tag, args) {
946
- if (column.isJustSorted())
947
- return;
948
- args = args || {};
949
- column.caption = (typeof args.caption !== 'undefined')
950
- ? args.caption
951
- : '';
952
- if (tag === ExprTag.AggregateFunction) {
953
- if (!args.funcId)
954
- throw Error('"funcId" argument is not defined');
955
- if (column.expr.tag == ExprTag.AggregateFunction) {
956
- column.expr.func = args.funcId;
957
- return;
958
- }
959
- var expr = new Expression(column);
960
- expr.tag = ExprTag.AggregateFunction;
961
- expr.func = args.funcId;
962
- expr.distinct = false;
963
- expr.dataType = args.funcId == 'COUNT' || args.funcId == 'CNTDST' ? 4 : column.expr.dataType;
964
- var arg = new Expression(column);
965
- arg.loadFromData(this.model, column.expr.saveToData());
966
- expr.args.push(arg);
967
- column.expr = expr;
968
- }
969
- else if (tag === ExprTag.CustomSql) {
970
- var attrId = (column.expr.tag == ExprTag.AggregateFunction)
971
- ? column.expr.args[0].value
972
- : column.expr.value;
973
- var sqlText = '';
974
- if (this.model) {
975
- sqlText = this.model.getAttributeById(attrId).expr;
976
- }
977
- var customSqlExpr = new Expression(column);
978
- customSqlExpr.tag = ExprTag.CustomSql;
979
- customSqlExpr.dataType = DataType.String; //the default data type
980
- customSqlExpr.sql = sqlText;
981
- customSqlExpr.baseAttrId = attrId;
982
- column.expr = customSqlExpr;
983
- }
984
- else if (tag === ExprTag.EntityAttribute) {
985
- if (column.expr.tag === ExprTag.EntityAttribute
986
- || column.expr.tag === ExprTag.ParentEntityAttribute) {
987
- return;
988
- }
989
- var exprId = (column.expr.tag === ExprTag.CustomSql)
990
- ? column.expr.baseAttrId
991
- : column.expr.args[0].value;
992
- var attr = this.model.getAttributeById(exprId);
993
- var expr = new Expression(column);
994
- expr.tag = ExprTag.EntityAttribute;
995
- expr.dataType = attr != null ? attr.dataType : DataType.Unknown;
996
- expr.setValue(exprId, true);
997
- column.expr = expr;
998
- }
999
- };
1000
- /**
1001
- * Moves the column with specified index to another position.
1002
- * @param index1 The index of the column that should be moved.
1003
- * @param index2 The index of the position the column should be moved to
1004
- * @param author The author
1005
- */
1006
- Query.prototype.moveColumn = function (index1, index2) {
1007
- var columns = this.getColumns();
1008
- dataUtils.moveArrayItem(columns, index1, index2);
1009
- };
1010
- /**
1011
- * Removes the column.
1012
- * @param column The column to be removed.
1013
- * @param author The author
1014
- */
1015
- Query.prototype.removeColumn = function (column, author) {
1016
- var columns = (column.isJustSorted())
1017
- ? this.getJustSortedColumns()
1018
- : this.getColumns();
1019
- dataUtils.removeArrayItem(columns, column);
1020
- };
1021
- /**
1022
- * Adds a condition group - a group of simple conditions (predicates) linked by AND or OR
1023
- * @param descriptor The descriptor of the new condition group.
1024
- * @returns The new search condition.
1025
- */
1026
- Query.prototype.addConditionGroup = function (descriptor, addChildCondition) {
1027
- if (addChildCondition === void 0) { addChildCondition = true; }
1028
- console.error("Community version doesn't support working with groups.");
1029
- return null;
1030
- };
1031
- Query.prototype.addExtraConditionGroup = function (descriptor, addChildCondition) {
1032
- if (addChildCondition === void 0) { addChildCondition = true; }
1033
- console.error("Community version doesn't support working with groups.");
1034
- return null;
1035
- };
1036
- Query.prototype.createCondition = function (tag) {
1037
- if (tag === void 0) { tag = CondTag.Simple; }
1038
- return new Condition(this, tag);
1039
- };
1040
- /**
1041
- * Adds a new simple condition (a predicate)
1042
- * @param descriptor The descriptor which defines different parameters of the new condition
1043
- * @returns The new condition.
1044
- */
1045
- Query.prototype.addSimpleCondition = function (descriptor) {
1046
- var parent = descriptor.parent || this.getRootCondition();
1047
- var model = this.getModel();
1048
- if (!model)
1049
- return null;
1050
- if (!descriptor.attribute && !descriptor.attributeId) {
1051
- throw new Error("Either `attribute` or `attributeId` parameter must have a value");
1052
- }
1053
- if (!descriptor.attribute) {
1054
- descriptor.attribute = model.getAttributeById(descriptor.attributeId);
1055
- if (!descriptor.attribute) {
1056
- throw new Error("Could not find this attribute: " + descriptor.attributeId);
1057
- }
1058
- }
1059
- if (!descriptor.operator && descriptor.operatorId) {
1060
- descriptor.operator = model.getOperatorById(descriptor.operatorId);
1061
- }
1062
- if (!descriptor.operator) {
1063
- descriptor.operator = model.getDefaultOperatorForAttr(descriptor.attribute);
1064
- }
1065
- var cond = this.createSimpleConditionObject(descriptor.attribute, descriptor.operator, descriptor.value);
1066
- parent.addCondition(cond);
1067
- cond.enabled = dataUtils.getIfDefined(descriptor.enabled, true);
1068
- cond.setReadOnly(dataUtils.getIfDefined(descriptor.readonly, false));
1069
- return cond;
1070
- };
1071
- Query.prototype.addSimpleExtraCondition = function (descriptor) {
1072
- descriptor.parent = descriptor.parent || this.extraConditions;
1073
- return this.addSimpleCondition(descriptor);
1074
- };
1075
- Query.prototype.createSimpleConditionObject = function (attr, operator, inputValues) {
1076
- if (!attr || !attr.useInConditions) {
1077
- var attrCaption = attr ? attr.caption : 'NULL';
1078
- throw "Can't add a condition with such attribute: " + attrCaption;
1079
- }
1080
- var cond = this.createCondition(CondTag.Simple);
1081
- cond.setOperatorId(operator.id, true);
1082
- var attrExpr = new Expression(cond);
1083
- attrExpr.setValue(attr.id, true);
1084
- attrExpr.tag = this.attributeExprTag;
1085
- attrExpr.kind = DataKind.Attribute;
1086
- attrExpr.dataType = attr.dataType;
1087
- cond.expressions.push(attrExpr);
1088
- var model = this.getModel();
1089
- var valCount = operator.paramCount;
1090
- var values = dataUtils.fillArray(new Array(valCount - 1), null);
1091
- if (inputValues !== null && typeof inputValues !== "undefined") {
1092
- if (Array.isArray(inputValues)) {
1093
- dataUtils.copyArrayTo(inputValues, values);
1094
- }
1095
- else if (valCount > 0) {
1096
- values[0] = inputValues;
1097
- }
1098
- }
1099
- var valLength = values.length;
1100
- for (var i = 0; i < valLength; i++) {
1101
- var operand = model.getOperand(attr, operator, i + 1);
1102
- cond.addExpressionByOperand(operand, values[i]);
1103
- }
1104
- return cond;
1105
- };
1106
- /**
1107
- * Removes several columns passed as array.
1108
- * @param columnsToRemove The list of columns to be removed.
1109
- * @param author The author.
1110
- */
1111
- Query.prototype.removeColumns = function (columnsToRemove, author) {
1112
- var justSortedColumns = columnsToRemove.filter(function (c) { return c.isJustSorted(); });
1113
- var columns = columnsToRemove.filter(function (c) { return !c.isJustSorted(); });
1114
- function removeFromArray(arr, arrToRemove) {
1115
- var ctrLen = arrToRemove.length;
1116
- for (var i = 0; i < ctrLen; i++) {
1117
- var index = arr.indexOf(arrToRemove[i]);
1118
- if (index >= 0) {
1119
- arr.splice(index, 1);
1120
- }
1121
- }
1122
- }
1123
- if (columns.length > 0) {
1124
- removeFromArray(this.getColumns(), columns);
1125
- }
1126
- if (justSortedColumns.length > 0) {
1127
- removeFromArray(this.getJustSortedColumns(), justSortedColumns);
1128
- }
1129
- };
1130
- /**
1131
- * Fires process event.
1132
- * @param data The data.
1133
- */
1134
- Query.prototype.fireProcessEvent = function (data) {
1135
- this.eventEmitter.fire('query.process', data);
1136
- };
1137
- Query.prototype.fireChangedEvent = function (params, postpone, wasModified) {
1138
- params = params || { part: QueryChangePart.All };
1139
- if (typeof (postpone) != 'undefined' || typeof (wasModified) != 'undefined') {
1140
- params.postpone = postpone || 0;
1141
- params.wasModified = wasModified;
1142
- console.warn('Method with \'postpone\' and \'wasModified\' args is deprecated. Pass params in data object');
1143
- }
1144
- this._isModified = typeof (params.wasModified) != 'undefined'
1145
- ? params.wasModified
1146
- : true;
1147
- var eventData = params || {
1148
- part: QueryChangePart.All
1149
- };
1150
- this.eventEmitter.fire('query.change', eventData, params.postpone || 0);
1151
- };
1152
- Query.prototype.fireColumnsChangedEvent = function (action, column, justsorted) {
1153
- if (justsorted === void 0) { justsorted = false; }
1154
- this.fireChangedEvent({
1155
- part: (justsorted)
1156
- ? QueryChangePart.SortingColumns
1157
- : QueryChangePart.Columns,
1158
- action: action,
1159
- changee: column
1160
- });
1161
- };
1162
- Query.prototype.fireConditionsChangedEvent = function (action, condition) {
1163
- this.fireChangedEvent({
1164
- part: QueryChangePart.Conditions,
1165
- action: action,
1166
- changee: condition
1167
- });
1168
- };
1169
- /**
1170
- * Runs through condition with this callback.
1171
- * @param processCondition The function to process condition.
1172
- */
1173
- Query.prototype.runThroughConditions = function (processCondition) {
1174
- var processGroup = function (predicate) {
1175
- for (var i = 0; i < predicate.getConditions().length; i++) {
1176
- var cond = predicate.getConditions()[i];
1177
- if (cond.isGroup()) {
1178
- processGroup(cond);
1179
- }
1180
- else {
1181
- if (processCondition)
1182
- processCondition(cond);
1183
- }
1184
- }
1185
- };
1186
- processGroup(this.getRootCondition());
1187
- };
1188
- /**
1189
- * Gets one value for the attribute
1190
- * @param attrId The attribute ID.
1191
- * @retruns The value.
1192
- */
1193
- Query.prototype.getOneValueForAttr = function (attrId) {
1194
- var res = null;
1195
- this.runThroughConditions(function (cond) {
1196
- if (cond.enabled) {
1197
- var expr = cond.expressions[0];
1198
- var opid = cond.getOperatorId();
1199
- if (expr.value == attrId && cond.expressions[1] &&
1200
- (opid == "Equal" || opid == "InList" || opid == "StartsWith")) {
1201
- res = cond.expressions[1].value;
1202
- }
1203
- }
1204
- });
1205
- return res;
1206
- };
1207
- /**
1208
- * Gets root predicate
1209
- * @retruns The condition.
1210
- */
1211
- Query.prototype.getRootCondition = function () {
1212
- return this.root;
1213
- };
1214
- /**
1215
- * Add process callback
1216
- * @param callback The callback.
1217
- * @retruns The callback ID.
1218
- */
1219
- Query.prototype.addProcessCallback = function (callback) {
1220
- return this.eventEmitter.subscribe('query.process', callback);
1221
- };
1222
- /**
1223
- * Remove process callback
1224
- * @param callbackId The callback ID.
1225
- */
1226
- Query.prototype.removeProcessCallback = function (callbackId) {
1227
- this.eventEmitter.unsubscribe('query.process', callbackId);
1228
- };
1229
- /**
1230
- * Add changed callback
1231
- * @param callback The callback ID.
1232
- */
1233
- Query.prototype.addChangedCallback = function (callback) {
1234
- return this.eventEmitter.subscribe('query.change', callback);
1235
- };
1236
- /**
1237
- * Remove changed callback
1238
- * @param callbackId The callback ID.
1239
- */
1240
- Query.prototype.removeChangedCallback = function (callbackId) {
1241
- this.eventEmitter.unsubscribe('query.change', callbackId);
1242
- };
1243
- /**
1244
- * Retruns conditions text
1245
- */
1246
- Query.prototype.getConditionsText = function () {
1247
- var _this = this;
1248
- var model = this.getModel();
1249
- if (!model)
1250
- return '';
1251
- var getConditionGroupText = function (group) {
1252
- var result = '', conjKey = "Conj" + equtils.linkTypeToStr(group.linkType), conjText = i18n.getText(conjKey), condText, i;
1253
- for (i = 0; i < group.getConditions().length; i++) {
1254
- condText = "";
1255
- var cond = group.getConditions()[i];
1256
- if (cond.enabled || typeof (cond.enabled) === "undefined") {
1257
- if (cond.isGroup()) {
1258
- condText = getConditionGroupText(cond);
1259
- if (condText) {
1260
- condText = "(" + condText + ")";
1261
- }
1262
- }
1263
- else {
1264
- var opId = cond.getOperatorId();
1265
- var operator = model.getOperatorById(opId);
1266
- var parts = equtils.parseOperatorFormat(operator);
1267
- var plen = parts.length;
1268
- for (var pi = 0; pi < plen; pi++) {
1269
- var part = parts[pi];
1270
- var txt = part.text;
1271
- if (part.type == "expression") {
1272
- var expr = cond.expressions[part.index];
1273
- if (expr.kind == DataKind.Attribute || expr.tag == ExprTag.EntityAttribute) {
1274
- var attr = model.getAttributeById(expr.value);
1275
- txt = model.getAttributeText(attr, "{entity} {attr}");
1276
- }
1277
- else {
1278
- txt = expr.getText();
1279
- if (_this.model.isDateMacro(txt) || _this.model.isTimeMacro(txt)) {
1280
- var macroText = txt.substring(3, txt.length - 2);
1281
- var res = i18n.getText(macroText);
1282
- txt = res || txt;
1283
- }
1284
- }
1285
- }
1286
- if (pi > 0)
1287
- condText += " ";
1288
- condText += txt;
1289
- }
1290
- }
1291
- }
1292
- if (condText) {
1293
- if (i > 0 && result) {
1294
- result += " " + conjText + " ";
1295
- }
1296
- result += condText;
1297
- }
1298
- }
1299
- if (group.linkType == LinkType.None || group.linkType == LinkType.NotAll) {
1300
- result = "not ( " + result + " )";
1301
- }
1302
- return result;
1303
- };
1304
- return getConditionGroupText(this.getRootCondition());
1305
- };
1306
- /**
1307
- * Retruns conditions text
1308
- */
1309
- Query.prototype.getConditionsTextAsHtml = function () {
1310
- var _this = this;
1311
- var model = this.getModel();
1312
- if (!model)
1313
- return '<div class="eqjs-query-text"></div>';
1314
- var quoteExprText = function (expr) {
1315
- if (expr.kind == DataKind.Query) {
1316
- return "&lt;" + expr.getText() + "&gt;";
1317
- }
1318
- else if (expr.kind == DataKind.List) {
1319
- return "[" + expr.getText() + "]";
1320
- }
1321
- else if (expr.dataType == DataType.String
1322
- || expr.dataType == DataType.Memo
1323
- || expr.dataType == DataType.FixedChar) {
1324
- return "&quot;" + expr.getText() + "&quot;";
1325
- }
1326
- else {
1327
- var txt = expr.getText();
1328
- if (_this.model.isDateMacro(txt) || _this.model.isTimeMacro(txt)) {
1329
- var macroText = txt.substring(3, txt.length - 2);
1330
- var res = i18n.getText(macroText);
1331
- txt = res || txt;
1332
- }
1333
- return txt;
1334
- }
1335
- };
1336
- var getConditionGroupText = function (group) {
1337
- var result = '', conjKey = "Conj" + equtils.linkTypeToStr(group.linkType), conjText = "<span class=\"eqjs-query-text-conj\">" + i18n.getText(conjKey) + "</span>", condText, i;
1338
- for (i = 0; i < group.getConditions().length; i++) {
1339
- condText = "";
1340
- var cond = group.getConditions()[i];
1341
- if (cond.enabled || typeof (cond.enabled) === "undefined") {
1342
- if (cond.isGroup()) {
1343
- condText = getConditionGroupText(cond);
1344
- if (condText) {
1345
- condText = "(" + condText + ")";
1346
- }
1347
- }
1348
- else {
1349
- var opId = cond.getOperatorId();
1350
- var operator = model.getOperatorById(opId);
1351
- var parts = equtils.parseOperatorFormat(operator);
1352
- var plen = parts.length;
1353
- for (var pi = 0; pi < plen; pi++) {
1354
- var part = parts[pi];
1355
- var txt = part.text;
1356
- if (part.type == "expression") {
1357
- var expr = cond.expressions[part.index];
1358
- if (expr.kind == DataKind.Attribute || expr.tag == ExprTag.EntityAttribute) {
1359
- var attr = model.getAttributeById(expr.value);
1360
- txt = "<span class=\"eqjs-query-text-attr\">" + model.getAttributeText(attr, "{entity} {attr}") + "</span>";
1361
- }
1362
- else {
1363
- txt = "<span class=\"eqjs-query-text-expr\">" + quoteExprText(expr) + "</span>";
1364
- }
1365
- }
1366
- else if (part.type == "operator") {
1367
- txt = "<span class=\"eqjs-query-text-op\">" + txt + "</span>";
1368
- }
1369
- if (pi > 0)
1370
- condText += " ";
1371
- condText += txt;
1372
- }
1373
- }
1374
- }
1375
- if (condText) {
1376
- if (i > 0 && result) {
1377
- result += " " + conjText + " ";
1378
- }
1379
- result += condText;
1380
- }
1381
- }
1382
- if (group.linkType == LinkType.None || group.linkType == LinkType.NotAll) {
1383
- result = "<span class=\"eqjs-query-text-conj\">not</span> ( " + result + " )";
1384
- }
1385
- return result;
1386
- };
1387
- return "<div class=\"eqjs-query-text\">" + getConditionGroupText(this.getRootCondition()) + "</div>";
1388
- };
1389
- return Query;
1390
- }());
1391
- export { Query };
1
+ var __extends = (this && this.__extends) || (function () {
2
+ var extendStatics = function (d, b) {
3
+ extendStatics = Object.setPrototypeOf ||
4
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6
+ return extendStatics(d, b);
7
+ };
8
+ return function (d, b) {
9
+ if (typeof b !== "function" && b !== null)
10
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
11
+ extendStatics(d, b);
12
+ function __() { this.constructor = d; }
13
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14
+ };
15
+ })();
16
+ import { EventEmitter, utils as dataUtils, AggregationSettings, DataType } from '@easydata/core';
17
+ import { i18n } from '@easydata/core';
18
+ import { equtils } from '../utils/utils';
19
+ import { DataModel } from '../dm/data_model';
20
+ import { Expression } from './expression';
21
+ import { QueryColumn, SortDirection } from './query_column';
22
+ import { Condition } from './condition';
23
+ import { DataKind } from '../types/data_kind';
24
+ import { LinkType } from '../types/link_type';
25
+ import { ExprTag } from '../types/expr_tag';
26
+ import { CondTag } from '../types/cond_tag';
27
+ import { QueryChangePart } from './query_events';
28
+ /**
29
+ * The error that appears when the query is not valid
30
+ */
31
+ var InvalidQueryError = /** @class */ (function (_super) {
32
+ __extends(InvalidQueryError, _super);
33
+ /**
34
+ * Creates an instance of error type.
35
+ * @param message The error message
36
+ */
37
+ function InvalidQueryError(message) {
38
+ var _this = _super.call(this, message) || this;
39
+ if (Error.captureStackTrace) {
40
+ Error.captureStackTrace(_this, InvalidQueryError);
41
+ }
42
+ _this.name = 'InvalidQueryError';
43
+ return _this;
44
+ }
45
+ return InvalidQueryError;
46
+ }(Error));
47
+ export { InvalidQueryError };
48
+ /**
49
+ * Represents Query.
50
+ */
51
+ var Query = /** @class */ (function () {
52
+ /**
53
+ * The default constructor.
54
+ * @param model The data model.
55
+ * @param data JSON representation object.
56
+ * @param options The options.
57
+ * @throws {InvalidQueryError} The error throws when query is not valid.
58
+ */
59
+ function Query(model, data, options) {
60
+ var _this = this;
61
+ /**
62
+ * Contains user-defined extra data for current query.
63
+ */
64
+ this.extraData = {};
65
+ this.innerData = {};
66
+ this.isNewbie = true;
67
+ this._isModified = false;
68
+ this._enableAggregation = false;
69
+ this.parentQuery = null;
70
+ this.drillDowns = [];
71
+ this.eventEmitter = new EventEmitter(this);
72
+ this.root = new Condition(this, CondTag.Group);
73
+ this.extraConditions = new Condition(this, CondTag.Group);
74
+ this.columns = new Array();
75
+ this.justsorted = new Array();
76
+ if (!this.id) {
77
+ this.regenerateId();
78
+ }
79
+ this.setDefaultName();
80
+ this.description = "";
81
+ this.model = (model) ? model : new DataModel();
82
+ if (data) {
83
+ this.loadFromData(data);
84
+ }
85
+ this.attributeExprTag = (options) ? options.attrTag || ExprTag.EntityAttribute : ExprTag.EntityAttribute;
86
+ this.clientListRequestHandler = (options) ? options.clientListRequestHandler : new Array();
87
+ this.serverListRequestHandler = (options) ? options.serverListRequestHandler : new Array();
88
+ this.timezoneOffset = (new Date()).getTimezoneOffset();
89
+ this.aggrSettings = new AggregationSettings(this);
90
+ if (options) {
91
+ this.parentQuery = options.parent;
92
+ }
93
+ this.addChangedCallback(function (ev) {
94
+ if (ev.data
95
+ && ((ev.data.part & QueryChangePart.Columns) > 0)
96
+ && !ev.data.aggregation) {
97
+ if (_this._enableAggregation && _this.updateAggregationSettings()) {
98
+ _this.fireChangedEvent({
99
+ part: QueryChangePart.Aggregation
100
+ });
101
+ }
102
+ }
103
+ });
104
+ }
105
+ Query.prototype.isModified = function () {
106
+ return this._isModified;
107
+ };
108
+ Query.prototype.resetModified = function () {
109
+ this._isModified = false;
110
+ };
111
+ Object.defineProperty(Query.prototype, "enableAggregation", {
112
+ get: function () {
113
+ return this._enableAggregation;
114
+ },
115
+ set: function (value) {
116
+ var oldValue = this._enableAggregation;
117
+ this._enableAggregation = value;
118
+ if (!oldValue && value) {
119
+ this.processQueryForAggregation();
120
+ var aggrCols = this.columns.filter(function (c) { return c.enabled
121
+ && c.expr.tag == ExprTag.AggregateFunction; });
122
+ }
123
+ if (!this._enableAggregation) {
124
+ this.aggrSettings.clear();
125
+ }
126
+ },
127
+ enumerable: false,
128
+ configurable: true
129
+ });
130
+ Query.prototype.updateAggregationSettings = function () {
131
+ var hasChanged = false;
132
+ var aggrSettings = this.getAggregationSettings();
133
+ for (var i = aggrSettings.groups.length - 1; i >= 0; i--) {
134
+ var group = aggrSettings.groups[i];
135
+ var _loop_1 = function (j) {
136
+ var colId = group.columns[j];
137
+ if (!this_1.columns.find(function (col) { return col.id === colId; })) {
138
+ group.columns.splice(j, 1);
139
+ hasChanged = true;
140
+ }
141
+ };
142
+ var this_1 = this;
143
+ for (var j = group.columns.length - 1; j >= 0; j--) {
144
+ _loop_1(j);
145
+ }
146
+ if (group.columns.length == 0) {
147
+ aggrSettings.groups.slice(i, 1);
148
+ }
149
+ }
150
+ var aggregates = aggrSettings.getAggregates();
151
+ var _loop_2 = function (i) {
152
+ var aggr = aggregates[i];
153
+ if (!this_2.columns.find(function (col) { return col.id === aggr.colId; })) {
154
+ aggregates.splice(i, 1);
155
+ hasChanged = true;
156
+ }
157
+ };
158
+ var this_2 = this;
159
+ for (var i = aggregates.length - 1; i >= 0; i--) {
160
+ _loop_2(i);
161
+ }
162
+ return hasChanged;
163
+ };
164
+ Query.prototype.createSubQuery = function () {
165
+ return new Query(this.model);
166
+ };
167
+ Query.prototype.useAggregation = function (settingsTuner, silent) {
168
+ if (silent === void 0) { silent = false; }
169
+ this.aggrSettings.clear();
170
+ settingsTuner(this.aggrSettings);
171
+ if (this.enableAggregation) {
172
+ this.processQueryForAggregation(silent);
173
+ }
174
+ else if (!silent) {
175
+ console.warn('Aggregation is turned off. Turn it on with query.enableAggregation = true');
176
+ return;
177
+ }
178
+ };
179
+ Query.prototype.useDefaultAggregation = function () {
180
+ var _this = this;
181
+ this._enableAggregation = true;
182
+ this.useAggregation(function (settings) {
183
+ var aggrCols = _this.columns.filter(function (c) { return c.enabled
184
+ && c.expr.tag == ExprTag.AggregateFunction; });
185
+ if (aggrCols.length) {
186
+ // query contains aggregate columns
187
+ var colsToGroup = _this.columns.filter(function (c) { return c.enabled
188
+ && c.expr.tag == ExprTag.EntityAttribute; });
189
+ var aggrsToAdd = [];
190
+ for (var _i = 0, aggrCols_1 = aggrCols; _i < aggrCols_1.length; _i++) {
191
+ var col = aggrCols_1[_i];
192
+ aggrsToAdd.push({ id: col.id, func: col.expr.func });
193
+ _this.changeColumnType(col, ExprTag.EntityAttribute);
194
+ }
195
+ for (var _a = 0, aggrsToAdd_1 = aggrsToAdd; _a < aggrsToAdd_1.length; _a++) {
196
+ var aggr = aggrsToAdd_1[_a];
197
+ settings.addAggregateColumn(aggr.id, aggr.func);
198
+ }
199
+ for (var _b = 0, colsToGroup_1 = colsToGroup; _b < colsToGroup_1.length; _b++) {
200
+ var col = colsToGroup_1[_b];
201
+ settings.addGroup({ columns: [col.id], name: col.caption });
202
+ }
203
+ settings.addGrandTotals();
204
+ _this.fireChangedEvent({
205
+ part: QueryChangePart.Columns,
206
+ wasModified: false
207
+ });
208
+ }
209
+ else {
210
+ // query does not has any aggr columns
211
+ var colToAggr = _this.getColumns()
212
+ .filter(function (c) { return c.enabled && c.expr.tag == ExprTag.EntityAttribute
213
+ && _this.model.getAttributeById(c.expr.value).dataType === DataType.Currency; })[0];
214
+ var colToGroup = _this.getColumns()
215
+ .filter(function (c) { return c.enabled && c.expr.tag == ExprTag.EntityAttribute
216
+ && _this.model.getAttributeById(c.expr.value).dataType === DataType.String; })[0];
217
+ if ((!colToAggr && !settings.hasAggregates()) || !colToGroup)
218
+ return;
219
+ settings.addGrandTotals()
220
+ .addAggregateColumn(colToAggr.id, 'SUM')
221
+ .addGroup({ columns: [colToGroup.id], name: 'Default' });
222
+ }
223
+ });
224
+ };
225
+ Query.prototype.processQueryForAggregation = function (silent) {
226
+ if (silent === void 0) { silent = false; }
227
+ var aggrSettings = this.getAggregationSettings();
228
+ var groups = aggrSettings.getGroups();
229
+ if (groups.length > 0) {
230
+ var groupColIds = groups[groups.length - 1].columns;
231
+ //take the list of grouped columns from the latest group
232
+ var groupedCols = [];
233
+ var sortedCols = [];
234
+ for (var _i = 0, _a = this.getColumns(); _i < _a.length; _i++) {
235
+ var col = _a[_i];
236
+ if (groupColIds.indexOf(col.id) >= 0) {
237
+ groupedCols.push(col);
238
+ }
239
+ else if (col.sorting != SortDirection.None) {
240
+ sortedCols.push(col);
241
+ }
242
+ }
243
+ var sortIndex_1 = 0;
244
+ groupedCols.forEach(function (col) {
245
+ if (col.sorting == SortDirection.None) {
246
+ col.sorting = SortDirection.Ascending;
247
+ }
248
+ col.sortIndex = sortIndex_1++;
249
+ });
250
+ sortedCols.forEach(function (col) {
251
+ col.sortIndex = sortIndex_1++;
252
+ });
253
+ if (!silent) {
254
+ this.fireChangedEvent({
255
+ part: QueryChangePart.Columns,
256
+ aggregation: true,
257
+ wasModified: false
258
+ });
259
+ }
260
+ }
261
+ };
262
+ Query.prototype.getAggregationSettings = function () {
263
+ return this.aggrSettings;
264
+ };
265
+ Query.prototype.getColumnIds = function (from, to) {
266
+ to = to || from;
267
+ return this.columns.slice(from, to - from + 1)
268
+ .map(function (c) { return c.id; });
269
+ };
270
+ /**
271
+ * Checks if the columns with IDs passed in function's parameter exist and are valid
272
+ */
273
+ Query.prototype.validateColumns = function (colIds) {
274
+ var enabledColIds = this.columns.filter(function (c) { return c.enabled; }).map(function (c) { return c.id; });
275
+ var prevIndex = -1;
276
+ for (var _i = 0, colIds_1 = colIds; _i < colIds_1.length; _i++) {
277
+ var col = colIds_1[_i];
278
+ var index = enabledColIds.indexOf(col);
279
+ if (index < 0)
280
+ return false;
281
+ if (prevIndex > index)
282
+ return false;
283
+ prevIndex = index;
284
+ }
285
+ return true;
286
+ };
287
+ Query.prototype.validateAggregate = function (colId, funcId) {
288
+ var col = this.columns.filter(function (c) { return c.enabled && c.id === colId; })[0];
289
+ var func = this.model.findAggrFunctionById(funcId);
290
+ if (!func || !col || func.appliedTypes.indexOf(col.expr.dataType) < 0)
291
+ return false;
292
+ return true;
293
+ };
294
+ Query.prototype.isEx = function () {
295
+ return false;
296
+ };
297
+ /**
298
+ * Resets the query: clears all its conditions and columns, regenerate the ID and sets the default name.
299
+ * @param silent Indicates whether we need to avoid firing the QueryChanged event.
300
+ */
301
+ Query.prototype.reset = function (clearQuery) {
302
+ if (clearQuery === void 0) { clearQuery = true; }
303
+ if (clearQuery) {
304
+ this.clear();
305
+ }
306
+ this.regenerateId();
307
+ this.setDefaultName();
308
+ this._isModified = false;
309
+ this.isNewbie = true;
310
+ };
311
+ Query.prototype.hasEnabledAggrColumns = function () {
312
+ return this.columns.filter(function (col) { return col.enabled
313
+ && col.expr.tag === ExprTag.AggregateFunction; }).length > 0;
314
+ };
315
+ Query.prototype.setDefaultName = function () {
316
+ this.setName(i18n.getText('NewQueryName'));
317
+ return this.getName();
318
+ };
319
+ /**
320
+ * Validates wether the query corresponds to the model.
321
+ * @param options Validate options.
322
+ * @throws {InvalidQueryError} If query is not valid.
323
+ */
324
+ Query.prototype.validate = function (options) {
325
+ options = options || {};
326
+ var entityAttrNotExistError = "EntityAttribute isn't declared in the model: ";
327
+ var wrongExprTag = "The expression has wrond tag: ";
328
+ if (!this.model) {
329
+ throw new InvalidQueryError("Model is not declared");
330
+ }
331
+ if (this.columns) {
332
+ for (var _i = 0, _a = this.columns; _i < _a.length; _i++) {
333
+ var column = _a[_i];
334
+ if (column.expr.tag == ExprTag.EntityAttribute
335
+ || column.expr.tag === ExprTag.ParentEntityAttribute) {
336
+ var attr = this.model.getAttributeById(column.expr.value);
337
+ if (!attr) {
338
+ throw new InvalidQueryError(entityAttrNotExistError + column.expr.value);
339
+ }
340
+ }
341
+ else if (column.expr.tag === ExprTag.AggregateFunction) {
342
+ var attr = this.model.getAttributeById(column.expr.args[0].value);
343
+ if (!attr) {
344
+ throw new InvalidQueryError(entityAttrNotExistError + column.expr.args[0].value);
345
+ }
346
+ }
347
+ else if (column.expr.tag !== ExprTag.CustomSql) {
348
+ throw new InvalidQueryError(wrongExprTag + column.expr.tag);
349
+ }
350
+ }
351
+ }
352
+ if (this.root && this.root.getConditions()) {
353
+ this.validateConditionGroup(this.root, options);
354
+ }
355
+ };
356
+ Query.prototype.getAggregatedColumns = function () {
357
+ return this.getColumns().filter(function (col) { return col.enabled
358
+ && col.expr.tag === ExprTag.AggregateFunction; });
359
+ };
360
+ /**
361
+ * Validates wether the query corresponds to the model.
362
+ * @param options Validate options.
363
+ * @returns `true` if it is valid, otherwise `false`
364
+ */
365
+ Query.prototype.tryValidate = function (options) {
366
+ try {
367
+ this.validate(options);
368
+ return true;
369
+ }
370
+ catch (e) {
371
+ if (e instanceof InvalidQueryError) {
372
+ return false;
373
+ }
374
+ else {
375
+ throw e;
376
+ }
377
+ }
378
+ };
379
+ Query.prototype.validateConditionGroup = function (curCond, options) {
380
+ if (curCond.isGroup()) {
381
+ for (var _i = 0, _a = curCond.getConditions(); _i < _a.length; _i++) {
382
+ var condition = _a[_i];
383
+ if (!condition.enabled)
384
+ continue;
385
+ this.validateConditionGroup(condition, options);
386
+ }
387
+ }
388
+ else if (curCond.expressions[0].tag === ExprTag.EntityAttribute) {
389
+ var attrId = curCond.expressions[0].value;
390
+ var attr = this.model.getAttributeById(attrId);
391
+ if (!attr) {
392
+ throw new InvalidQueryError("EntityAttribute isn't declared in the model: " + attrId);
393
+ }
394
+ if (!options.checkExpressions)
395
+ return;
396
+ for (var i = 1; i < curCond.expressions.length; i++) {
397
+ var expr = curCond.expressions[i];
398
+ if (expr.tag !== ExprTag.Constant)
399
+ continue;
400
+ //validate number exprs
401
+ if (dataUtils.isNumericType(expr.dataType)) {
402
+ if (!expr.value)
403
+ continue;
404
+ var values = [];
405
+ if (expr.kind === DataKind.List) {
406
+ values = expr.value.split(/\s*,\s*/);
407
+ }
408
+ else {
409
+ values = [expr.value];
410
+ }
411
+ for (var _b = 0, values_1 = values; _b < values_1.length; _b++) {
412
+ var value = values_1[_b];
413
+ var parsedVal = +value;
414
+ if (isNaN(parsedVal)) {
415
+ throw new InvalidQueryError("Expression constant is NaN in condition:" + curCond.id);
416
+ }
417
+ if (dataUtils.isIntType(expr.dataType) && parsedVal != parseInt(value, 10)) {
418
+ throw new InvalidQueryError("Expression constant is wrong interger in condition: " + curCond.id);
419
+ }
420
+ }
421
+ }
422
+ }
423
+ }
424
+ };
425
+ /**
426
+ * Sets data to the query.
427
+ * @param data JSON representation object or JSON string
428
+ * @param changeStatus Indicate whether we should change the "isModified" status (by default == `true`)
429
+ */
430
+ Query.prototype.loadFromDataOrJson = function (data, options) {
431
+ if (data) {
432
+ if (typeof data === "string") {
433
+ this.loadFromJson(data, options);
434
+ }
435
+ else {
436
+ this.loadFromData(data, options);
437
+ }
438
+ }
439
+ };
440
+ /**
441
+ * Loads query from JSON.
442
+ * @param json The JSON string.
443
+ * @param options The options.
444
+ * @throws {InvalidQueryError} The error throws when query is not valid.
445
+ */
446
+ Query.prototype.loadFromJson = function (json, options) {
447
+ var data = JSON.parse(json);
448
+ this.loadFromData(data, options);
449
+ };
450
+ /**
451
+ * Loads query from data representation.
452
+ * @param data The query DTO.
453
+ * @param options The options.
454
+ * @throws {InvalidQueryError} The error throws when query is not valid.
455
+ */
456
+ Query.prototype.loadFromData = function (data, options) {
457
+ var _this = this;
458
+ options = dataUtils.assign({
459
+ changeStatus: true,
460
+ validate: true
461
+ }, options || {});
462
+ var noErrors = false;
463
+ this.clear();
464
+ this.clearDrillDowns();
465
+ if (data) {
466
+ this.id = data.id;
467
+ this.root.loadFromData(this.model, data.root);
468
+ if (data.root && data.root.conds) {
469
+ for (var i = 0; i < data.root.conds.length; i++) {
470
+ var condData = data.root.conds[i];
471
+ if (condData.conds && !this.isEx()) {
472
+ console.error("Community version doesn't support working with groups.");
473
+ continue;
474
+ }
475
+ var cond = this.createCondition();
476
+ cond.loadFromData(this.model, condData);
477
+ this.root.addCondition(cond);
478
+ }
479
+ }
480
+ this.name = data.name;
481
+ this.description = data.desc;
482
+ this.justsorted = [];
483
+ if (data.justsortcols) {
484
+ for (var i = 0; i < data.justsortcols.length; i++) {
485
+ var newCol = this.createColumn(true);
486
+ newCol.loadFromData(this.model, data.justsortcols[i]);
487
+ this.justsorted.push(newCol);
488
+ }
489
+ }
490
+ if (data.cols) {
491
+ for (var i = 0; i < data.cols.length; i++) {
492
+ var newCol = this.createColumn();
493
+ newCol.loadFromData(this.model, data.cols[i]);
494
+ this.columns.push(newCol);
495
+ }
496
+ }
497
+ if (data.extraData) {
498
+ this.extraData = data.extraData;
499
+ }
500
+ this.innerData = data.innerData || this.innerData;
501
+ if (this.innerData && this.innerData.aggr) {
502
+ this._enableAggregation = this.innerData.aggr.enabled || false;
503
+ this.useAggregation(function (settings) {
504
+ settings.loadFromData(_this.innerData.aggr);
505
+ }, true);
506
+ }
507
+ if (data.dds && data.dds.length) {
508
+ for (var _i = 0, _a = data.dds; _i < _a.length; _i++) {
509
+ var dd = _a[_i];
510
+ var query = this.addDrillDown();
511
+ query.loadFromData(dd);
512
+ }
513
+ }
514
+ }
515
+ noErrors = true;
516
+ if (noErrors) {
517
+ if (options.changeStatus) {
518
+ this.isNewbie = false;
519
+ this._isModified = false;
520
+ }
521
+ }
522
+ if (options.validate) {
523
+ this.validate();
524
+ }
525
+ };
526
+ /**
527
+ *
528
+ */
529
+ Query.prototype.addDrillDown = function () {
530
+ var query = this.model.createQuery();
531
+ query.parentQuery = this;
532
+ this.drillDowns.push(query);
533
+ return query;
534
+ };
535
+ Query.prototype.getDrillDowns = function () {
536
+ return this.drillDowns;
537
+ };
538
+ Query.prototype.getParentQuery = function () {
539
+ return this.parentQuery;
540
+ };
541
+ /**
542
+ *
543
+ */
544
+ Query.prototype.findColumnById = function (colId) {
545
+ for (var _i = 0, _a = this.columns; _i < _a.length; _i++) {
546
+ var col = _a[_i];
547
+ if (col.id === colId)
548
+ return col;
549
+ }
550
+ return null;
551
+ };
552
+ /**
553
+ * Gets DataModel object associated with this query.
554
+ * @retruns The data model.
555
+ */
556
+ Query.prototype.getModel = function () {
557
+ return this.model;
558
+ };
559
+ /**
560
+ * Sets DataModel object associated with this query.
561
+ * @param model The data model.
562
+ */
563
+ Query.prototype.setModel = function (model) {
564
+ this.model = model;
565
+ };
566
+ /**
567
+ * Loads data model.
568
+ * @param model JSON representation object or JSON string.
569
+ */
570
+ Query.prototype.loadModelData = function (model) {
571
+ this.model.setData(model);
572
+ };
573
+ /**
574
+ * Returns JSON representation of this query.
575
+ * @retruns JSON string.
576
+ */
577
+ Query.prototype.toJSON = function () {
578
+ return JSON.stringify(this.toJSONData());
579
+ };
580
+ /**
581
+ * Returns JSON representation of this query.
582
+ * @retruns JSON representation object.
583
+ */
584
+ Query.prototype.toJSONData = function () {
585
+ var _this = this;
586
+ var obj = {
587
+ modelId: this.model ? this.model.getId() : null,
588
+ modelName: this.model ? this.model.getName() : null
589
+ };
590
+ obj.id = this.id;
591
+ obj.name = this.name;
592
+ if (this.description) {
593
+ obj.desc = this.description;
594
+ }
595
+ obj.cols = [];
596
+ for (var i = 0; i < this.columns.length; i++) {
597
+ obj.cols.push(this.columns[i].saveToData());
598
+ }
599
+ obj.justsortcols = [];
600
+ for (var i = 0; i < this.justsorted.length; i++) {
601
+ obj.justsortcols.push(this.justsorted[i].saveToData());
602
+ }
603
+ if (this.extraData) {
604
+ obj.extraData = this.extraData;
605
+ }
606
+ if (this.innerData) {
607
+ obj.innerData = this.innerData;
608
+ obj.innerData.aggr = this.aggrSettings.saveToData();
609
+ obj.innerData.aggr.enabled = this._enableAggregation;
610
+ }
611
+ var rootCondToData = function (condGroup) {
612
+ var result = condGroup.saveToData();
613
+ result.conds = [];
614
+ var conditions = condGroup.getConditions();
615
+ for (var i = 0; i < conditions.length; i++) {
616
+ if (conditions[i].isGroup() && !_this.isEx()) {
617
+ console.error("Community version doesn't support working with groups.");
618
+ continue;
619
+ }
620
+ result.conds.push(conditions[i].saveToData());
621
+ }
622
+ return result;
623
+ };
624
+ obj.root = rootCondToData(this.root);
625
+ obj.extraConds = rootCondToData(this.extraConditions);
626
+ if (this.drillDowns.length > 0) {
627
+ obj.dds = [];
628
+ for (var _i = 0, _a = this.drillDowns; _i < _a.length; _i++) {
629
+ var dd = _a[_i];
630
+ obj.dds.push(dd.toJSONData());
631
+ }
632
+ }
633
+ obj.timezoneOffset = this.timezoneOffset;
634
+ obj.locale = i18n.getCurrentLocale();
635
+ return obj;
636
+ };
637
+ /**
638
+ * Checks wether query does not contains any condtion.
639
+ * @retruns `true` if query does not contain any condition, otherwise `false`.
640
+ */
641
+ Query.prototype.isEmptyConditions = function () {
642
+ return this.root.isEmpty();
643
+ };
644
+ /**
645
+ * Checks wether query does not contains any column.
646
+ * @retruns `true` if query does not contain any column, otherwise `false`.
647
+ */
648
+ Query.prototype.isEmptyColumns = function () {
649
+ return !this.columns || this.columns.length === 0;
650
+ };
651
+ /**
652
+ * Checks wether query does not contains any column and any condition.
653
+ * @retruns `true` if query does not contain any column and any condition, otherwise `false`.
654
+ */
655
+ Query.prototype.isEmpty = function () {
656
+ return this.isEmptyColumns() && this.isEmptyConditions();
657
+ };
658
+ /**
659
+ * Clears the query (all conditions, columns, extraData, etc).
660
+ */
661
+ Query.prototype.clear = function () {
662
+ this._enableAggregation = false;
663
+ this.aggrSettings.clear();
664
+ this.clearColumns();
665
+ this.clearConditions();
666
+ this.clearExtraConditions();
667
+ this.innerData = {};
668
+ this.extraData = {};
669
+ };
670
+ /**
671
+ * Clears all columns in query
672
+ */
673
+ Query.prototype.clearColumns = function () {
674
+ this.columns = [];
675
+ this.justsorted = [];
676
+ };
677
+ /**
678
+ * Clears all conditions in query.
679
+ */
680
+ Query.prototype.clearConditions = function () {
681
+ this.root.clearConditions();
682
+ this.root.linkType = LinkType.All;
683
+ this.root.enabled = true;
684
+ };
685
+ /**
686
+ * Clears all extra conditions in query
687
+ */
688
+ Query.prototype.clearExtraConditions = function () {
689
+ this.extraConditions.clearConditions();
690
+ };
691
+ /**
692
+ * Clears all drill downs
693
+ */
694
+ Query.prototype.clearDrillDowns = function () {
695
+ this.drillDowns = [];
696
+ };
697
+ /**
698
+ * Gets query ID.
699
+ * @returns The ID>
700
+ */
701
+ Query.prototype.getId = function () {
702
+ return this.id;
703
+ };
704
+ /**
705
+ * Sets query ID.
706
+ * @param id New Query ID.
707
+ */
708
+ Query.prototype.setId = function (id) {
709
+ this.id = id;
710
+ };
711
+ /**
712
+ * Regenerates current query ID.
713
+ * @param id New Query ID.
714
+ */
715
+ Query.prototype.regenerateId = function () {
716
+ this.id = dataUtils.generateId("quer");
717
+ };
718
+ /**
719
+ * Gets name of the query.
720
+ * @retruns The name.
721
+ */
722
+ Query.prototype.getName = function () {
723
+ return this.name;
724
+ };
725
+ /**
726
+ * Sets name of the query
727
+ * @param name New name.
728
+ */
729
+ Query.prototype.setName = function (name) {
730
+ this.name = name;
731
+ };
732
+ /**
733
+ * Gets description of the query.
734
+ * @retruns The description.
735
+ */
736
+ Query.prototype.getDescription = function () {
737
+ return this.description;
738
+ };
739
+ /**
740
+ * Sets description of the query
741
+ * @param description New description.
742
+ */
743
+ Query.prototype.setDescription = function (description) {
744
+ this.description = description;
745
+ };
746
+ /**
747
+ * Get array of columns.
748
+ * @retruns Columns.
749
+ */
750
+ Query.prototype.getColumns = function () {
751
+ return this.columns;
752
+ };
753
+ /**
754
+ * Gets array of columns that are used as keys
755
+ * for totals.
756
+ */
757
+ Query.prototype.getUsedInTotalsColumns = function () {
758
+ var aggrs = this.getAggregatedColumns();
759
+ if (aggrs.length === 0)
760
+ return [];
761
+ var cols = this.getColumns()
762
+ .filter(function (col) { return col.enabled && col.expr.tag === ExprTag.EntityAttribute; });
763
+ if (cols.length)
764
+ cols.pop();
765
+ return cols;
766
+ };
767
+ /**
768
+ * Get array of columns used only in sorting.
769
+ * @retruns Columns.
770
+ */
771
+ Query.prototype.getJustSortedColumns = function () {
772
+ return this.justsorted;
773
+ };
774
+ /**
775
+ * Gets array of columns used in sorting
776
+ * @retruns Columns
777
+ */
778
+ Query.prototype.getSortedColumns = function () {
779
+ var sortedCols = new Array();
780
+ var cols = this.getColumns()
781
+ .concat(this.getJustSortedColumns());
782
+ for (var i = 0; i < cols.length; i++) {
783
+ var col = cols[i];
784
+ if (col.sortIndex >= 0) {
785
+ sortedCols.push(col);
786
+ }
787
+ }
788
+ sortedCols.sort(function (col1, col2) {
789
+ return col1.sortIndex - col2.sortIndex;
790
+ });
791
+ return sortedCols;
792
+ };
793
+ /**
794
+ * Gets Colummn sorting index.
795
+ * @param col The column.
796
+ * @retruns The index.
797
+ */
798
+ Query.prototype.getColumnSortIndex = function (col) {
799
+ if (col.sorting != SortDirection.None) {
800
+ if (col.sortIndex < 0) {
801
+ var cols = this.getColumns()
802
+ .concat(this.getJustSortedColumns());
803
+ return dataUtils.indexOfArrayItem(cols, col);
804
+ }
805
+ else {
806
+ return col.sortIndex;
807
+ }
808
+ }
809
+ return -1;
810
+ };
811
+ Query.prototype.createColumn = function (justsorted) {
812
+ if (justsorted === void 0) { justsorted = false; }
813
+ return new QueryColumn(this, justsorted);
814
+ };
815
+ Query.prototype.getColumnById = function (id) {
816
+ return dataUtils.findItemById(this.columns, id);
817
+ };
818
+ /**
819
+ * Adds a new column with specified parameters
820
+ * @param desriptor The descriptor of the new column. Can contain different parameters like:
821
+ * `attribute` - a reference to a EntityAttr object,
822
+ * `attributeId` - an ID of the entity attribute we need (if we don't indicate `attribute`),
823
+ * `index`, sorting`, 'sortIndex` and other
824
+ *
825
+ * @param author The author of this operation. This parameter is used in EasyQuery widgets only to indicate which of the initiates the change.
826
+ * @retruns The column.
827
+ * @example
828
+ * query.addColumn({
829
+ * attributeId: 'Customers.CompanyName',
830
+ * sortIndex: SortDirection.Ascending
831
+ * }});
832
+ */
833
+ Query.prototype.addColumn = function (descriptor, author) {
834
+ var columns = (descriptor.justsorted)
835
+ ? this.justsorted
836
+ : this.columns;
837
+ var newColumn;
838
+ if (descriptor.column) {
839
+ newColumn = descriptor.column;
840
+ }
841
+ else {
842
+ newColumn = this.createColumn(descriptor.justsorted);
843
+ var attr = void 0;
844
+ if (descriptor.attribute) {
845
+ attr = descriptor.attribute;
846
+ }
847
+ else if (descriptor.attributeId) {
848
+ attr = this.model.getAttributeById(descriptor.attributeId);
849
+ if (!attr) {
850
+ throw new Error("Incorrect attribute id (".concat(descriptor.attributeId, "): addColumn"));
851
+ }
852
+ }
853
+ else {
854
+ throw new Error('Not enought data for addColumn operation. Need attribute or attributeId');
855
+ }
856
+ if (!attr.useInResult) {
857
+ if (attr.lookupAttr) {
858
+ attr = this.model.getAttributeById(attr.lookupAttr);
859
+ }
860
+ if (!attr || !attr.useInResult) {
861
+ throw new Error("Can't use this attribute for a column");
862
+ }
863
+ }
864
+ if (descriptor.aggrFuncId && descriptor.cusomtSql) {
865
+ console.warn("Column cannot be created using aggrFuncId and customSql at the same time. " +
866
+ "cusomSql will be used.");
867
+ }
868
+ if (descriptor.cusomtSql) {
869
+ newColumn.caption = 'Custom SQL Column';
870
+ newColumn.expr.tag = ExprTag.CustomSql;
871
+ newColumn.expr.baseAttrId = attr.id;
872
+ newColumn.expr.sql = descriptor.cusomtSql;
873
+ newColumn.expr.kind = DataKind.Query;
874
+ newColumn.expr.dataType = DataType.Unknown;
875
+ }
876
+ else if (descriptor.aggrFuncId) {
877
+ var funcId = descriptor.aggrFuncId;
878
+ newColumn.caption = attr.caption + ' '
879
+ + this.model.getAggrFunctionCaption(descriptor.aggrFuncId);
880
+ newColumn.expr.tag = ExprTag.AggregateFunction;
881
+ newColumn.expr.func = descriptor.aggrFuncId;
882
+ newColumn.expr.kind = DataKind.Scalar;
883
+ newColumn.expr.dataType = funcId == 'COUNT' || funcId == 'CNTDST' ? 4 : attr.dataType;
884
+ newColumn.expr.distinct = false;
885
+ var arg = new Expression(newColumn);
886
+ arg.setValue(attr.id, true);
887
+ arg.tag = ExprTag.EntityAttribute;
888
+ arg.dataType = attr.dataType;
889
+ newColumn.expr.args.push(arg);
890
+ }
891
+ else {
892
+ newColumn.caption = attr.caption;
893
+ newColumn.expr.setValue(attr.id, true);
894
+ newColumn.expr.tag = ExprTag.EntityAttribute;
895
+ newColumn.expr.dataType = attr.dataType;
896
+ }
897
+ newColumn.caption = descriptor.caption || newColumn.caption;
898
+ newColumn.sorting = descriptor.sorting || SortDirection.None;
899
+ newColumn.sortIndex = descriptor.sortIndex || -1;
900
+ newColumn.enabled = dataUtils.getIfDefined(descriptor.enabled, true);
901
+ newColumn.setReadOnly(dataUtils.getIfDefined(descriptor.readonly, false));
902
+ }
903
+ if (descriptor.index && descriptor.index >= 0 && descriptor.index < columns.length) {
904
+ columns.splice(descriptor.index, 0, newColumn);
905
+ }
906
+ else {
907
+ columns.push(newColumn);
908
+ }
909
+ return newColumn;
910
+ };
911
+ /**
912
+ * Adds a new column with specified index.
913
+ * @param column The column or array of columns
914
+ * @param index The index of new column
915
+ * @param author The author.
916
+ * @example
917
+ * const column = new Column();
918
+ * column.caption = "Company name";
919
+ *
920
+ * query.addColumn(column, 1)
921
+ */
922
+ Query.prototype.addColumnObj = function (column, index, author) {
923
+ var columns = this.columns;
924
+ if (typeof column.length == "undefined") {
925
+ if (typeof index == "number") {
926
+ columns.splice(index, 0, column);
927
+ }
928
+ else {
929
+ columns.push(column);
930
+ }
931
+ }
932
+ else {
933
+ if (typeof index == "number") {
934
+ columns.push.apply(columns, [index, 0].concat(column));
935
+ }
936
+ else {
937
+ columns.push.apply(columns, [].concat(column));
938
+ }
939
+ }
940
+ };
941
+ /**
942
+ * Changes column to Aggregate function, custom expression or simple column.
943
+ * @param column The column to change.
944
+ * @param tag New column expression tag.
945
+ * @param args The arguments (Contains aggregate function id)
946
+ */
947
+ Query.prototype.changeColumnType = function (column, tag, args) {
948
+ if (column.isJustSorted())
949
+ return;
950
+ args = args || {};
951
+ column.caption = (typeof args.caption !== 'undefined')
952
+ ? args.caption
953
+ : '';
954
+ if (tag === ExprTag.AggregateFunction) {
955
+ if (!args.funcId)
956
+ throw Error('"funcId" argument is not defined');
957
+ if (column.expr.tag == ExprTag.AggregateFunction) {
958
+ column.expr.func = args.funcId;
959
+ return;
960
+ }
961
+ var expr = new Expression(column);
962
+ expr.tag = ExprTag.AggregateFunction;
963
+ expr.func = args.funcId;
964
+ expr.distinct = false;
965
+ expr.dataType = args.funcId == 'COUNT' || args.funcId == 'CNTDST' ? 4 : column.expr.dataType;
966
+ var arg = new Expression(column);
967
+ arg.loadFromData(this.model, column.expr.saveToData());
968
+ expr.args.push(arg);
969
+ column.expr = expr;
970
+ }
971
+ else if (tag === ExprTag.CustomSql) {
972
+ var attrId = (column.expr.tag == ExprTag.AggregateFunction)
973
+ ? column.expr.args[0].value
974
+ : column.expr.value;
975
+ var sqlText = '';
976
+ if (this.model) {
977
+ sqlText = this.model.getAttributeById(attrId).expr;
978
+ }
979
+ var customSqlExpr = new Expression(column);
980
+ customSqlExpr.tag = ExprTag.CustomSql;
981
+ customSqlExpr.dataType = DataType.String; //the default data type
982
+ customSqlExpr.sql = sqlText;
983
+ customSqlExpr.baseAttrId = attrId;
984
+ column.expr = customSqlExpr;
985
+ }
986
+ else if (tag === ExprTag.EntityAttribute) {
987
+ if (column.expr.tag === ExprTag.EntityAttribute
988
+ || column.expr.tag === ExprTag.ParentEntityAttribute) {
989
+ return;
990
+ }
991
+ var exprId = (column.expr.tag === ExprTag.CustomSql)
992
+ ? column.expr.baseAttrId
993
+ : column.expr.args[0].value;
994
+ var attr = this.model.getAttributeById(exprId);
995
+ var expr = new Expression(column);
996
+ expr.tag = ExprTag.EntityAttribute;
997
+ expr.dataType = attr != null ? attr.dataType : DataType.Unknown;
998
+ expr.setValue(exprId, true);
999
+ column.expr = expr;
1000
+ }
1001
+ };
1002
+ /**
1003
+ * Moves the column with specified index to another position.
1004
+ * @param index1 The index of the column that should be moved.
1005
+ * @param index2 The index of the position the column should be moved to
1006
+ * @param author The author
1007
+ */
1008
+ Query.prototype.moveColumn = function (index1, index2) {
1009
+ var columns = this.getColumns();
1010
+ dataUtils.moveArrayItem(columns, index1, index2);
1011
+ };
1012
+ /**
1013
+ * Removes the column.
1014
+ * @param column The column to be removed.
1015
+ * @param author The author
1016
+ */
1017
+ Query.prototype.removeColumn = function (column, author) {
1018
+ var columns = (column.isJustSorted())
1019
+ ? this.getJustSortedColumns()
1020
+ : this.getColumns();
1021
+ dataUtils.removeArrayItem(columns, column);
1022
+ };
1023
+ /**
1024
+ * Adds a condition group - a group of simple conditions (predicates) linked by AND or OR
1025
+ * @param descriptor The descriptor of the new condition group.
1026
+ * @returns The new search condition.
1027
+ */
1028
+ Query.prototype.addConditionGroup = function (descriptor, addChildCondition) {
1029
+ if (addChildCondition === void 0) { addChildCondition = true; }
1030
+ console.error("Community version doesn't support working with groups.");
1031
+ return null;
1032
+ };
1033
+ Query.prototype.addExtraConditionGroup = function (descriptor, addChildCondition) {
1034
+ if (addChildCondition === void 0) { addChildCondition = true; }
1035
+ console.error("Community version doesn't support working with groups.");
1036
+ return null;
1037
+ };
1038
+ Query.prototype.createCondition = function (tag) {
1039
+ if (tag === void 0) { tag = CondTag.Simple; }
1040
+ return new Condition(this, tag);
1041
+ };
1042
+ /**
1043
+ * Adds a new simple condition (a predicate)
1044
+ * @param descriptor The descriptor which defines different parameters of the new condition
1045
+ * @returns The new condition.
1046
+ */
1047
+ Query.prototype.addSimpleCondition = function (descriptor) {
1048
+ var parent = descriptor.parent || this.getRootCondition();
1049
+ var model = this.getModel();
1050
+ if (!model)
1051
+ return null;
1052
+ if (!descriptor.attribute && !descriptor.attributeId) {
1053
+ throw new Error("Either `attribute` or `attributeId` parameter must have a value");
1054
+ }
1055
+ if (!descriptor.attribute) {
1056
+ descriptor.attribute = model.getAttributeById(descriptor.attributeId);
1057
+ if (!descriptor.attribute) {
1058
+ throw new Error("Could not find this attribute: " + descriptor.attributeId);
1059
+ }
1060
+ }
1061
+ if (!descriptor.operator && descriptor.operatorId) {
1062
+ descriptor.operator = model.getOperatorById(descriptor.operatorId);
1063
+ }
1064
+ if (!descriptor.operator) {
1065
+ descriptor.operator = model.getDefaultOperatorForAttr(descriptor.attribute);
1066
+ }
1067
+ var cond = this.createSimpleConditionObject(descriptor.attribute, descriptor.operator, descriptor.value);
1068
+ parent.addCondition(cond);
1069
+ cond.enabled = dataUtils.getIfDefined(descriptor.enabled, true);
1070
+ cond.setReadOnly(dataUtils.getIfDefined(descriptor.readonly, false));
1071
+ return cond;
1072
+ };
1073
+ Query.prototype.addSimpleExtraCondition = function (descriptor) {
1074
+ descriptor.parent = descriptor.parent || this.extraConditions;
1075
+ return this.addSimpleCondition(descriptor);
1076
+ };
1077
+ Query.prototype.createSimpleConditionObject = function (attr, operator, inputValues) {
1078
+ if (!attr || !attr.useInConditions) {
1079
+ var attrCaption = attr ? attr.caption : 'NULL';
1080
+ throw "Can't add a condition with such attribute: " + attrCaption;
1081
+ }
1082
+ var cond = this.createCondition(CondTag.Simple);
1083
+ cond.setOperatorId(operator.id, true);
1084
+ var attrExpr = new Expression(cond);
1085
+ attrExpr.setValue(attr.id, true);
1086
+ attrExpr.tag = this.attributeExprTag;
1087
+ attrExpr.kind = DataKind.Attribute;
1088
+ attrExpr.dataType = attr.dataType;
1089
+ cond.expressions.push(attrExpr);
1090
+ var model = this.getModel();
1091
+ var valCount = operator.paramCount;
1092
+ var values = dataUtils.fillArray(new Array(valCount - 1), null);
1093
+ if (inputValues !== null && typeof inputValues !== "undefined") {
1094
+ if (Array.isArray(inputValues)) {
1095
+ dataUtils.copyArrayTo(inputValues, values);
1096
+ }
1097
+ else if (valCount > 0) {
1098
+ values[0] = inputValues;
1099
+ }
1100
+ }
1101
+ var valLength = values.length;
1102
+ for (var i = 0; i < valLength; i++) {
1103
+ var operand = model.getOperand(attr, operator, i + 1);
1104
+ cond.addExpressionByOperand(operand, values[i]);
1105
+ }
1106
+ return cond;
1107
+ };
1108
+ /**
1109
+ * Removes several columns passed as array.
1110
+ * @param columnsToRemove The list of columns to be removed.
1111
+ * @param author The author.
1112
+ */
1113
+ Query.prototype.removeColumns = function (columnsToRemove, author) {
1114
+ var justSortedColumns = columnsToRemove.filter(function (c) { return c.isJustSorted(); });
1115
+ var columns = columnsToRemove.filter(function (c) { return !c.isJustSorted(); });
1116
+ function removeFromArray(arr, arrToRemove) {
1117
+ var ctrLen = arrToRemove.length;
1118
+ for (var i = 0; i < ctrLen; i++) {
1119
+ var index = arr.indexOf(arrToRemove[i]);
1120
+ if (index >= 0) {
1121
+ arr.splice(index, 1);
1122
+ }
1123
+ }
1124
+ }
1125
+ if (columns.length > 0) {
1126
+ removeFromArray(this.getColumns(), columns);
1127
+ }
1128
+ if (justSortedColumns.length > 0) {
1129
+ removeFromArray(this.getJustSortedColumns(), justSortedColumns);
1130
+ }
1131
+ };
1132
+ /**
1133
+ * Fires process event.
1134
+ * @param data The data.
1135
+ */
1136
+ Query.prototype.fireProcessEvent = function (data) {
1137
+ this.eventEmitter.fire('query.process', data);
1138
+ };
1139
+ Query.prototype.fireChangedEvent = function (params, postpone, wasModified) {
1140
+ params = params || { part: QueryChangePart.All };
1141
+ if (typeof (postpone) != 'undefined' || typeof (wasModified) != 'undefined') {
1142
+ params.postpone = postpone || 0;
1143
+ params.wasModified = wasModified;
1144
+ console.warn('Method with \'postpone\' and \'wasModified\' args is deprecated. Pass params in data object');
1145
+ }
1146
+ this._isModified = typeof (params.wasModified) != 'undefined'
1147
+ ? params.wasModified
1148
+ : true;
1149
+ var eventData = params || {
1150
+ part: QueryChangePart.All
1151
+ };
1152
+ this.eventEmitter.fire('query.change', eventData, params.postpone || 0);
1153
+ };
1154
+ Query.prototype.fireColumnsChangedEvent = function (action, column, justsorted) {
1155
+ if (justsorted === void 0) { justsorted = false; }
1156
+ this.fireChangedEvent({
1157
+ part: (justsorted)
1158
+ ? QueryChangePart.SortingColumns
1159
+ : QueryChangePart.Columns,
1160
+ action: action,
1161
+ changee: column
1162
+ });
1163
+ };
1164
+ Query.prototype.fireConditionsChangedEvent = function (action, condition) {
1165
+ this.fireChangedEvent({
1166
+ part: QueryChangePart.Conditions,
1167
+ action: action,
1168
+ changee: condition
1169
+ });
1170
+ };
1171
+ /**
1172
+ * Runs through condition with this callback.
1173
+ * @param processCondition The function to process condition.
1174
+ */
1175
+ Query.prototype.runThroughConditions = function (processCondition) {
1176
+ var processGroup = function (predicate) {
1177
+ for (var i = 0; i < predicate.getConditions().length; i++) {
1178
+ var cond = predicate.getConditions()[i];
1179
+ if (cond.isGroup()) {
1180
+ processGroup(cond);
1181
+ }
1182
+ else {
1183
+ if (processCondition)
1184
+ processCondition(cond);
1185
+ }
1186
+ }
1187
+ };
1188
+ processGroup(this.getRootCondition());
1189
+ };
1190
+ /**
1191
+ * Gets one value for the attribute
1192
+ * @param attrId The attribute ID.
1193
+ * @retruns The value.
1194
+ */
1195
+ Query.prototype.getOneValueForAttr = function (attrId) {
1196
+ var res = null;
1197
+ this.runThroughConditions(function (cond) {
1198
+ if (cond.enabled) {
1199
+ var expr = cond.expressions[0];
1200
+ var opid = cond.getOperatorId();
1201
+ if (expr.value == attrId && cond.expressions[1] &&
1202
+ (opid == "Equal" || opid == "InList" || opid == "StartsWith")) {
1203
+ res = cond.expressions[1].value;
1204
+ }
1205
+ }
1206
+ });
1207
+ return res;
1208
+ };
1209
+ /**
1210
+ * Gets root predicate
1211
+ * @retruns The condition.
1212
+ */
1213
+ Query.prototype.getRootCondition = function () {
1214
+ return this.root;
1215
+ };
1216
+ /**
1217
+ * Add process callback
1218
+ * @param callback The callback.
1219
+ * @retruns The callback ID.
1220
+ */
1221
+ Query.prototype.addProcessCallback = function (callback) {
1222
+ return this.eventEmitter.subscribe('query.process', callback);
1223
+ };
1224
+ /**
1225
+ * Remove process callback
1226
+ * @param callbackId The callback ID.
1227
+ */
1228
+ Query.prototype.removeProcessCallback = function (callbackId) {
1229
+ this.eventEmitter.unsubscribe('query.process', callbackId);
1230
+ };
1231
+ /**
1232
+ * Add changed callback
1233
+ * @param callback The callback ID.
1234
+ */
1235
+ Query.prototype.addChangedCallback = function (callback) {
1236
+ return this.eventEmitter.subscribe('query.change', callback);
1237
+ };
1238
+ /**
1239
+ * Remove changed callback
1240
+ * @param callbackId The callback ID.
1241
+ */
1242
+ Query.prototype.removeChangedCallback = function (callbackId) {
1243
+ this.eventEmitter.unsubscribe('query.change', callbackId);
1244
+ };
1245
+ /**
1246
+ * Retruns conditions text
1247
+ */
1248
+ Query.prototype.getConditionsText = function () {
1249
+ var _this = this;
1250
+ var model = this.getModel();
1251
+ if (!model)
1252
+ return '';
1253
+ var getConditionGroupText = function (group) {
1254
+ var result = '', conjKey = "Conj" + equtils.linkTypeToStr(group.linkType), conjText = i18n.getText(conjKey), condText, i;
1255
+ for (i = 0; i < group.getConditions().length; i++) {
1256
+ condText = "";
1257
+ var cond = group.getConditions()[i];
1258
+ if (cond.enabled || typeof (cond.enabled) === "undefined") {
1259
+ if (cond.isGroup()) {
1260
+ condText = getConditionGroupText(cond);
1261
+ if (condText) {
1262
+ condText = "(" + condText + ")";
1263
+ }
1264
+ }
1265
+ else {
1266
+ var opId = cond.getOperatorId();
1267
+ var operator = model.getOperatorById(opId);
1268
+ var parts = equtils.parseOperatorFormat(operator);
1269
+ var plen = parts.length;
1270
+ for (var pi = 0; pi < plen; pi++) {
1271
+ var part = parts[pi];
1272
+ var txt = part.text;
1273
+ if (part.type == "expression") {
1274
+ var expr = cond.expressions[part.index];
1275
+ if (expr.kind == DataKind.Attribute || expr.tag == ExprTag.EntityAttribute) {
1276
+ var attr = model.getAttributeById(expr.value);
1277
+ txt = model.getAttributeText(attr, "{entity} {attr}");
1278
+ }
1279
+ else {
1280
+ txt = expr.getText();
1281
+ if (_this.model.isDateMacro(txt) || _this.model.isTimeMacro(txt)) {
1282
+ var macroText = txt.substring(3, txt.length - 2);
1283
+ var res = i18n.getText(macroText);
1284
+ txt = res || txt;
1285
+ }
1286
+ }
1287
+ }
1288
+ if (pi > 0)
1289
+ condText += " ";
1290
+ condText += txt;
1291
+ }
1292
+ }
1293
+ }
1294
+ if (condText) {
1295
+ if (i > 0 && result) {
1296
+ result += " " + conjText + " ";
1297
+ }
1298
+ result += condText;
1299
+ }
1300
+ }
1301
+ if (group.linkType == LinkType.None || group.linkType == LinkType.NotAll) {
1302
+ result = "not ( " + result + " )";
1303
+ }
1304
+ return result;
1305
+ };
1306
+ return getConditionGroupText(this.getRootCondition());
1307
+ };
1308
+ /**
1309
+ * Retruns conditions text
1310
+ */
1311
+ Query.prototype.getConditionsTextAsHtml = function () {
1312
+ var _this = this;
1313
+ var model = this.getModel();
1314
+ if (!model)
1315
+ return '<div class="eqjs-query-text"></div>';
1316
+ var quoteExprText = function (expr) {
1317
+ if (expr.kind == DataKind.Query) {
1318
+ return "&lt;".concat(expr.getText(), "&gt;");
1319
+ }
1320
+ else if (expr.kind == DataKind.List) {
1321
+ return "[".concat(expr.getText(), "]");
1322
+ }
1323
+ else if (expr.dataType == DataType.String
1324
+ || expr.dataType == DataType.Memo
1325
+ || expr.dataType == DataType.FixedChar) {
1326
+ return "&quot;".concat(expr.getText(), "&quot;");
1327
+ }
1328
+ else {
1329
+ var txt = expr.getText();
1330
+ if (_this.model.isDateMacro(txt) || _this.model.isTimeMacro(txt)) {
1331
+ var macroText = txt.substring(3, txt.length - 2);
1332
+ var res = i18n.getText(macroText);
1333
+ txt = res || txt;
1334
+ }
1335
+ return txt;
1336
+ }
1337
+ };
1338
+ var getConditionGroupText = function (group) {
1339
+ var result = '', conjKey = "Conj" + equtils.linkTypeToStr(group.linkType), conjText = "<span class=\"eqjs-query-text-conj\">".concat(i18n.getText(conjKey), "</span>"), condText, i;
1340
+ for (i = 0; i < group.getConditions().length; i++) {
1341
+ condText = "";
1342
+ var cond = group.getConditions()[i];
1343
+ if (cond.enabled || typeof (cond.enabled) === "undefined") {
1344
+ if (cond.isGroup()) {
1345
+ condText = getConditionGroupText(cond);
1346
+ if (condText) {
1347
+ condText = "(" + condText + ")";
1348
+ }
1349
+ }
1350
+ else {
1351
+ var opId = cond.getOperatorId();
1352
+ var operator = model.getOperatorById(opId);
1353
+ var parts = equtils.parseOperatorFormat(operator);
1354
+ var plen = parts.length;
1355
+ for (var pi = 0; pi < plen; pi++) {
1356
+ var part = parts[pi];
1357
+ var txt = part.text;
1358
+ if (part.type == "expression") {
1359
+ var expr = cond.expressions[part.index];
1360
+ if (expr.kind == DataKind.Attribute || expr.tag == ExprTag.EntityAttribute) {
1361
+ var attr = model.getAttributeById(expr.value);
1362
+ txt = "<span class=\"eqjs-query-text-attr\">".concat(model.getAttributeText(attr, "{entity} {attr}"), "</span>");
1363
+ }
1364
+ else {
1365
+ txt = "<span class=\"eqjs-query-text-expr\">".concat(quoteExprText(expr), "</span>");
1366
+ }
1367
+ }
1368
+ else if (part.type == "operator") {
1369
+ txt = "<span class=\"eqjs-query-text-op\">".concat(txt, "</span>");
1370
+ }
1371
+ if (pi > 0)
1372
+ condText += " ";
1373
+ condText += txt;
1374
+ }
1375
+ }
1376
+ }
1377
+ if (condText) {
1378
+ if (i > 0 && result) {
1379
+ result += " " + conjText + " ";
1380
+ }
1381
+ result += condText;
1382
+ }
1383
+ }
1384
+ if (group.linkType == LinkType.None || group.linkType == LinkType.NotAll) {
1385
+ result = "<span class=\"eqjs-query-text-conj\">not</span> ( " + result + " )";
1386
+ }
1387
+ return result;
1388
+ };
1389
+ return "<div class=\"eqjs-query-text\">".concat(getConditionGroupText(this.getRootCondition()), "</div>");
1390
+ };
1391
+ return Query;
1392
+ }());
1393
+ export { Query };
1392
1394
  //# sourceMappingURL=query.js.map