@resolveio/server-lib 4.3.15 → 4.4.0

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.
@@ -0,0 +1,680 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __generator = (this && this.__generator) || function (thisArg, body) {
11
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
+ function verb(n) { return function (v) { return step([n, v]); }; }
14
+ function step(op) {
15
+ if (f) throw new TypeError("Generator is already executing.");
16
+ while (_) try {
17
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18
+ if (y = 0, t) op = [op[0] & 2, t.value];
19
+ switch (op[0]) {
20
+ case 0: case 1: t = op; break;
21
+ case 4: _.label++; return { value: op[1], done: false };
22
+ case 5: _.label++; y = op[1]; op = [0]; continue;
23
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
+ default:
25
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
+ if (t[2]) _.ops.pop();
30
+ _.trys.pop(); continue;
31
+ }
32
+ op = body.call(thisArg, _);
33
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
+ }
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ var simpl_schema_1 = require("simpl-schema");
39
+ var pagination_model_1 = require("../models/pagination.model");
40
+ var index_1 = require("../index");
41
+ var schema_report_builder_1 = require("../util/schema-report-builder");
42
+ var common_1 = require("../util/common");
43
+ function loadReportBuilderMethods(methodManager) {
44
+ methodManager.methods({
45
+ reportBuilderBuildTree: {
46
+ skipQueue: true,
47
+ check: new simpl_schema_1.default({
48
+ collection_root: {
49
+ type: String
50
+ }
51
+ }),
52
+ function: function (collection_root) {
53
+ var _this = this;
54
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
55
+ var lookupSchemaData, lookupSchemaTree, treeItems;
56
+ return __generator(this, function (_a) {
57
+ lookupSchemaData = schema_report_builder_1.getReportLookupSchemas(collection_root).sort(function (a, b) { return a.collection_name.localeCompare(b.collection_name); });
58
+ lookupSchemaTree = lookupSchemaData.filter(function (a) { return a.is_root === true; })[0].tree;
59
+ treeItems = schema_report_builder_1.buildTree(collection_root, lookupSchemaTree);
60
+ Object.keys(lookupSchemaTree).filter(function (a) { return a.endsWith('(Lookup)'); }).forEach(function (lookup) {
61
+ var fieldPath = lookup.split('.');
62
+ var field = null;
63
+ fieldPath.forEach(function (path) {
64
+ if (!field) {
65
+ field = treeItems.filter(function (a) { return a.fieldName === path; })[0];
66
+ }
67
+ else {
68
+ field = field.children.filter(function (a) { return a.fieldName === path; })[0];
69
+ }
70
+ });
71
+ field.children = schema_report_builder_1.buildTree(lookupSchemaTree[lookup].lookup_collection, lookupSchemaData.filter(function (a) { return a.collection_name === lookupSchemaTree[lookup].lookup_collection; })[0].tree, field);
72
+ });
73
+ // console.log('----------- Tree Items -----------', treeItems);
74
+ resolve({ isLeaf: false, children: treeItems });
75
+ return [2 /*return*/];
76
+ });
77
+ }); });
78
+ }
79
+ },
80
+ reportBuilderGetDistinctValue: {
81
+ skipQueue: true,
82
+ check: new simpl_schema_1.default({
83
+ treeLeaf: {
84
+ type: Object,
85
+ blackbox: true
86
+ }
87
+ }),
88
+ function: function (treeLeaf) {
89
+ var _this = this;
90
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
91
+ var _a;
92
+ return __generator(this, function (_b) {
93
+ switch (_b.label) {
94
+ case 0:
95
+ if (!(treeLeaf.fieldType === 'String')) return [3 /*break*/, 2];
96
+ _a = resolve;
97
+ return [4 /*yield*/, schema_report_builder_1.mongoCommand('distinct', treeLeaf.collection_name, treeLeaf.fieldPath.replace(/\.\$/g, ''))];
98
+ case 1:
99
+ _a.apply(void 0, [_b.sent()]);
100
+ return [3 /*break*/, 3];
101
+ case 2:
102
+ resolve([]);
103
+ _b.label = 3;
104
+ case 3: return [2 /*return*/];
105
+ }
106
+ });
107
+ }); });
108
+ }
109
+ },
110
+ reportBuilderGetResults: {
111
+ skipQueue: true,
112
+ check: new simpl_schema_1.default({
113
+ reportType: {
114
+ type: String
115
+ },
116
+ rootCollectionName: {
117
+ type: String
118
+ },
119
+ options: {
120
+ type: pagination_model_1.PaginationOptionsSchema
121
+ },
122
+ filters: {
123
+ type: Array,
124
+ optional: true
125
+ },
126
+ 'filters.$': {
127
+ type: Object,
128
+ blackbox: true,
129
+ optional: true
130
+ },
131
+ filterArrays: {
132
+ type: Array,
133
+ optional: true
134
+ },
135
+ 'filterArrays.$': {
136
+ type: Object,
137
+ blackbox: true,
138
+ optional: true
139
+ },
140
+ selectedFields: {
141
+ type: Array,
142
+ optional: true
143
+ },
144
+ 'selectedFields.$': {
145
+ type: Object,
146
+ optional: true,
147
+ blackbox: true
148
+ },
149
+ groupsRow: {
150
+ type: Array
151
+ },
152
+ 'groupsRow.$': {
153
+ type: Object,
154
+ blackbox: true
155
+ },
156
+ fieldsTotal: {
157
+ type: Array
158
+ },
159
+ 'fieldsTotal.$': {
160
+ type: Object,
161
+ blackbox: true
162
+ },
163
+ fieldsLink: {
164
+ type: Array
165
+ },
166
+ 'fieldsLink.$': {
167
+ type: Object,
168
+ blackbox: true
169
+ },
170
+ date_field: {
171
+ type: String,
172
+ optional: true
173
+ },
174
+ date_interval: {
175
+ type: String,
176
+ optional: true
177
+ }
178
+ }),
179
+ function: function (reportType, rootCollectionName, rootOptions, filters, filterArrays, selectedFields, groupsRow, fieldsTotal, fieldsLink, date_field, date_interval) {
180
+ var _this = this;
181
+ if (filters === void 0) { filters = []; }
182
+ if (filterArrays === void 0) { filterArrays = []; }
183
+ if (selectedFields === void 0) { selectedFields = []; }
184
+ if (groupsRow === void 0) { groupsRow = []; }
185
+ if (fieldsTotal === void 0) { fieldsTotal = []; }
186
+ if (fieldsLink === void 0) { fieldsLink = []; }
187
+ if (date_field === void 0) { date_field = ''; }
188
+ if (date_interval === void 0) { date_interval = ''; }
189
+ return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
190
+ var _a, _b, uniqueSelectedFieldCollections, modelCollection, queryMatchCondition, queryLookups, queryUnwindCollectionPaths, queryGroups, queryGroupUnwind, queryGroup_1, correctSort_1, _loop_1, i, queryProjection, queryTotals, query, queryMatchConditionLookup, tmpProj_1, tmpAnds_1, res, err_1;
191
+ var _this = this;
192
+ return __generator(this, function (_c) {
193
+ switch (_c.label) {
194
+ case 0:
195
+ uniqueSelectedFieldCollections = selectedFields.map(function (a) { return a.collection_name; }).filter(function (elem, index, self) {
196
+ return index === self.indexOf(elem);
197
+ });
198
+ modelCollection = index_1.ResolveIOServer.getMainDB().model(rootCollectionName);
199
+ queryMatchCondition = {
200
+ $and: [
201
+ {
202
+ $or: []
203
+ }
204
+ ]
205
+ };
206
+ // Match Non-Nulls
207
+ selectedFields.filter(function (a) { return a.collection_name === rootCollectionName; }).forEach(function (field) {
208
+ var _a, _b, _c;
209
+ queryMatchCondition['$and'][0].$or.push({
210
+ $and: [
211
+ (_a = {}, _a[field.fieldPath.replace(/\.\$/g, '')] = { $exists: 1 }, _a),
212
+ (_b = {}, _b[field.fieldPath.replace(/\.\$/g, '')] = { $ne: '' }, _b),
213
+ (_c = {}, _c[field.fieldPath.replace(/\.\$/g, '')] = { $ne: null }, _c),
214
+ ]
215
+ });
216
+ });
217
+ if (filters.filter(function (a) { return (!a['$or'] && !Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && !a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).length) {
218
+ filters.filter(function (a) { return (!a['$or'] && !Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && !a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).forEach(function (filter) {
219
+ queryMatchCondition['$and'].push(filter);
220
+ });
221
+ }
222
+ queryLookups = [];
223
+ // Lookup Groups
224
+ groupsRow.filter(function (a) { return a.treeItem.collection_name !== rootCollectionName; }).forEach(function (group) {
225
+ if (!queryLookups.filter(function (a) { return a.as === group.treeItem.lookup_as.replace(/\.\$/g, ''); }).length) {
226
+ queryLookups.push({
227
+ from: group.treeItem.lookup_collection,
228
+ localField: group.treeItem.lookup_local_key,
229
+ foreignField: group.treeItem.lookup_foreign_key,
230
+ as: group.treeItem.lookup_as.replace(/\.\$/g, '')
231
+ });
232
+ }
233
+ });
234
+ // Lookup Selected Fields
235
+ uniqueSelectedFieldCollections.filter(function (a) { return a !== rootCollectionName; }).forEach(function (uniqueCollection) {
236
+ selectedFields.filter(function (a) { return a.collection_name === uniqueCollection; }).forEach(function (field) {
237
+ if (!queryLookups.filter(function (a) { return a.as === field.lookup_as.replace(/\.\$/g, ''); }).length) {
238
+ queryLookups.push({
239
+ from: field.lookup_collection,
240
+ localField: field.lookup_local_key,
241
+ foreignField: field.lookup_foreign_key,
242
+ as: field.lookup_as.replace(/\.\$/g, '')
243
+ });
244
+ }
245
+ });
246
+ });
247
+ queryUnwindCollectionPaths = [];
248
+ selectedFields.filter(function (a) { return a.fieldPath.includes('$'); }).forEach(function (field) {
249
+ var arrayPartData = field.fieldPath.split('.$');
250
+ var path = '$';
251
+ for (var i = 0; i < arrayPartData.length - 1; i++) {
252
+ path += arrayPartData[i];
253
+ if (!queryUnwindCollectionPaths.filter(function (a) { return a === path; })[0]) {
254
+ queryUnwindCollectionPaths.push(path);
255
+ }
256
+ }
257
+ });
258
+ groupsRow.filter(function (a) { return a.treeItem.fieldPath.includes('$'); }).forEach(function (field) {
259
+ var arrayPartData = field.treeItem.fieldPath.split('.$');
260
+ var path = '$';
261
+ for (var i = 0; i < arrayPartData.length - 1; i++) {
262
+ path += arrayPartData[i];
263
+ if (!queryUnwindCollectionPaths.filter(function (a) { return a === path; })[0]) {
264
+ queryUnwindCollectionPaths.push(path);
265
+ }
266
+ }
267
+ });
268
+ queryGroups = [];
269
+ queryGroupUnwind = [];
270
+ if (groupsRow.length) {
271
+ queryGroup_1 = {
272
+ _id: {}
273
+ };
274
+ groupsRow.forEach(function (row) {
275
+ if (row.field.includes('$')) {
276
+ var fieldData = row.field.split('.$');
277
+ var fieldPath = '';
278
+ for (var i = 0; i < fieldData.length - 1; i++) {
279
+ fieldPath += fieldData[i];
280
+ queryGroupUnwind.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
281
+ }
282
+ }
283
+ queryGroup_1._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
284
+ if (date_field && date_interval) {
285
+ if (date_interval === 'Daily') {
286
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
287
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
288
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
289
+ }
290
+ else if (date_interval === 'Weekly') {
291
+ queryGroup_1._id['week'] = { '$week': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
292
+ // queryGroup._id['month'] = {'$month' : '$' + date_field.replace(/\.\$/g, '')};
293
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
294
+ }
295
+ else if (date_interval === 'Monthly') {
296
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
297
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
298
+ }
299
+ else if (date_interval === 'Quarterly') {
300
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
301
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
302
+ }
303
+ else if (date_interval === 'Yearly') {
304
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
305
+ }
306
+ }
307
+ });
308
+ selectedFields.forEach(function (field) {
309
+ if (field.leafType === 'Average') {
310
+ queryGroup_1[field.id] = { '$avg': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
311
+ }
312
+ else if (field.leafType === 'Sum') {
313
+ queryGroup_1[field.id] = { '$sum': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
314
+ }
315
+ else if (field.leafType === 'Count') {
316
+ queryGroup_1[field.id] = { '$sum': 1 };
317
+ }
318
+ else if (field.leafType === 'Minimum') {
319
+ queryGroup_1[field.id] = { '$min': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
320
+ }
321
+ else if (field.leafType === 'Maximum') {
322
+ queryGroup_1[field.id] = { '$max': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
323
+ }
324
+ else if (field.leafType === 'First') {
325
+ queryGroup_1[field.id] = { '$first': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
326
+ }
327
+ else if (field.leafType === 'Last') {
328
+ queryGroup_1[field.id] = { '$last': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
329
+ }
330
+ else {
331
+ queryGroup_1[field.id] = { '$push': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
332
+ }
333
+ });
334
+ //Totals
335
+ if (fieldsTotal.length) {
336
+ fieldsTotal.forEach(function (total) {
337
+ selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (field) {
338
+ var _a;
339
+ queryGroup_1[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + field.fieldPath.replace(/\.\$/g, ''), _a);
340
+ });
341
+ });
342
+ }
343
+ //Links
344
+ if (fieldsLink.length) {
345
+ fieldsLink.filter(function (a) { return a.field_first && a.field_second; }).forEach(function (link) {
346
+ queryGroup_1[link.id] = { $cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')] };
347
+ });
348
+ }
349
+ if (rootOptions.sort && reportType === 'Tabular Group') {
350
+ correctSort_1 = {};
351
+ Object.keys(rootOptions.sort).forEach(function (key) {
352
+ correctSort_1[selectedFields.filter(function (a) { return a.id === key; })[0].fieldPath.replace(/\.\$/g, '')] = rootOptions.sort[key];
353
+ });
354
+ queryGroups.push({
355
+ $sort: correctSort_1
356
+ });
357
+ }
358
+ queryGroups.push({ $group: queryGroup_1 });
359
+ if (reportType === 'Tabular Group') {
360
+ _loop_1 = function (i) {
361
+ var _a, _b;
362
+ queryGroups.push({ $sort: (_a = {}, _a['_id.' + groupsRow[i].id] = 1, _a) });
363
+ var tmpQueryGroup = {
364
+ _id: {}
365
+ };
366
+ for (var j = 0; j < i; j++) {
367
+ tmpQueryGroup._id[groupsRow[j].id] = '$_id.' + groupsRow[j].id;
368
+ }
369
+ var tmpQueryGroupObj = (_b = {},
370
+ _b[groupsRow[i].id] = '$_id.' + [groupsRow[i].id],
371
+ _b);
372
+ if (i === groupsRow.length - 1) {
373
+ selectedFields.forEach(function (field) {
374
+ tmpQueryGroupObj[field.id] = '$' + field.id;
375
+ });
376
+ }
377
+ else {
378
+ tmpQueryGroupObj[groupsRow[i + 1].id] = '$' + [groupsRow[i + 1].id];
379
+ }
380
+ fieldsTotal.forEach(function (total) {
381
+ selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (field) {
382
+ var _a;
383
+ tmpQueryGroupObj[total.id + '_' + field.id] = '$' + total.id + '_' + field.id;
384
+ tmpQueryGroup[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + field.id, _a);
385
+ });
386
+ });
387
+ tmpQueryGroup[groupsRow[i].id] = { '$push': tmpQueryGroupObj };
388
+ queryGroups.push({ $group: tmpQueryGroup });
389
+ };
390
+ for (i = groupsRow.length - 1; i > 0; i--) {
391
+ _loop_1(i);
392
+ }
393
+ queryGroups.push({ $sort: (_a = {}, _a['_id.' + groupsRow[0].id] = 1, _a) });
394
+ }
395
+ else if (reportType === 'Dated') {
396
+ // db.collection.aggregate([
397
+ // { "$group": {
398
+ // "_id": {
399
+ // "$toDate": {
400
+ // "$subtract": [
401
+ // { "$toLong": "$created_at" },
402
+ // { "$mod": [ { "$toLong": "$created_at" }, 1000 * 60 * 15 ] }
403
+ // ]
404
+ // }
405
+ // },
406
+ // "count": { "$sum": 1 }
407
+ // }}
408
+ // ])
409
+ }
410
+ }
411
+ queryProjection = {
412
+ _id: 1
413
+ };
414
+ selectedFields.forEach(function (field) {
415
+ if (field.leafType === 'Average') {
416
+ queryProjection[field.id] = { $avg: '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
417
+ }
418
+ else if (field.leafType === 'Sum') {
419
+ queryProjection[field.id] = { $sum: '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
420
+ }
421
+ else if (field.leafType === 'Count') {
422
+ queryProjection[field.id] = { $sum: 1 };
423
+ }
424
+ else if (field.leafType === 'Minimum') {
425
+ queryProjection[field.id] = { $min: '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
426
+ }
427
+ else if (field.leafType === 'Maximum') {
428
+ queryProjection[field.id] = { $max: '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
429
+ }
430
+ else if (field.leafType === 'First') {
431
+ queryProjection[field.id] = { $slice: ['$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')), 0] };
432
+ }
433
+ else if (field.leafType === 'Last') {
434
+ queryProjection[field.id] = { $slice: ['$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')), -1] };
435
+ }
436
+ else {
437
+ queryProjection[field.id] = '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, ''));
438
+ }
439
+ });
440
+ //Links
441
+ if (fieldsLink.length) {
442
+ fieldsLink.filter(function (a) { return a.field_first && a.field_second; }).forEach(function (link) {
443
+ queryProjection[link.id] = { $cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')] };
444
+ });
445
+ }
446
+ queryTotals = null;
447
+ if (fieldsTotal.length && (reportType === 'Tabular' || reportType === 'Dated')) {
448
+ fieldsTotal.forEach(function (total) {
449
+ selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (field) {
450
+ var _a;
451
+ if (!queryTotals) {
452
+ queryTotals = {};
453
+ }
454
+ queryTotals[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$results.' + field.id, _a);
455
+ });
456
+ });
457
+ }
458
+ query = [];
459
+ // Non-Lookup Filters
460
+ if (filters.filter(function (a) { return (!a['$or'] && !Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && !a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).length || selectedFields.filter(function (a) { return !a.fieldPath.includes('(Lookup'); }).length) {
461
+ query.push({
462
+ $match: queryMatchCondition
463
+ });
464
+ }
465
+ // Unwind Pre-Lookup Arrays
466
+ queryUnwindCollectionPaths.filter(function (a) { return !a.includes('(Lookup)'); }).forEach(function (path) {
467
+ query.push({
468
+ $unwind: {
469
+ path: path,
470
+ preserveNullAndEmptyArrays: true
471
+ }
472
+ });
473
+ });
474
+ // Look Ups
475
+ queryLookups.forEach(function (lookup) {
476
+ query.push({
477
+ $lookup: lookup
478
+ });
479
+ });
480
+ // Unwind Lookups
481
+ queryUnwindCollectionPaths.filter(function (a) { return a.includes('(Lookup)'); }).forEach(function (path) {
482
+ if (!query.filter(function (a) { return a.$unwind && a.$unwind.path === path; }).length) {
483
+ query.push({
484
+ $unwind: {
485
+ path: path,
486
+ preserveNullAndEmptyArrays: true
487
+ }
488
+ });
489
+ }
490
+ });
491
+ // Group Unwinds
492
+ if (groupsRow.length) {
493
+ query = query.concat(queryGroupUnwind.filter(function (a) { return !query.some(function (b) { return b.$unwind && (b.$unwind.path === a.$unwind.path); }); }));
494
+ }
495
+ queryMatchConditionLookup = {
496
+ $and: []
497
+ };
498
+ if (filters.filter(function (a) { return (!a['$or'] && Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).length) {
499
+ filters.filter(function (a) { return (!a['$or'] && Object.keys(a).some(function (b) { return b.includes('(Lookup)'); })) || (a['$or'] && a['$or'].some(function (b) { return Object.keys(b).some(function (c) { return c.includes('(Lookup)'); }); })); }).forEach(function (filter) {
500
+ queryMatchConditionLookup['$and'].push(filter);
501
+ });
502
+ }
503
+ filterArrays.forEach(function (filter) {
504
+ queryMatchConditionLookup['$and'].push(filter);
505
+ });
506
+ if (queryMatchConditionLookup.$and.some(function (a) { return !a['$or'] || (a['$or'] && a['$or'].length); }) || queryMatchConditionLookup.$and.length) {
507
+ query.push({
508
+ $match: queryMatchConditionLookup
509
+ });
510
+ }
511
+ // Group Queries and Projection
512
+ if (groupsRow.length) {
513
+ queryGroups.forEach(function (group) {
514
+ query.push(group);
515
+ });
516
+ if (reportType === 'Tabular Group') {
517
+ tmpProj_1 = common_1.deepCopy(queryGroups[queryGroups.length - 2].$group);
518
+ if (groupsRow.length === 1) {
519
+ tmpProj_1._id.gr_1 = '$_id.gr_1';
520
+ }
521
+ Object.keys(tmpProj_1).filter(function (a) { return a !== '_id'; }).forEach(function (key) {
522
+ tmpProj_1[key] = 1;
523
+ });
524
+ Object.assign(tmpProj_1, tmpProj_1['_id']);
525
+ tmpProj_1['_id'] = 0;
526
+ query.push({
527
+ $project: tmpProj_1
528
+ });
529
+ }
530
+ }
531
+ else {
532
+ query.push({
533
+ $project: queryProjection
534
+ });
535
+ }
536
+ // Links
537
+ if (fieldsLink.length) {
538
+ if (fieldsLink.length === 1 && fieldsLink[0].field_first && fieldsLink[0].field_second) {
539
+ query.push({ $match: (_b = {}, _b[fieldsLink[0].id] = 0, _b) });
540
+ }
541
+ else {
542
+ tmpAnds_1 = [];
543
+ fieldsLink.filter(function (a) { return a.field_first && a.field_second; }).forEach(function (link) {
544
+ var _a;
545
+ tmpAnds_1.push((_a = {}, _a[link.id] = 0, _a));
546
+ });
547
+ if (tmpAnds_1.length) {
548
+ query.push({ $match: { $and: tmpAnds_1 } });
549
+ }
550
+ }
551
+ }
552
+ // SORT
553
+ if (rootOptions.sort && reportType !== 'Tabular Group') {
554
+ query.push({
555
+ $sort: rootOptions.sort
556
+ });
557
+ }
558
+ // Dated Grouping
559
+ // if (date_field && date_interval) {
560
+ // if (date_interval === 'Daily') {
561
+ // query.push({
562
+ // $group: {
563
+ // _id: {
564
+ // day: '$_id.day',
565
+ // month: '$_id.month',
566
+ // year: '$_id.year'
567
+ // },
568
+ // results: {
569
+ // '$push': '$$ROOT'
570
+ // }
571
+ // }
572
+ // });
573
+ // }
574
+ // else if (date_interval === 'Weekly') {
575
+ // query.push({
576
+ // $group: {
577
+ // _id: {
578
+ // week: '$_id.week',
579
+ // // month: '$_id.month',
580
+ // year: '$_id.year'
581
+ // },
582
+ // results: {
583
+ // '$push': '$$ROOT'
584
+ // }
585
+ // }
586
+ // });
587
+ // }
588
+ // else if (date_interval === 'Monthly') {
589
+ // query.push({
590
+ // $group: {
591
+ // _id: {
592
+ // month: '$_id.month',
593
+ // year: '$_id.year'
594
+ // },
595
+ // results: {
596
+ // '$push': '$$ROOT'
597
+ // }
598
+ // }
599
+ // });
600
+ // }
601
+ // else if (date_interval === 'Quarterly') {
602
+ // query.push({
603
+ // $group: {
604
+ // _id: {
605
+ // month: '$_id.month',
606
+ // year: '$_id.year'
607
+ // },
608
+ // results: {
609
+ // '$push': '$$ROOT'
610
+ // }
611
+ // }
612
+ // });
613
+ // }
614
+ // else if (date_interval === 'Yearly') {
615
+ // query.push({
616
+ // $group: {
617
+ // _id: {
618
+ // year: '$_id.year'
619
+ // },
620
+ // results: {
621
+ // '$push': '$$ROOT'
622
+ // }
623
+ // }
624
+ // });
625
+ // }
626
+ // }
627
+ // GROUP TO GET TOTAL COUNT
628
+ query.push({
629
+ $group: {
630
+ _id: null,
631
+ count: { $sum: 1 },
632
+ results: { $push: '$$ROOT' }
633
+ }
634
+ });
635
+ if (rootOptions.limit) {
636
+ // PROJECT TO SKIP/LIMIT
637
+ query.push({
638
+ $project: {
639
+ count: 1,
640
+ results: {
641
+ $slice: ['$results', rootOptions.skip, rootOptions.limit]
642
+ }
643
+ }
644
+ });
645
+ if (queryTotals !== null) {
646
+ query[query.length - 1].$project['totals'] = queryTotals;
647
+ }
648
+ }
649
+ else if (queryTotals !== null) {
650
+ query.push({
651
+ $project: {
652
+ count: 1,
653
+ results: 1,
654
+ totals: queryTotals
655
+ }
656
+ });
657
+ }
658
+ res = null;
659
+ _c.label = 1;
660
+ case 1:
661
+ _c.trys.push([1, 3, , 4]);
662
+ return [4 /*yield*/, modelCollection.aggregate(query).allowDiskUse(true)];
663
+ case 2:
664
+ res = _c.sent();
665
+ return [3 /*break*/, 4];
666
+ case 3:
667
+ err_1 = _c.sent();
668
+ console.log(err_1);
669
+ return [3 /*break*/, 4];
670
+ case 4:
671
+ resolve(res);
672
+ return [2 /*return*/];
673
+ }
674
+ });
675
+ }); });
676
+ },
677
+ }
678
+ });
679
+ }
680
+ exports.loadReportBuilderMethods = loadReportBuilderMethods;