@resolveio/server-lib 4.5.11 → 4.5.12

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.
@@ -39,7 +39,6 @@ var simpl_schema_1 = require("simpl-schema");
39
39
  var pagination_model_1 = require("../models/pagination.model");
40
40
  var index_1 = require("../index");
41
41
  var schema_report_builder_1 = require("../util/schema-report-builder");
42
- var common_1 = require("../util/common");
43
42
  function loadReportBuilderMethods(methodManager) {
44
43
  methodManager.methods({
45
44
  reportBuilderBuildTree: {
@@ -196,25 +195,26 @@ function loadReportBuilderMethods(methodManager) {
196
195
  if (date_field === void 0) { date_field = ''; }
197
196
  if (date_interval === void 0) { date_interval = ''; }
198
197
  return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
199
- var _a, uniqueSelectedFieldCollections, modelCollection, queryMatchCondition, initialLookups, initialProjection, tmpIndex_1, initialTotals, queryGroups, queryGroupUnwind, initialGroup, secondInitialGroup, secondInitialLookup, zipLayers, initialNonSumFilterProj, initialNonSumElemAtProj, initialNonSumValueProj, cnt, _loop_1, group, correctSort_1, _loop_2, i, queryProjection, queryTotals, query, i, res, err_1;
200
- return __generator(this, function (_b) {
201
- switch (_b.label) {
198
+ var uniqueSelectedFieldCollections, modelCollection, query, initialQueryMatchCondition, groupQueries, queryGroup_1, queryGroup_2, queryTotals, res, err_1;
199
+ var _this = this;
200
+ return __generator(this, function (_a) {
201
+ switch (_a.label) {
202
202
  case 0:
203
203
  uniqueSelectedFieldCollections = selectedFields.map(function (a) { return a.collection_name; }).filter(function (elem, index, self) {
204
204
  return index === self.indexOf(elem);
205
205
  });
206
206
  modelCollection = index_1.ResolveIOServer.getMainDB().model(rootCollectionName);
207
- queryMatchCondition = {
207
+ query = [];
208
+ initialQueryMatchCondition = {
208
209
  $and: [
209
210
  {
210
211
  $or: []
211
212
  }
212
213
  ]
213
214
  };
214
- // Match Non-Nulls
215
215
  selectedFields.filter(function (a) { return a.collection_name === rootCollectionName; }).forEach(function (field) {
216
216
  var _a, _b, _c;
217
- queryMatchCondition['$and'][0].$or.push({
217
+ initialQueryMatchCondition['$and'][0].$or.push({
218
218
  $and: [
219
219
  (_a = {}, _a[field.fieldPath.replace(/\.\$/g, '')] = { $exists: 1 }, _a),
220
220
  (_b = {}, _b[field.fieldPath.replace(/\.\$/g, '')] = { $ne: '' }, _b),
@@ -224,651 +224,428 @@ function loadReportBuilderMethods(methodManager) {
224
224
  });
225
225
  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) {
226
226
  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) {
227
- queryMatchCondition['$and'].push(filter);
227
+ initialQueryMatchCondition['$and'].push(filter);
228
228
  });
229
229
  }
230
- 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) {
231
- 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) {
232
- queryMatchCondition['$and'].push(filter);
230
+ // Add filter to query
231
+ 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) {
232
+ query.push({
233
+ $match: initialQueryMatchCondition
233
234
  });
234
235
  }
235
- filterArrays.forEach(function (filter) {
236
- queryMatchCondition['$and'].push(filter);
237
- // queryMatchConditionLookup['$and'].push(filter);
238
- });
239
- initialLookups = [];
240
- // Lookup Groups
241
- groupsRow.filter(function (a) { return a.treeItem.collection_name !== rootCollectionName && a.treeItem.fieldPath.split('.$').length === 2; }).forEach(function (group) {
242
- if (!initialLookups.filter(function (a) { return a.as === group.treeItem.lookup_as.replace(/\.\$/g, ''); }).length) {
243
- initialLookups.push({
244
- from: group.treeItem.lookup_collection,
245
- localField: group.treeItem.lookup_local_key,
246
- foreignField: group.treeItem.lookup_foreign_key,
247
- as: group.treeItem.lookup_as.replace(/\.\$/g, '')
248
- });
249
- }
250
- });
251
- // Lookup Selected Fields
252
- uniqueSelectedFieldCollections.filter(function (a) { return a !== rootCollectionName; }).forEach(function (uniqueCollection) {
253
- selectedFields.filter(function (a) { return a.collection_name === uniqueCollection; }).forEach(function (field) {
254
- if (!initialLookups.filter(function (a) { return a.as === field.lookup_as.replace(/\.\$/g, ''); }).length && field.fieldPath.split('.$').length === 2) {
255
- initialLookups.push({
256
- from: field.lookup_collection,
257
- localField: field.lookup_local_key,
258
- foreignField: field.lookup_foreign_key,
259
- as: field.lookup_as.replace(/\.\$/g, '')
260
- });
261
- }
262
- });
263
- });
264
- initialProjection = { _id: 1, count: { $sum: 1 } };
265
- // Projection
236
+ groupQueries = [];
266
237
  groupsRow.forEach(function (row) {
267
- initialProjection[row.treeItem.fieldPath.split('.$')[0]] = 1;
268
- });
269
- selectedFields.forEach(function (field) {
270
- initialProjection[field.fieldPath.split('.$')[0]] = 1;
271
- });
272
- if (selectedFields.some(function (a) { return a.fieldPath.includes('$'); }) || groupsRow.some(function (a) { return a.field.includes('$') || a.field.includes('(Lookup)'); })) {
273
- initialProjection['rb_arrays_0'] = {
274
- $map: {
275
- input: {
276
- $zip: {
277
- inputs: [
278
- // '$chemicals',
279
- // '$drivers',
280
- // '$invoices'
281
- ],
282
- useLongestLength: true
238
+ if (row.field.includes('$')) {
239
+ var fieldData = row.field.split('.$');
240
+ var fieldPath_1 = '';
241
+ var _loop_1 = function (i) {
242
+ fieldPath_1 += fieldData[i];
243
+ if (fieldPath_1.includes('(Lookup)')) {
244
+ groupQueries.push({ $lookup: {
245
+ from: row.treeItem.lookup_collection,
246
+ localField: row.treeItem.lookup_local_key,
247
+ foreignField: row.treeItem.lookup_foreign_key,
248
+ as: row.treeItem.lookup_as.replace(/\.\$/g, '')
249
+ } });
250
+ if (i === 0) {
251
+ if (fieldsTotal.length) {
252
+ var addFields_1 = { $addFields: {} };
253
+ fieldsTotal.forEach(function (total) {
254
+ selectedFields.filter(function (a) { return !a.fieldPath.include('.$') && a.fieldType === 'Number'; }).forEach(function (field) {
255
+ addFields_1.$addFields[total.id + '_' + field.id] = {
256
+ $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: [{ $cond: { if: { $gt: [{ $size: '$' + row.treeItem.lookup_as.replace(/\.\$/g, '') }, 0] }, then: { $size: '$' + row.treeItem.lookup_as.replace(/\.\$/g, '') }, else: 1 } }] }]
257
+ };
258
+ });
259
+ });
260
+ groupQueries.push(addFields_1);
261
+ }
262
+ }
263
+ // total_1_f_0: {
264
+ // $divide: ['$loaded_miles.loaded_miles', {$multiply: [{$size: '$chemicals'}] } ]
265
+ // },
266
+ // total_1_f_1: {
267
+ // $divide: ['$wo_number', {$size: '$chemicals'}]
268
+ // }
269
+ groupQueries.push({ '$unwind': { path: '$' + row.treeItem.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
270
+ }
271
+ if (i === 0) {
272
+ if (fieldsTotal.length) {
273
+ var addFields_2 = { $addFields: {} };
274
+ fieldsTotal.forEach(function (total) {
275
+ selectedFields.filter(function (a) { return !a.fieldPath.includes('.$') && a.fieldType === 'Number'; }).forEach(function (field) {
276
+ addFields_2.$addFields[total.id + '_' + field.id] = {
277
+ $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: [{ $cond: { if: { $gt: [{ $size: '$' + fieldPath_1 }, 0] }, then: { $size: '$' + fieldPath_1 }, else: 1 } }] }]
278
+ };
279
+ });
280
+ });
281
+ groupQueries.push(addFields_2);
283
282
  }
284
- },
285
- as: 'zipped',
286
- in: {
287
- // chemicals: {
288
- // $arrayElemAt: [
289
- // '$$zipped',
290
- // 0
291
- // ]
292
- // },
293
- // drivers: {
294
- // $arrayElemAt: [
295
- // '$$zipped',
296
- // 1
297
- // ]
298
- // },
299
- // invoices: {
300
- // $arrayElemAt: [
301
- // '$$zipped',
302
- // 2
303
- // ]
304
- // }
305
- }
306
- }
307
- };
308
- tmpIndex_1 = 0;
309
- groupsRow.filter(function (a) { return a.field.includes('$'); }).forEach(function (field) {
310
- if (!initialProjection['rb_arrays_0'].$map.input.$zip.inputs.some(function (a) { return a === '$' + field.field.split('.$')[0]; })) {
311
- initialProjection['rb_arrays_0'].$map.input.$zip.inputs.push('$' + field.field.split('.$')[0]);
312
- initialProjection['rb_arrays_0'].$map.in[field.field.split('.$')[0].replace(new RegExp(/\./g), '_')] = {
313
- $arrayElemAt: ['$$zipped', tmpIndex_1++]
314
- };
315
- }
316
- });
317
- selectedFields.filter(function (a) { return a.fieldPath.includes('$'); }).forEach(function (field) {
318
- if (!initialProjection['rb_arrays_0'].$map.input.$zip.inputs.some(function (a) { return a === '$' + field.fieldPath.split('.$')[0]; })) {
319
- initialProjection['rb_arrays_0'].$map.input.$zip.inputs.push('$' + field.fieldPath.split('.$')[0]);
320
- initialProjection['rb_arrays_0'].$map.in[field.fieldPath.split('.$')[0].replace(new RegExp(/\./g), '_')] = {
321
- $arrayElemAt: ['$$zipped', tmpIndex_1++]
322
- };
323
- }
324
- });
325
- }
326
- initialTotals = null;
327
- fieldsTotal.forEach(function (total) {
328
- selectedFields.filter(function (a) { return a.fieldType === 'Number' && !a.fieldPath.includes('$') && !a.fieldPath.includes('(Lookup)'); }).forEach(function (field) {
329
- if (!initialTotals) {
330
- initialTotals = {
331
- $addFields: {}
332
- };
333
- }
334
- initialTotals.$addFields[total.id + '_' + field.id] = {
335
- $divide: ['$' + field.fieldPath, { $max: [1, { $size: '$rb_arrays_0' }] }]
336
- };
337
- });
338
- });
339
- queryGroups = [];
340
- queryGroupUnwind = [];
341
- initialGroup = null;
342
- secondInitialGroup = null;
343
- secondInitialLookup = [];
344
- zipLayers = [];
345
- if (groupsRow.length && !groupsRow.some(function (a) { return a.treeItem.fieldPath.includes('$') || a.treeItem.collection_name !== rootCollectionName; })) {
346
- initialGroup = { _id: {} };
347
- groupsRow.forEach(function (row) {
348
- initialGroup._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
349
- initialGroup.rb_arrays_0 = { '$first': '$rb_arrays_0' };
350
- initialGroup.count = { '$sum': '$count' };
351
- selectedFields.filter(function (a) { return !a.fieldPath.includes('$') && a.collection_name === rootCollectionName; }).forEach(function (field) {
352
- if (field.leafValueType === 'Average') {
353
- initialGroup[field.id] = { '$avg': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
354
- }
355
- else if (field.leafValueType === 'Sum') {
356
- initialGroup[field.id] = { '$sum': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
357
- }
358
- else if (field.leafValueType === 'Count') {
359
- initialGroup[field.id] = { '$sum': 1 };
360
- }
361
- else if (field.leafValueType === 'Minimum') {
362
- initialGroup[field.id] = { '$min': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
363
- }
364
- else if (field.leafValueType === 'Maximum') {
365
- initialGroup[field.id] = { '$max': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
366
- }
367
- else if (field.leafValueType === 'First') {
368
- initialGroup[field.id] = { '$first': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
369
- }
370
- else if (field.leafValueType === 'Last') {
371
- initialGroup[field.id] = { '$last': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
372
283
  }
373
- else {
374
- initialGroup[field.id] = { '$push': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
284
+ groupQueries.push({ '$unwind': { path: '$' + fieldPath_1, preserveNullAndEmptyArrays: true } });
285
+ if (fieldsTotal.length) {
286
+ var addFields_3 = { $addFields: {} };
287
+ fieldsTotal.forEach(function (total) {
288
+ selectedFields.filter(function (a) { return a.fieldPath.replace(/\.\$/g, '').includes(fieldPath_1) && a.fieldPath.split('.$').length === 2 && a.fieldType === 'Number'; }).forEach(function (field) {
289
+ addFields_3.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
290
+ });
291
+ });
292
+ groupQueries.push(addFields_3);
375
293
  }
376
- });
377
- });
378
- if (fieldsTotal.length) {
379
- fieldsTotal.forEach(function (total) {
380
- selectedFields.filter(function (a) { return a.fieldType === 'Number' && !a.fieldPath.includes('$'); }).forEach(function (field) {
381
- var _a;
382
- initialGroup[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + field.id, _a);
383
- });
384
- });
294
+ };
295
+ for (var i = 0; i < fieldData.length - 1; i++) {
296
+ _loop_1(i);
297
+ }
385
298
  }
386
- }
387
- else if (groupsRow.length) { //group has array or lookup
388
- // project next layers
389
- groupsRow.forEach(function (group) {
390
- if (groupsRow.some(function (a) { return a.treeItem.collection_name !== rootCollectionName; })) {
391
- if (!secondInitialLookup.filter(function (a) { return a.as === group.treeItem.lookup_as.replace(/\.\$/g, ''); }).length) {
392
- secondInitialLookup.push({ $lookup: {
393
- from: group.treeItem.lookup_collection,
394
- localField: 'rb_arrays_0.' + group.treeItem.lookup_local_key,
395
- foreignField: group.treeItem.lookup_foreign_key,
396
- as: 'rb_arrays_0.' + group.treeItem.lookup_as.replace(/\.\$/g, '')
299
+ });
300
+ if (!groupsRow.length) {
301
+ selectedFields.forEach(function (field) {
302
+ var fieldData = field.fieldPath.split('.$');
303
+ var fieldPath = '';
304
+ var _loop_2 = function (i) {
305
+ fieldPath += fieldData[i];
306
+ if (fieldPath.includes('(Lookup)')) {
307
+ groupQueries.push({ $lookup: {
308
+ from: field.lookup_collection,
309
+ localField: field.lookup_local_key,
310
+ foreignField: field.lookup_foreign_key,
311
+ as: field.lookup_as.replace(/\.\$/g, '')
397
312
  } });
398
- secondInitialLookup.push({
399
- '$unwind': {
400
- "path": '$rb_arrays_0.' + group.treeItem.lookup_local_key,
401
- "preserveNullAndEmptyArrays": true
313
+ if (i === 0) {
314
+ if (fieldsTotal.length) {
315
+ var addFields_4 = { $addFields: {} };
316
+ fieldsTotal.forEach(function (total) {
317
+ selectedFields.filter(function (a) { return !a.fieldPath.include('.$') && a.fieldType === 'Number'; }).forEach(function (field) {
318
+ addFields_4.$addFields[total.id + '_' + field.id] = {
319
+ $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: [{ $cond: { if: { $gt: [{ $size: '$' + field.lookup_as.replace(/\.\$/g, '') }, 0] }, then: { $size: '$' + field.lookup_as.replace(/\.\$/g, '') }, else: 1 } }] }]
320
+ };
321
+ });
322
+ });
323
+ groupQueries.push(addFields_4);
402
324
  }
325
+ }
326
+ // total_1_f_0: {
327
+ // $divide: ['$loaded_miles.loaded_miles', {$multiply: [{$size: '$chemicals'}] } ]
328
+ // },
329
+ // total_1_f_1: {
330
+ // $divide: ['$wo_number', {$size: '$chemicals'}]
331
+ // }
332
+ groupQueries.push({ '$unwind': { path: '$' + field.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
333
+ }
334
+ if (i === 0) {
335
+ if (fieldsTotal.length) {
336
+ var addFields_5 = { $addFields: {} };
337
+ fieldsTotal.forEach(function (total) {
338
+ selectedFields.filter(function (a) { return !a.fieldPath.includes('.$') && a.fieldType === 'Number'; }).forEach(function (field) {
339
+ addFields_5.$addFields[total.id + '_' + field.id] = {
340
+ $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: [{ $cond: { if: { $gt: [{ $size: '$' + fieldPath }, 0] }, then: { $size: '$' + fieldPath }, else: 1 } }] }]
341
+ };
342
+ });
343
+ });
344
+ groupQueries.push(addFields_5);
345
+ }
346
+ }
347
+ groupQueries.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
348
+ if (fieldsTotal.length) {
349
+ var addFields_6 = { $addFields: {} };
350
+ fieldsTotal.forEach(function (total) {
351
+ selectedFields.filter(function (a) { return a.fieldPath.replace(/\.\$/g, '').includes(fieldPath) && a.fieldPath.split('.$').length === 2 && a.fieldType === 'Number'; }).forEach(function (field) {
352
+ addFields_6.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
353
+ });
403
354
  });
355
+ groupQueries.push(addFields_6);
404
356
  }
357
+ };
358
+ for (var i = 0; i < fieldData.length - 1; i++) {
359
+ _loop_2(i);
405
360
  }
406
361
  });
407
- secondInitialGroup = { _id: {} };
362
+ }
363
+ // Add group lookups and unwinds to query
364
+ query = query.concat(groupQueries);
365
+ // GROUP
366
+ if (groupsRow.length) {
367
+ queryGroup_1 = {
368
+ _id: {}
369
+ };
408
370
  groupsRow.forEach(function (row) {
409
- secondInitialGroup._id[row.id] = '$rb_arrays_0.' + row.field.replace(/\.\$/g, '');
410
- secondInitialGroup.rb_arrays_0 = { '$push': '$rb_arrays_0' };
411
- secondInitialGroup.count = { '$sum': '$count' };
412
- selectedFields.filter(function (a) { return !a.fieldPath.includes('$') && a.collection_name === rootCollectionName; }).forEach(function (field) {
413
- if (field.leafValueType === 'Average') {
414
- secondInitialGroup[field.id] = { '$avg': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
415
- }
416
- else if (field.leafValueType === 'Sum') {
417
- secondInitialGroup[field.id] = { '$sum': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
418
- }
419
- else if (field.leafValueType === 'Count') {
420
- secondInitialGroup[field.id] = { '$sum': 1 };
421
- }
422
- else if (field.leafValueType === 'Minimum') {
423
- secondInitialGroup[field.id] = { '$min': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
424
- }
425
- else if (field.leafValueType === 'Maximum') {
426
- secondInitialGroup[field.id] = { '$max': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
427
- }
428
- else if (field.leafValueType === 'First') {
429
- secondInitialGroup[field.id] = { '$first': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
430
- }
431
- else if (field.leafValueType === 'Last') {
432
- secondInitialGroup[field.id] = { '$last': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
433
- }
434
- else {
435
- secondInitialGroup[field.id] = { '$push': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
436
- }
437
- });
371
+ queryGroup_1._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
372
+ if (date_field && date_interval) {
373
+ if (date_interval === 'Daily') {
374
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
375
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
376
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
377
+ }
378
+ else if (date_interval === 'Weekly') {
379
+ queryGroup_1._id['week'] = { '$week': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
380
+ // queryGroup._id['month'] = {'$month' : '$' + date_field.replace(/\.\$/g, '')};
381
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
382
+ }
383
+ else if (date_interval === 'Monthly') {
384
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
385
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
386
+ }
387
+ else if (date_interval === 'Quarterly') {
388
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
389
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
390
+ }
391
+ else if (date_interval === 'Yearly') {
392
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
393
+ }
394
+ // queryGroup[date_field.replace(/\.\$/g, '')] = {$first: '$' + date_field.replace(/\.\$/g, '')};
395
+ }
438
396
  });
397
+ selectedFields.forEach(function (field) {
398
+ if (field.leafValueType === 'Average') {
399
+ queryGroup_1[field.id] = { '$avg': '$' + field.fieldPath.replace(/\.\$/g, '') };
400
+ }
401
+ else if (field.leafValueType === 'Sum') {
402
+ queryGroup_1[field.id] = { '$sum': '$' + field.fieldPath.replace(/\.\$/g, '') };
403
+ }
404
+ else if (field.leafValueType === 'Count') {
405
+ queryGroup_1[field.id] = { '$sum': 1 };
406
+ }
407
+ else if (field.leafValueType === 'Minimum') {
408
+ queryGroup_1[field.id] = { '$min': '$' + field.fieldPath.replace(/\.\$/g, '') };
409
+ }
410
+ else if (field.leafValueType === 'Maximum') {
411
+ queryGroup_1[field.id] = { '$max': '$' + field.fieldPath.replace(/\.\$/g, '') };
412
+ }
413
+ else if (field.leafValueType === 'First') {
414
+ queryGroup_1[field.id] = { '$first': '$' + field.fieldPath.replace(/\.\$/g, '') };
415
+ }
416
+ else if (field.leafValueType === 'Last') {
417
+ queryGroup_1[field.id] = { '$last': '$' + field.fieldPath.replace(/\.\$/g, '') };
418
+ }
419
+ else {
420
+ queryGroup_1[field.id] = { '$push': '$' + field.fieldPath.replace(/\.\$/g, '') };
421
+ }
422
+ // if (field.fieldPath.includes('.$') && ) {
423
+ // }
424
+ });
425
+ //Totals
439
426
  if (fieldsTotal.length) {
440
427
  fieldsTotal.forEach(function (total) {
441
- selectedFields.filter(function (a) { return a.fieldType === 'Number' && !a.fieldPath.includes('$'); }).forEach(function (field) {
428
+ selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (field) {
442
429
  var _a;
443
- secondInitialGroup[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + field.id, _a);
430
+ queryGroup_1[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + field.id, _a);
444
431
  });
445
432
  });
446
433
  }
447
- }
448
- initialNonSumFilterProj = null;
449
- initialNonSumElemAtProj = null;
450
- initialNonSumValueProj = null;
451
- if (selectedFields.some(function (a) { return a.fieldPath.split('.$').length === 2; })) {
452
- initialNonSumFilterProj = { $addFields: {} };
453
- selectedFields.filter(function (a) { return a.fieldPath.split('.$').length === 2; }).forEach(function (field) {
454
- var _a;
455
- initialNonSumFilterProj.$addFields['rb_arrays_0_' + field.id] = {
456
- $filter: {
457
- input: '$rb_arrays_0',
458
- cond: {
459
- $and: [
460
- { $ne: ['$$this', null] },
461
- { $ne: ['$$this.' + field.fieldPath.split('.$.')[0], null] },
462
- { $ne: ['$$this.' + field.fieldPath.split('.$.')[0] + field.fieldPath.split('.$')[1], null] }
463
- ]
464
- }
465
- }
466
- };
467
- if (filterArrayPaths.some(function (a) { return a.replace(new RegExp(/\.\w+$/g), '') === field.fieldPath.replace(new RegExp(/\.\w+$/g), ''); })) {
468
- var tmpOr_1 = [];
469
- var filter = common_1.deepCopy(filterArrays[filterArrayPaths.findIndex(function (a) { return a.replace(new RegExp(/\.\w+$/), '') === field.fieldPath.replace(new RegExp(/\.\w+$/), ''); })]);
470
- if (filter['$or']) {
471
- filter['$or'].forEach(function (orVal) {
472
- var _a;
473
- tmpOr_1.push((_a = {},
474
- _a[Object.keys(orVal[Object.keys(orVal)[0]])[0]] = ['$$this.' + field.fieldPath.split('.$.')[0] + field.fieldPath.split('.$')[1], orVal[Object.keys(orVal)[0]][Object.keys(orVal[Object.keys(orVal)[0]])[0]]],
475
- _a));
476
- });
477
- }
478
- else {
479
- initialNonSumFilterProj.$addFields['rb_arrays_0_' + field.id].$filter.cond.$and.push((_a = {}, _a[Object.keys(filter[Object.keys(filter)[0]])[0]] = ['$$this.' + field.fieldPath.split('.$.')[0] + field.fieldPath.split('.$')[1], filter[Object.keys(filter)[0]][Object.keys(filter[Object.keys(filter)[0]])[0]]], _a));
480
- }
481
- if (tmpOr_1.length) {
482
- initialNonSumFilterProj.$addFields['rb_arrays_0_' + field.id].$filter.cond.$and.push({ $or: tmpOr_1 });
483
- }
484
- }
434
+ // Copy Group Arrays Moving Forward
435
+ groupsRow.filter(function (a) { return a.field.includes('.$'); }).forEach(function (row) {
436
+ queryGroup_1[row.field.split('.$')[0]] = { $first: '$' + row.field.split('.$')[0] };
485
437
  });
486
- initialNonSumElemAtProj = { $addFields: {} };
487
- initialNonSumValueProj = { $addFields: {} };
488
- selectedFields.filter(function (a) { return a.fieldPath.split('.$').length === 2; }).forEach(function (field) {
489
- initialNonSumElemAtProj.$addFields['rb_arrays_0_' + field.id] = '$rb_arrays_0_' + field.id + '.' + field.fieldPath.split('.$')[0].replace(new RegExp(/\./g), '_');
438
+ selectedFields.filter(function (a) { return a.fieldPath.includes('.$'); }).forEach(function (field) {
439
+ if (!queryGroup_1[field.fieldPath.split('.$')[0]]) {
440
+ queryGroup_1[field.fieldPath.split('.$')[0]] = { $push: '$' + field.fieldPath.split('.$')[0] };
441
+ }
490
442
  });
491
- selectedFields.filter(function (a) { return a.fieldPath.split('.$').length === 2; }).forEach(function (field) {
492
- if (field.leafValueType === 'Count') {
493
- initialNonSumValueProj.$addFields[field.id] = { '$size': '$rb_arrays_0_' + field.id + field.fieldPath.split('.$')[1] };
443
+ query.push({ $group: queryGroup_1 });
444
+ }
445
+ else {
446
+ queryGroup_2 = {
447
+ _id: '$_id'
448
+ };
449
+ selectedFields.filter(function (a) { return !a.fieldPath.includes('.$'); }).forEach(function (field) {
450
+ if (field.leafValueType === 'Average') {
451
+ queryGroup_2[field.id] = { '$avg': '$' + field.fieldPath.replace(/\.\$/g, '') };
452
+ }
453
+ else if (field.leafValueType === 'Sum') {
454
+ queryGroup_2[field.id] = { '$sum': '$' + field.fieldPath.replace(/\.\$/g, '') };
455
+ }
456
+ else if (field.leafValueType === 'Count') {
457
+ queryGroup_2[field.id] = { '$sum': 1 };
494
458
  }
495
459
  else if (field.leafValueType === 'Minimum') {
496
- initialNonSumValueProj.$addFields[field.id] = { '$min': '$rb_arrays_0_' + field.id + field.fieldPath.split('.$')[1] };
460
+ queryGroup_2[field.id] = { '$min': '$' + field.fieldPath.replace(/\.\$/g, '') };
497
461
  }
498
462
  else if (field.leafValueType === 'Maximum') {
499
- initialNonSumValueProj.$addFields[field.id] = { '$max': '$rb_arrays_0_' + field.id + field.fieldPath.split('.$')[1] };
463
+ queryGroup_2[field.id] = { '$max': '$' + field.fieldPath.replace(/\.\$/g, '') };
500
464
  }
501
465
  else if (field.leafValueType === 'First') {
502
- initialNonSumValueProj.$addFields[field.id] = { '$arrayElemAt': ['$rb_arrays_0_' + field.id + field.fieldPath.split('.$')[1], 0] };
466
+ queryGroup_2[field.id] = { '$first': '$' + field.fieldPath.replace(/\.\$/g, '') };
503
467
  }
504
468
  else if (field.leafValueType === 'Last') {
505
- initialNonSumValueProj.$addFields[field.id] = { '$arrayElemAt': ['$rb_arrays_0_' + field.id + field.fieldPath.split('.$')[1], -1] };
469
+ queryGroup_2[field.id] = { '$last': '$' + field.fieldPath.replace(/\.\$/g, '') };
506
470
  }
507
- else { //push
508
- initialNonSumValueProj.$addFields[field.id] = '$rb_arrays_0_' + field.id + field.fieldPath.split('.$')[1];
471
+ else {
472
+ queryGroup_2[field.id] = { '$push': '$' + field.fieldPath.replace(/\.\$/g, '') };
509
473
  }
510
474
  });
511
- }
512
- cnt = 1;
513
- _loop_1 = function () {
514
- // Lookups
515
- var queryLookups = [];
516
- // Lookup Groups
517
- groupsRow.filter(function (a) { return a.treeItem.collection_name !== rootCollectionName && a.treeItem.fieldPath.split('.$').length === cnt + 3; }).forEach(function (group) {
518
- if (!queryLookups.filter(function (a) { return a.as === group.treeItem.lookup_as.replace(/\.\$/g, ''); }).length) {
519
- queryLookups.push({
520
- from: group.treeItem.lookup_collection,
521
- localField: 'rb_arrays_' + (cnt - 1) + '.' + group.treeItem.lookup_local_key,
522
- foreignField: group.treeItem.lookup_foreign_key,
523
- as: 'rb_arrays_' + (cnt - 1) + '.' + group.treeItem.lookup_as.replace(/\.\$/g, '')
475
+ //Totals
476
+ if (fieldsTotal.length) {
477
+ fieldsTotal.forEach(function (total) {
478
+ selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (field) {
479
+ var _a;
480
+ queryGroup_2[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + field.id, _a);
524
481
  });
482
+ });
483
+ }
484
+ // Copy Group Arrays Moving Forward
485
+ groupsRow.filter(function (a) { return a.field.includes('.$'); }).forEach(function (row) {
486
+ queryGroup_2[row.field.split('.$')[0]] = { $first: '$' + row.field.split('.$')[0] };
487
+ });
488
+ selectedFields.filter(function (a) { return a.fieldPath.includes('.$'); }).forEach(function (field) {
489
+ if (!queryGroup_2[field.fieldPath.split('.$')[0]]) {
490
+ queryGroup_2[field.fieldPath.split('.$')[0]] = { $push: '$' + field.fieldPath.split('.$')[0] };
525
491
  }
526
492
  });
527
- // Lookup Selected Fields
528
- uniqueSelectedFieldCollections.filter(function (a) { return a !== rootCollectionName; }).forEach(function (uniqueCollection) {
529
- selectedFields.filter(function (a) { return a.collection_name === uniqueCollection; }).forEach(function (field) {
530
- if (!queryLookups.filter(function (a) { return a.as === field.lookup_as.replace(/\.\$/g, ''); }).length && field.fieldPath.split('.$').length === cnt + 2) {
531
- queryLookups.push({
532
- from: field.lookup_collection,
533
- localField: 'rb_arrays_' + (cnt - 1) + '.' + field.lookup_local_key,
534
- foreignField: field.lookup_foreign_key,
535
- as: 'rb_arrays_' + (cnt - 1) + '.' + field.lookup_as.replace(/\.\$/g, '')
536
- });
493
+ query.push({ $group: queryGroup_2 });
494
+ }
495
+ /* --------------------- END IF GROUP ---------------------- */
496
+ // Lookup Selected Fields
497
+ selectedFields.filter(function (a) { return a.fieldPath.includes('.$'); }).forEach(function (field) {
498
+ // Unwind if from group
499
+ if (groupsRow.length && !groupsRow.some(function (a) { return a.field.split('.$')[0] === field.fieldPath.split('.$')[0]; })) {
500
+ query.push({ $unwind: {
501
+ path: '$' + field.fieldPath.split('.$')[0],
502
+ preserveNullAndEmptyArrays: true
503
+ } });
504
+ }
505
+ var path = '$';
506
+ // Loop for each array value (Not Grouped!)
507
+ for (var i = 0; i < field.fieldPath.split('.$').length; i++) {
508
+ path += field.fieldPath.split('.$')[i];
509
+ // Unwind
510
+ if (i < field.fieldPath.split('.$').length - 1 && !groupsRow.some(function (a) { return a.field.split('.$')[0] === field.fieldPath.split('.$')[0]; })) {
511
+ query.push({ $unwind: {
512
+ path: path,
513
+ preserveNullAndEmptyArrays: true
514
+ } });
515
+ }
516
+ // Link
517
+ if (!groupsRow.some(function (a) { return a.field.split('.$')[0] === field.fieldPath.split('.$')[0]; })) {
518
+ fieldsLink.filter(function (a) { return a.field_first && a.field_second; }).forEach(function (link) {
519
+ var _a, _b;
520
+ var firstLink = link.field_first.split('.$.');
521
+ firstLink.pop();
522
+ firstLink = firstLink.join('.');
523
+ var secondLink = link.field_second.split('.$.');
524
+ secondLink.pop();
525
+ secondLink = secondLink.join('.');
526
+ if ('$' + firstLink === path || '$' + secondLink === path) {
527
+ query.push({
528
+ $addFields: (_a = {},
529
+ _a[link.id] = {
530
+ $cmp: [
531
+ '$' + link.field_first.replace(/\.\$/g, ''),
532
+ '$' + link.field_second.replace(/\.\$/g, '')
533
+ ]
534
+ },
535
+ _a)
536
+ }, {
537
+ $match: (_b = {},
538
+ _b[link.id] = 0,
539
+ _b)
540
+ });
541
+ }
542
+ });
543
+ }
544
+ //Totals
545
+ if (i === field.fieldPath.split('.$').length - 1 && field.fieldType === 'Number') {
546
+ fieldsTotal.forEach(function (total) {
547
+ var _a;
548
+ query.push({ $addFields: (_a = {}, _a[total.id + '_' + field.id] = path, _a) });
549
+ });
550
+ }
551
+ }
552
+ // Regroup
553
+ var queryLoopGroup = {
554
+ _id: {}
555
+ };
556
+ if (!groupsRow.length) {
557
+ queryLoopGroup._id = '$_id';
558
+ }
559
+ groupsRow.forEach(function (row) {
560
+ queryLoopGroup._id[row.id] = '$_id.' + row.id;
561
+ if (date_field && date_interval) {
562
+ if (date_interval === 'Daily') {
563
+ queryLoopGroup._id['day'] = '$_id.day';
564
+ queryLoopGroup._id['month'] = '$_id.month';
565
+ queryLoopGroup._id['year'] = '$_id.year';
537
566
  }
538
- });
539
- });
540
- queryLookups.forEach(function (lookup) {
541
- zipLayers.push({ $lookup: lookup });
567
+ else if (date_interval === 'Weekly') {
568
+ queryLoopGroup._id['week'] = '$_id.week';
569
+ // queryGroup._id['month'] = {'$month' : '$' + date_field.replace(/\.\$/g, '')};
570
+ queryLoopGroup._id['year'] = '$_id.year';
571
+ }
572
+ else if (date_interval === 'Monthly') {
573
+ queryLoopGroup._id['month'] = '$_id.month';
574
+ queryLoopGroup._id['year'] = '$_id.year';
575
+ }
576
+ else if (date_interval === 'Quarterly') {
577
+ queryLoopGroup._id['month'] = '$_id.month';
578
+ queryLoopGroup._id['year'] = '$_id.year';
579
+ }
580
+ else if (date_interval === 'Yearly') {
581
+ queryLoopGroup._id['year'] = '$_id.year';
582
+ }
583
+ }
542
584
  });
543
- var proj = { $addFields: {} };
544
- if (selectedFields.some(function (a) { return a.fieldPath.split('.$').length === cnt + 2; })) {
545
- proj.$addFields['rb_arrays_' + cnt] = {
546
- $map: {
547
- input: {
548
- $zip: {
549
- inputs: [],
550
- useLongestLength: true
551
- }
552
- },
553
- as: 'zipped',
554
- in: {}
585
+ selectedFields.forEach(function (selField) {
586
+ if (selField.id === field.id) {
587
+ if (selField.leafValueType === 'Average') {
588
+ queryLoopGroup[selField.id] = { '$avg': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, '')) };
555
589
  }
556
- };
557
- var indexCnt_1 = 0;
558
- selectedFields.filter(function (a) { return a.fieldPath.split('.$').length === cnt + 2; }).forEach(function (field) {
559
- var fieldPath = field.fieldPath.split('.$')[0];
560
- for (var i = 1; i < cnt + 1; i++) {
561
- fieldPath += field.fieldPath.split('.$')[i];
590
+ else if (selField.leafValueType === 'Sum') {
591
+ queryLoopGroup[selField.id] = { '$sum': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, '')) };
562
592
  }
563
- if (!proj.$addFields['rb_arrays_' + cnt].$map.input.$zip.inputs.some(function (a) { return a === '$' + fieldPath; })) {
564
- if (!proj.$addFields['rb_arrays_' + cnt].$map.input.$zip.inputs.some(function (a) { return a === '$rb_arrays_' + (cnt - 1) + '.' + fieldPath; })) {
565
- proj.$addFields['rb_arrays_' + cnt].$map.input.$zip.inputs.push('$rb_arrays_' + (cnt - 1) + '.' + fieldPath);
566
- proj.$addFields['rb_arrays_' + cnt].$map.in[field.fieldPath.split('.$.')[cnt].replace(new RegExp(/\./g), '_')] = {
567
- $arrayElemAt: ['$$zipped', indexCnt_1++]
568
- };
569
- }
593
+ else if (selField.leafValueType === 'Count') {
594
+ queryLoopGroup[selField.id] = { '$sum': 1 };
570
595
  }
571
- });
572
- zipLayers.push(proj);
573
- if (selectedFields.some(function (a) { return a.fieldPath.split('.$').length === cnt + 2; })) {
574
- var proj_1 = { $addFields: {} };
575
- selectedFields.filter(function (a) { return a.fieldPath.split('.$').length === cnt + 2; }).forEach(function (field) {
576
- var _a;
577
- proj_1.$addFields['rb_arrays_' + cnt + '_' + field.id] = {
578
- $filter: {
579
- input: '$rb_arrays_' + cnt,
580
- cond: {
581
- $and: [
582
- { $ne: ['$$this', null] }
583
- ]
584
- }
585
- }
586
- };
587
- var path = '$$this' + '.' + field.fieldPath.split('.$.')[cnt];
588
- proj_1.$addFields['rb_arrays_' + cnt + '_' + field.id].$filter.cond.$and.push({ $ne: [path, null] });
589
- if (filterArrayPaths.some(function (a) { return a.replace(new RegExp(/\.\w+$/), '') === field.fieldPath.replace(new RegExp(/\.\w+$/), ''); })) {
590
- var tmpOr_2 = [];
591
- var filter = common_1.deepCopy(filterArrays[filterArrayPaths.findIndex(function (a) { return a.replace(new RegExp(/\.\w+$/), '') === field.fieldPath.replace(new RegExp(/\.\w+$/), ''); })]);
592
- if (filter['$or']) {
593
- filter['$or'].forEach(function (orVal) {
594
- var _a;
595
- var tmpFilterPath = '';
596
- for (var k = cnt; k < (Object.keys(orVal)[0]).split('.').length; k++) {
597
- if (tmpFilterPath) {
598
- tmpFilterPath += '.';
599
- }
600
- tmpFilterPath += (Object.keys(orVal)[0]).split('.')[k];
601
- }
602
- var filterPath = '$$this.' + tmpFilterPath;
603
- tmpOr_2.push((_a = {},
604
- _a[Object.keys(orVal[Object.keys(orVal)[0]])[0]] = [filterPath, orVal[Object.keys(orVal)[0]][Object.keys(orVal[Object.keys(orVal)[0]])[0]]],
605
- _a));
606
- });
607
- }
608
- else {
609
- var tmpFilterPath = '';
610
- for (var k = cnt; k < (Object.keys(filter)[0]).split('.').length; k++) {
611
- if (tmpFilterPath) {
612
- tmpFilterPath += '.';
613
- }
614
- tmpFilterPath += (Object.keys(filter)[0]).split('.')[k];
615
- }
616
- var filterPath = '$$this.' + tmpFilterPath;
617
- proj_1.$addFields['rb_arrays_' + cnt + '_' + field.id].$filter.cond.$and.push((_a = {}, _a[Object.keys(filter[Object.keys(filter)[0]])[0]] = [filterPath, filter[Object.keys(filter)[0]][Object.keys(filter[Object.keys(filter)[0]])[0]]], _a));
618
- }
619
- if (tmpOr_2.length) {
620
- proj_1.$addFields['rb_arrays_' + cnt + '_' + field.id].$filter.cond.$and.push({ $or: tmpOr_2 });
621
- }
622
- }
623
- });
624
- zipLayers.push(proj_1);
625
- proj_1 = { $addFields: {} };
626
- selectedFields.filter(function (a) { return a.fieldPath.split('.$').length === cnt + 2; }).forEach(function (field) {
627
- proj_1.$addFields['rb_arrays_' + cnt + '_' + field.id] = '$rb_arrays_' + cnt + '_' + field.id + field.fieldPath.split('.$')[cnt];
628
- });
629
- zipLayers.push(proj_1);
630
- proj_1 = { $addFields: {} };
631
- selectedFields.filter(function (a) { return a.fieldPath.split('.$').length === cnt + 2; }).forEach(function (field) {
632
- if (field.leafValueType === 'Count') {
633
- proj_1.$addFields[field.id] = { '$size': '$rb_arrays_' + cnt + '_' + field.id + field.fieldPath.split('.$')[cnt + 1] };
634
- }
635
- else if (field.leafValueType === 'Minimum') {
636
- proj_1.$addFields[field.id] = { '$min': '$rb_arrays_' + cnt + '_' + field.id + field.fieldPath.split('.$')[cnt + 1] };
637
- }
638
- else if (field.leafValueType === 'Maximum') {
639
- proj_1.$addFields[field.id] = { '$max': '$rb_arrays_' + cnt + '_' + field.id + field.fieldPath.split('.$')[cnt + 1] };
640
- }
641
- else if (field.leafValueType === 'First') {
642
- proj_1.$addFields[field.id] = { '$arrayElemAt': ['$rb_arrays_' + cnt + '_' + field.id + field.fieldPath.split('.$')[cnt + 1], 0] };
643
- }
644
- else if (field.leafValueType === 'Last') {
645
- proj_1.$addFields[field.id] = { '$arrayElemAt': ['$rb_arrays_' + cnt + '_' + field.id + field.fieldPath.split('.$')[cnt + 1], -1] };
646
- }
647
- else if (field.leafValueType === 'Sum') {
648
- proj_1.$addFields[field.id] = { '$sum': '$rb_arrays_' + cnt + '_' + field.id + field.fieldPath.split('.$')[cnt + 1] };
649
- }
650
- else if (field.leafValueType === 'Average') {
651
- proj_1.$addFields[field.id] = { '$avg': '$rb_arrays_' + cnt + '_' + field.id + field.fieldPath.split('.$')[cnt + 1] };
652
- }
653
- else { //push
654
- proj_1.$addFields[field.id] = '$rb_arrays_' + cnt + '_' + field.id + field.fieldPath.split('.$')[cnt + 1];
655
- }
656
- });
657
- zipLayers.push(proj_1);
658
- group = { $group: { _id: {} } };
659
- if (selectedFields.some(function (a) { return a.fieldPath.split('.$').length > cnt + 1; })) {
660
- groupsRow.forEach(function (row) {
661
- group.$group._id[row.id] = '$_id.' + row.id;
662
- });
663
- group.$group['rb_arrays_' + (cnt - 1)] = { '$push': '$rb_arrays_' + (cnt - 1) };
664
- selectedFields.filter(function (a) { return a.fieldPath.split('.$').length <= cnt + 2; }).forEach(function (field) {
665
- group.$group[field.id] = { $first: '$' + field.id };
666
- });
667
- if (fieldsTotal.length) {
668
- fieldsTotal.forEach(function (total) {
669
- selectedFields.filter(function (a) { return a.fieldType === 'Number' && a.fieldPath.split('.$').length === 1; }).forEach(function (field) {
670
- group.$group[total.id + '_' + field.id] = { $first: '$' + total.id + '_' + field.id };
671
- });
672
- selectedFields.filter(function (a) { return a.fieldType === 'Number' && a.fieldPath.split('.$').length < cnt + 2 && a.fieldPath.split('.$').length > 1; }).forEach(function (field) {
673
- var tmpPath = field.fieldPath.split('.$.')[cnt - 1] + field.fieldPath.split('.$')[cnt];
674
- group.$group[total.id + '_' + field.id] = { $first: '$rb_arrays_' + (cnt - 1) + '.' + tmpPath };
675
- });
676
- selectedFields.filter(function (a) { return a.fieldType === 'Number' && a.fieldPath.split('.$').length === cnt + 2; }).forEach(function (field) {
677
- var _a;
678
- var tmpPath = field.fieldPath.split('.$.')[cnt - 1] + field.fieldPath.split('.$')[cnt];
679
- group.$group[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + field.id, _a);
680
- });
681
- });
682
- }
683
- zipLayers.push(group);
596
+ else if (selField.leafValueType === 'Minimum') {
597
+ queryLoopGroup[selField.id] = { '$min': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, '')) };
598
+ }
599
+ else if (selField.leafValueType === 'Maximum') {
600
+ queryLoopGroup[selField.id] = { '$max': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, '')) };
601
+ }
602
+ else if (selField.leafValueType === 'First') {
603
+ queryLoopGroup[selField.id] = { '$first': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, '')) };
604
+ }
605
+ else if (selField.leafValueType === 'Last') {
606
+ queryLoopGroup[selField.id] = { '$last': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, '')) };
607
+ }
608
+ else {
609
+ queryLoopGroup[selField.id] = { '$push': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, '')) };
684
610
  }
685
611
  }
686
- if (selectedFields.some(function (a) { return a.fieldPath.split('.$').length > cnt + 2; })) {
687
- zipLayers.push({ $unwind: {
688
- path: '$rb_arrays_' + cnt,
689
- preserveNullAndEmptyArrays: true
690
- } });
612
+ else {
613
+ queryLoopGroup[selField.id] = { '$first': '$' + selField.id };
691
614
  }
692
- }
693
- cnt++;
694
- };
695
- while (selectedFields.some(function (a) { return a.fieldPath.split('.$').length > cnt; })) {
696
- _loop_1();
697
- }
698
- if (groupsRow.length) {
699
- // groupsRow.forEach(row => {
700
- // if (row.field.includes('$')) {
701
- // let fieldData = row.field.split('.$');
702
- // let fieldPath = '';
703
- // for (let i = 0; i < fieldData.length - 1; i++) {
704
- // fieldPath += fieldData[i];
705
- // queryGroupUnwind.push({'$unwind': {path: '$' + fieldPath, preserveNullAndEmptyArrays: true}});
706
- // }
707
- // }
708
- // initialGroup._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
709
- // if (date_field && date_interval) {
710
- // if (date_interval === 'Daily') {
711
- // initialGroup._id['day'] = {'$dayOfMonth' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
712
- // initialGroup._id['month'] = {'$month' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
713
- // initialGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
714
- // }
715
- // else if (date_interval === 'Weekly') {
716
- // initialGroup._id['week'] = {'$week' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
717
- // // queryGroup._id['month'] = {'$month' : '$' + date_field.replace(/\.\$/g, '')};
718
- // initialGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
719
- // }
720
- // else if (date_interval === 'Monthly') {
721
- // initialGroup._id['month'] = {'$month' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
722
- // initialGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
723
- // }
724
- // else if (date_interval === 'Quarterly') {
725
- // initialGroup._id['month'] = {'$month' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
726
- // initialGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
727
- // }
728
- // else if (date_interval === 'Yearly') {
729
- // initialGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
730
- // }
731
- // }
732
- // });
733
- // selectedFields.filter(a => !a.fieldPath.includes('$')).forEach(field => {
734
- // if (field.leafValueType === 'Average') {
735
- // initialGroup[field.id] = {'$avg': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, ''))};
736
- // }
737
- // else if (field.leafValueType === 'Sum') {
738
- // initialGroup[field.id] = {'$sum': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, ''))};
739
- // }
740
- // else if (field.leafValueType === 'Count') {
741
- // initialGroup[field.id] = {'$sum': 1};
742
- // }
743
- // else if (field.leafValueType === 'Minimum') {
744
- // initialGroup[field.id] = {'$min': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, ''))};
745
- // }
746
- // else if (field.leafValueType === 'Maximum') {
747
- // initialGroup[field.id] = {'$max': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, ''))};
748
- // }
749
- // else if (field.leafValueType === 'First') {
750
- // initialGroup[field.id] = {'$first': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, ''))};
751
- // }
752
- // else if (field.leafValueType === 'Last') {
753
- // initialGroup[field.id] = {'$last': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, ''))};
754
- // }
755
- // else {
756
- // initialGroup[field.id] = {'$push': '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, ''))};
757
- // }
758
- // });
615
+ });
759
616
  //Totals
760
- // if (fieldsTotal.length) {
761
- // fieldsTotal.forEach(total => {
762
- // selectedFields.filter(a => a.fieldType === 'Number' && !a.fieldPath.includes('$')).forEach(field => {
763
- // initialGroup[total.id + '_' + field.id] = {['$' + total.type]: '$' + field.fieldPath.replace(/\.\$/g, '')};
764
- // });
765
- // });
766
- // }
767
- //Arrays
768
- // selectedFields.filter(a => a.fieldPath.includes('$')).forEach(field => {
769
- // });
770
- //Links
771
- // if (fieldsLink.length) {
772
- // fieldsLink.filter(a => a.field_first && a.field_second).forEach(link => {
773
- // queryGroup[link.id] = {$cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')]};
774
- // });
775
- // }
776
- if (rootOptions.sort && reportType === 'Tabular Group') {
777
- correctSort_1 = {};
778
- Object.keys(rootOptions.sort).forEach(function (key) {
779
- correctSort_1[selectedFields.filter(function (a) { return a.id === key; })[0].fieldPath.replace(/\.\$/g, '')] = rootOptions.sort[key];
780
- });
781
- queryGroups.push({
782
- $sort: correctSort_1
617
+ if (fieldsTotal.length) {
618
+ fieldsTotal.forEach(function (total) {
619
+ selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (selField) {
620
+ var _a;
621
+ if (selField.id === field.id) {
622
+ queryLoopGroup[total.id + '_' + selField.id] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + selField.id, _a);
623
+ }
624
+ else {
625
+ queryLoopGroup[total.id + '_' + selField.id] = { $first: '$' + total.id + '_' + selField.id };
626
+ }
627
+ });
783
628
  });
784
629
  }
785
- if (reportType === 'Tabular Group') {
786
- _loop_2 = function (i) {
787
- var _a, _b;
788
- queryGroups.push({ $sort: (_a = {}, _a['_id.' + groupsRow[i].id] = 1, _a) });
789
- var tmpQueryGroup = {
790
- _id: {}
791
- };
792
- for (var j = 0; j < i; j++) {
793
- tmpQueryGroup._id[groupsRow[j].id] = '$_id.' + groupsRow[j].id;
794
- }
795
- var tmpQueryGroupObj = (_b = {},
796
- _b[groupsRow[i].id] = '$_id.' + [groupsRow[i].id],
797
- _b);
798
- if (i === groupsRow.length - 1) {
799
- selectedFields.forEach(function (field) {
800
- tmpQueryGroupObj[field.id] = '$' + field.id;
801
- });
630
+ // Copy Group Arrays Moving Forward
631
+ groupsRow.filter(function (a) { return a.field.includes('.$'); }).forEach(function (row) {
632
+ queryLoopGroup[row.field.split('.$')[0]] = { $first: '$' + row.field.split('.$')[0] };
633
+ });
634
+ selectedFields.filter(function (a) { return a.fieldPath.includes('.$'); }).forEach(function (selField) {
635
+ if (selField.id === field.id) {
636
+ if (!queryLoopGroup[selField.fieldPath.split('.$')[0]]) {
637
+ queryLoopGroup[selField.fieldPath.split('.$')[0]] = { $push: '$' + selField.fieldPath.split('.$')[0] };
802
638
  }
803
- else {
804
- tmpQueryGroupObj[groupsRow[i + 1].id] = '$' + [groupsRow[i + 1].id];
639
+ }
640
+ else {
641
+ if (!queryLoopGroup[selField.fieldPath.split('.$')[0]]) {
642
+ queryLoopGroup[selField.fieldPath.split('.$')[0]] = { $first: '$' + selField.fieldPath.split('.$')[0] };
805
643
  }
806
- fieldsTotal.forEach(function (total) {
807
- selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (field) {
808
- var _a;
809
- tmpQueryGroupObj[total.id + '_' + field.id] = '$' + total.id + '_' + field.id;
810
- tmpQueryGroup[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + field.id, _a);
811
- });
812
- });
813
- tmpQueryGroup[groupsRow[i].id] = { '$push': tmpQueryGroupObj };
814
- queryGroups.push({ $group: tmpQueryGroup });
815
- };
816
- for (i = groupsRow.length - 1; i > 0; i--) {
817
- _loop_2(i);
818
644
  }
819
- queryGroups.push({ $sort: (_a = {}, _a['_id.' + groupsRow[0].id] = 1, _a) });
820
- }
821
- else if (reportType === 'Dated') {
822
- // db.collection.aggregate([
823
- // { "$group": {
824
- // "_id": {
825
- // "$toDate": {
826
- // "$subtract": [
827
- // { "$toLong": "$created_at" },
828
- // { "$mod": [ { "$toLong": "$created_at" }, 1000 * 60 * 15 ] }
829
- // ]
830
- // }
831
- // },
832
- // "count": { "$sum": 1 }
833
- // }}
834
- // ])
835
- }
836
- }
837
- queryProjection = {
838
- _id: 1
839
- };
840
- selectedFields.forEach(function (field) {
841
- if (field.leafValueType === 'Average') {
842
- queryProjection[field.id] = { $avg: '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
843
- }
844
- else if (field.leafValueType === 'Sum') {
845
- queryProjection[field.id] = { $sum: '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
846
- }
847
- else if (field.leafValueType === 'Count') {
848
- queryProjection[field.id] = { $sum: 1 };
849
- }
850
- else if (field.leafValueType === 'Minimum') {
851
- queryProjection[field.id] = { $min: '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
852
- }
853
- else if (field.leafValueType === 'Maximum') {
854
- queryProjection[field.id] = { $max: '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')) };
855
- }
856
- else if (field.leafValueType === 'First') {
857
- queryProjection[field.id] = { $slice: ['$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')), 0] };
858
- }
859
- else if (field.leafValueType === 'Last') {
860
- queryProjection[field.id] = { $slice: ['$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, '')), -1] };
861
- }
862
- else {
863
- queryProjection[field.id] = '$' + (field.collection_name === rootCollectionName ? field.fieldPath.replace(/\.\$/g, '') : field.fieldPath.replace(/\.\$/g, ''));
864
- }
865
- });
866
- //Links
867
- if (fieldsLink.length) {
868
- fieldsLink.filter(function (a) { return a.field_first && a.field_second; }).forEach(function (link) {
869
- queryProjection[link.id] = { $cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')] };
870
645
  });
871
- }
646
+ query.push({ $group: queryLoopGroup });
647
+ // Sort
648
+ });
872
649
  queryTotals = null;
873
650
  if (fieldsTotal.length && (reportType === 'Tabular' || reportType === 'Dated')) {
874
651
  fieldsTotal.forEach(function (total) {
@@ -881,68 +658,8 @@ function loadReportBuilderMethods(methodManager) {
881
658
  });
882
659
  });
883
660
  }
884
- query = [];
885
- // Non-Lookup Filters
886
- 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) {
887
- query.push({
888
- $match: queryMatchCondition
889
- });
890
- }
891
- initialLookups.forEach(function (lookup) {
892
- query.push({ $lookup: lookup });
893
- });
894
- // Group w/ root properties & all arrays needed
895
- query.push({
896
- $project: initialProjection
897
- });
898
- if (initialTotals) {
899
- query.push(initialTotals);
900
- }
901
- if (initialGroup) {
902
- query.push({
903
- $group: initialGroup
904
- });
905
- }
906
- if (secondInitialGroup) {
907
- query.push({
908
- $unwind: {
909
- "path": "$rb_arrays_0",
910
- "preserveNullAndEmptyArrays": true
911
- }
912
- });
913
- secondInitialLookup.forEach(function (lookup) {
914
- query.push(lookup);
915
- });
916
- query.push({
917
- $group: secondInitialGroup
918
- });
919
- }
920
- if (initialNonSumFilterProj) {
921
- query.push(initialNonSumFilterProj);
922
- }
923
- if (initialNonSumElemAtProj) {
924
- query.push(initialNonSumElemAtProj);
925
- }
926
- if (initialNonSumValueProj) {
927
- query.push(initialNonSumValueProj);
928
- }
929
- if (selectedFields.some(function (a) { return a.fieldPath.split('.$').length > 2; })) {
930
- query.push({
931
- $unwind: {
932
- "path": "$rb_arrays_0",
933
- "preserveNullAndEmptyArrays": true
934
- }
935
- });
936
- }
937
- for (i = 0; i < zipLayers.length; i++) {
938
- query.push(zipLayers[i]);
939
- }
940
- // START LOOP
941
- // Project results and layer rb_arrays (for $sum)
942
- // Unwind rb_arrays
943
- // Group that layer's props ($sum) and keep next layer
944
- // END LOOP
945
- // Unwind Pre-Lookup Arrays
661
+ // // ---------------------------------------------------------------
662
+ // // Unwind Pre-Lookup Arrays
946
663
  // queryUnwindCollectionPaths.filter(a => !a.includes('(Lookup)')).forEach(path => {
947
664
  // query.push({
948
665
  // $unwind: {
@@ -959,12 +676,6 @@ function loadReportBuilderMethods(methodManager) {
959
676
  // }
960
677
  // });
961
678
  // });
962
- // // Look Ups
963
- // queryLookups.forEach(lookup => {
964
- // query.push({
965
- // $lookup: lookup
966
- // });
967
- // });
968
679
  // // Unwind Lookups
969
680
  // queryUnwindCollectionPaths.filter(a => a.includes('(Lookup)')).forEach(path => {
970
681
  // if (!query.filter(a => a.$unwind && a.$unwind.path === path).length) {
@@ -1157,15 +868,15 @@ function loadReportBuilderMethods(methodManager) {
1157
868
  console.log(query);
1158
869
  console.log(JSON.stringify(query, null, 2));
1159
870
  res = null;
1160
- _b.label = 1;
871
+ _a.label = 1;
1161
872
  case 1:
1162
- _b.trys.push([1, 3, , 4]);
873
+ _a.trys.push([1, 3, , 4]);
1163
874
  return [4 /*yield*/, modelCollection.aggregate(query).allowDiskUse(true)];
1164
875
  case 2:
1165
- res = _b.sent();
876
+ res = _a.sent();
1166
877
  return [3 /*break*/, 4];
1167
878
  case 3:
1168
- err_1 = _b.sent();
879
+ err_1 = _a.sent();
1169
880
  console.log(err_1);
1170
881
  return [3 /*break*/, 4];
1171
882
  case 4: