@resolveio/server-lib 4.5.12 → 4.6.0-newrole

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.
@@ -195,7 +195,7 @@ function loadReportBuilderMethods(methodManager) {
195
195
  if (date_field === void 0) { date_field = ''; }
196
196
  if (date_interval === void 0) { date_interval = ''; }
197
197
  return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
198
- var uniqueSelectedFieldCollections, modelCollection, query, initialQueryMatchCondition, groupQueries, queryGroup_1, queryGroup_2, queryTotals, res, err_1;
198
+ var uniqueSelectedFieldCollections, modelCollection, query, initialQueryMatchCondition, sizes, divFields, queryGroup, res, err_1, tmpTotals, tmpRes;
199
199
  var _this = this;
200
200
  return __generator(this, function (_a) {
201
201
  switch (_a.label) {
@@ -233,637 +233,211 @@ function loadReportBuilderMethods(methodManager) {
233
233
  $match: initialQueryMatchCondition
234
234
  });
235
235
  }
236
- groupQueries = [];
236
+ // Add count
237
+ query.push({ $addFields: { count: { $sum: 1 } } });
238
+ sizes = [];
239
+ // Groups - Lookups / Sizes / Unwinds
237
240
  groupsRow.forEach(function (row) {
241
+ var _a, _b;
238
242
  if (row.field.includes('$')) {
239
243
  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: {
244
+ var fieldPath = '';
245
+ for (var i = 0; i < fieldData.length - 1; i++) {
246
+ fieldPath += fieldData[i];
247
+ if (fieldPath.split('.$')[fieldPath.split('.$').length - 1].includes('(Lookup)')) {
248
+ query.push({ $lookup: {
245
249
  from: row.treeItem.lookup_collection,
246
250
  localField: row.treeItem.lookup_local_key,
247
251
  foreignField: row.treeItem.lookup_foreign_key,
248
252
  as: row.treeItem.lookup_as.replace(/\.\$/g, '')
249
253
  } });
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);
282
- }
254
+ sizes.push(row.treeItem.lookup_as.replace(/\.\$\./g, '_'));
255
+ query.push({ $addFields: (_a = {}, _a['size_' + row.treeItem.lookup_as.replace(/\.\$\./g, '_')] = { $size: '$' + row.treeItem.lookup_as.replace(/\.\$/g, '') }, _a) });
256
+ query.push({ '$unwind': { path: '$' + row.treeItem.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
283
257
  }
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);
258
+ else {
259
+ sizes.push(fieldPath.replace(/\./g, '_'));
260
+ query.push({ $addFields: (_b = {}, _b['size_' + fieldPath.replace(/\./g, '_')] = { $size: '$' + fieldPath }, _b) });
261
+ query.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
293
262
  }
294
- };
295
- for (var i = 0; i < fieldData.length - 1; i++) {
296
- _loop_1(i);
297
263
  }
298
264
  }
299
265
  });
300
- if (!groupsRow.length) {
301
- selectedFields.forEach(function (field) {
266
+ // Selected Fields - Lookups / Sizes / Unwinds
267
+ selectedFields.forEach(function (field) {
268
+ var _a, _b;
269
+ if (field.fieldPath.includes('$')) {
302
270
  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, '')
312
- } });
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);
324
- }
271
+ var fieldPath_1 = '';
272
+ for (var i = 0; i < fieldData.length - 1; i++) {
273
+ fieldPath_1 += fieldData[i];
274
+ if (fieldPath_1.split('.$')[fieldPath_1.split('.$').length - 1].includes('(Lookup)')) {
275
+ if (!query.some(function (a) { return a.$lookup && a.$lookup.as === field.lookup_as.replace(/\.\$/g, ''); })) {
276
+ query.push({ $lookup: {
277
+ from: field.lookup_collection,
278
+ localField: field.lookup_local_key,
279
+ foreignField: field.lookup_foreign_key,
280
+ as: field.lookup_as.replace(/\.\$/g, '')
281
+ } });
282
+ sizes.push(field.lookup_as.replace(/\.\$\./g, '_'));
283
+ query.push({ $addFields: (_a = {}, _a['size_' + field.lookup_as.replace(/\.\$\./g, '_')] = { $size: '$' + field.lookup_as.replace(/\.\$/g, '') }, _a) });
284
+ query.push({ '$unwind': { path: '$' + field.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
325
285
  }
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
286
  }
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);
287
+ else {
288
+ if (!query.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath_1.replace(/\./g, '_')); })) {
289
+ sizes.push(fieldPath_1.replace(/\./g, '_'));
290
+ query.push({ $addFields: (_b = {}, _b['size_' + fieldPath_1.replace(/\./g, '_')] = { $size: '$' + fieldPath_1 }, _b) });
291
+ query.push({ '$unwind': { path: '$' + fieldPath_1, preserveNullAndEmptyArrays: true } });
345
292
  }
346
293
  }
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
- });
354
- });
355
- groupQueries.push(addFields_6);
356
- }
357
- };
358
- for (var i = 0; i < fieldData.length - 1; i++) {
359
- _loop_2(i);
360
- }
361
- });
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
- };
370
- groupsRow.forEach(function (row) {
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
- }
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
294
  }
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, '') };
295
+ }
296
+ });
297
+ divFields = { $addFields: {} };
298
+ fieldsTotal.filter(function (a) { return a.type === 'sum'; }).forEach(function (total) {
299
+ selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (field) {
300
+ var multFields = [];
301
+ if (!field.fieldPath.includes('.$')) {
302
+ sizes.forEach(function (size) {
303
+ multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
304
+ });
412
305
  }
413
- else if (field.leafValueType === 'First') {
414
- queryGroup_1[field.id] = { '$first': '$' + field.fieldPath.replace(/\.\$/g, '') };
306
+ else {
307
+ sizes.filter(function (a) { return !field.fieldPath.replace(/\.\$\./g, '_').includes(a) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').includes(a); }); }).forEach(function (size) {
308
+ multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
309
+ });
415
310
  }
416
- else if (field.leafValueType === 'Last') {
417
- queryGroup_1[field.id] = { '$last': '$' + field.fieldPath.replace(/\.\$/g, '') };
311
+ if (multFields.length) {
312
+ if (field.leafValueType === 'Count') {
313
+ divFields.$addFields[total.id + '_' + field.id] = {
314
+ $divide: ['$count', { $multiply: multFields }]
315
+ };
316
+ }
317
+ else {
318
+ divFields.$addFields[total.id + '_' + field.id] = {
319
+ $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
320
+ };
321
+ }
418
322
  }
419
323
  else {
420
- queryGroup_1[field.id] = { '$push': '$' + field.fieldPath.replace(/\.\$/g, '') };
324
+ if (field.leafValueType === 'Count') {
325
+ divFields.$addFields[total.id + '_' + field.id] = '$count';
326
+ }
327
+ else {
328
+ divFields.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
329
+ }
421
330
  }
422
- // if (field.fieldPath.includes('.$') && ) {
423
- // }
424
331
  });
425
- //Totals
426
- if (fieldsTotal.length) {
427
- fieldsTotal.forEach(function (total) {
428
- selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (field) {
429
- var _a;
430
- queryGroup_1[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$' + total.id + '_' + field.id, _a);
431
- });
332
+ });
333
+ selectedFields.filter(function (a) { return a.fieldType === 'Number' && a.leafValueType === 'Sum'; }).forEach(function (field) {
334
+ var multFields = [];
335
+ if (field.fieldPath.includes('.$')) {
336
+ sizes.filter(function (a) { return !field.fieldPath.replace(/\.\$\./g, '_').includes(a) && !groupsRow.some(function (b) { return b.field.replace(/\.\$\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').includes(a); }); }).forEach(function (size) {
337
+ multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
432
338
  });
433
339
  }
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] };
437
- });
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
- }
340
+ if (multFields.length) {
341
+ divFields.$addFields[field.fieldPath.replace(/\.\$/g, '')] = {
342
+ $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
343
+ };
344
+ }
345
+ });
346
+ selectedFields.filter(function (a) { return a.fieldType === 'Number' && a.leafValueType === 'Count'; }).forEach(function (field) {
347
+ var multFields = [];
348
+ sizes.filter(function (a) { return !field.fieldPath.replace(/\.\$\./g, '_').includes(a) && !groupsRow.some(function (b) { return b.field.replace(/\.\$\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').includes(a); }); }).forEach(function (size) {
349
+ multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
442
350
  });
443
- query.push({ $group: queryGroup_1 });
351
+ if (multFields.length) {
352
+ divFields.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = {
353
+ $divide: ['$count', { $multiply: multFields }]
354
+ };
355
+ }
356
+ else {
357
+ divFields.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = '$count';
358
+ }
359
+ });
360
+ if (Object.keys(divFields.$addFields).length > 0) {
361
+ query.push(divFields);
444
362
  }
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 };
458
- }
459
- else if (field.leafValueType === 'Minimum') {
460
- queryGroup_2[field.id] = { '$min': '$' + field.fieldPath.replace(/\.\$/g, '') };
363
+ fieldsLink.filter(function (a) { return a.field_first && a.field_second; }).forEach(function (link) {
364
+ var _a, _b;
365
+ query.push({ $addFields: (_a = {}, _a[link.id] = { $cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')] }, _a) });
366
+ query.push({ $match: (_b = {}, _b[link.id] = 0, _b) });
367
+ });
368
+ queryGroup = {
369
+ _id: {}
370
+ };
371
+ if (!groupsRow.length) {
372
+ queryGroup._id = '$_id';
373
+ }
374
+ groupsRow.forEach(function (row) {
375
+ queryGroup._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
376
+ if (date_field && date_interval) {
377
+ if (date_interval === 'Daily') {
378
+ queryGroup._id['day'] = { '$dayOfMonth': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
379
+ queryGroup._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
380
+ queryGroup._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
461
381
  }
462
- else if (field.leafValueType === 'Maximum') {
463
- queryGroup_2[field.id] = { '$max': '$' + field.fieldPath.replace(/\.\$/g, '') };
382
+ else if (date_interval === 'Weekly') {
383
+ queryGroup._id['week'] = { '$week': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
384
+ queryGroup._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
464
385
  }
465
- else if (field.leafValueType === 'First') {
466
- queryGroup_2[field.id] = { '$first': '$' + field.fieldPath.replace(/\.\$/g, '') };
386
+ else if (date_interval === 'Monthly') {
387
+ queryGroup._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
388
+ queryGroup._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
467
389
  }
468
- else if (field.leafValueType === 'Last') {
469
- queryGroup_2[field.id] = { '$last': '$' + field.fieldPath.replace(/\.\$/g, '') };
390
+ else if (date_interval === 'Quarterly') {
391
+ queryGroup._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
392
+ queryGroup._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
470
393
  }
471
- else {
472
- queryGroup_2[field.id] = { '$push': '$' + field.fieldPath.replace(/\.\$/g, '') };
394
+ else if (date_interval === 'Yearly') {
395
+ queryGroup._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': _this.serverConfig['TIMEZONE'] } };
473
396
  }
474
- });
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);
481
- });
482
- });
483
397
  }
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] };
491
- }
492
- });
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
- } });
398
+ });
399
+ selectedFields.forEach(function (field) {
400
+ if (field.leafValueType === 'Average') {
401
+ queryGroup[field.id] = { '$avg': '$' + field.fieldPath.replace(/\.\$/g, '') };
504
402
  }
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
- }
403
+ else if (field.leafValueType === 'Sum') {
404
+ queryGroup[field.id] = { '$sum': '$' + field.fieldPath.replace(/\.\$/g, '') };
551
405
  }
552
- // Regroup
553
- var queryLoopGroup = {
554
- _id: {}
555
- };
556
- if (!groupsRow.length) {
557
- queryLoopGroup._id = '$_id';
406
+ else if (field.leafValueType === 'Count') {
407
+ queryGroup[field.id] = { '$sum': '$count_' + field.fieldPath.replace(/\.\$/g, '') };
558
408
  }
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';
566
- }
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
- }
584
- });
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, '')) };
589
- }
590
- else if (selField.leafValueType === 'Sum') {
591
- queryLoopGroup[selField.id] = { '$sum': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, '')) };
592
- }
593
- else if (selField.leafValueType === 'Count') {
594
- queryLoopGroup[selField.id] = { '$sum': 1 };
595
- }
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, '')) };
610
- }
611
- }
612
- else {
613
- queryLoopGroup[selField.id] = { '$first': '$' + selField.id };
614
- }
615
- });
616
- //Totals
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
- });
628
- });
409
+ else if (field.leafValueType === 'Minimum') {
410
+ queryGroup[field.id] = { '$min': '$' + field.fieldPath.replace(/\.\$/g, '') };
411
+ }
412
+ else if (field.leafValueType === 'Maximum') {
413
+ queryGroup[field.id] = { '$max': '$' + field.fieldPath.replace(/\.\$/g, '') };
414
+ }
415
+ else if (field.leafValueType === 'First' || (!groupsRow.length && !field.fieldPath.includes('.$'))) {
416
+ queryGroup[field.id] = { '$first': '$' + field.fieldPath.replace(/\.\$/g, '') };
417
+ }
418
+ else if (field.leafValueType === 'Last') {
419
+ queryGroup[field.id] = { '$last': '$' + field.fieldPath.replace(/\.\$/g, '') };
420
+ }
421
+ else {
422
+ queryGroup[field.id] = { '$push': '$' + field.fieldPath.replace(/\.\$/g, '') };
629
423
  }
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] };
638
- }
639
- }
640
- else {
641
- if (!queryLoopGroup[selField.fieldPath.split('.$')[0]]) {
642
- queryLoopGroup[selField.fieldPath.split('.$')[0]] = { $first: '$' + selField.fieldPath.split('.$')[0] };
643
- }
644
- }
645
- });
646
- query.push({ $group: queryLoopGroup });
647
- // Sort
648
424
  });
649
- queryTotals = null;
650
- if (fieldsTotal.length && (reportType === 'Tabular' || reportType === 'Dated')) {
425
+ // Totals
426
+ if (fieldsTotal.length) {
651
427
  fieldsTotal.forEach(function (total) {
652
428
  selectedFields.filter(function (a) { return a.fieldType === 'Number'; }).forEach(function (field) {
653
- var _a;
654
- if (!queryTotals) {
655
- queryTotals = {};
656
- }
657
- queryTotals[total.id + '_' + field.id] = (_a = {}, _a['$' + total.type] = '$results.' + total.id + '_' + field.id, _a);
429
+ // queryGroup[total.id + '_' + field.id] = {['$' + total.type]: '$' + total.id + '_' + field.id};
430
+ queryGroup[total.id + '_' + field.id] = { $sum: '$' + total.id + '_' + field.id };
658
431
  });
659
432
  });
660
433
  }
661
- // // ---------------------------------------------------------------
662
- // // Unwind Pre-Lookup Arrays
663
- // queryUnwindCollectionPaths.filter(a => !a.includes('(Lookup)')).forEach(path => {
664
- // query.push({
665
- // $unwind: {
666
- // path: path,
667
- // preserveNullAndEmptyArrays: true
668
- // }
669
- // });
670
- // });
671
- // queryGroupUnwindCollectionPaths.filter(a => !a.includes('(Lookup)')).forEach(path => {
672
- // query.push({
673
- // $unwind: {
674
- // path: path,
675
- // preserveNullAndEmptyArrays: false
676
- // }
677
- // });
678
- // });
679
- // // Unwind Lookups
680
- // queryUnwindCollectionPaths.filter(a => a.includes('(Lookup)')).forEach(path => {
681
- // if (!query.filter(a => a.$unwind && a.$unwind.path === path).length) {
682
- // query.push({
683
- // $unwind: {
684
- // path: path,
685
- // preserveNullAndEmptyArrays: true
686
- // }
687
- // });
688
- // }
689
- // });
690
- // queryGroupUnwindCollectionPaths.filter(a => a.includes('(Lookup)')).forEach(path => {
691
- // if (!query.filter(a => a.$unwind && a.$unwind.path === path).length) {
692
- // query.push({
693
- // $unwind: {
694
- // path: path,
695
- // preserveNullAndEmptyArrays: false
696
- // }
697
- // });
698
- // }
699
- // });
700
- // // Group Unwinds
701
- // if (groupsRow.length) {
702
- // query = query.concat(queryGroupUnwind.filter(a => !query.some(b => b.$unwind && (b.$unwind.path === a.$unwind.path))));
703
- // }
704
- // // Array and Lookup Filters
705
- // let queryMatchConditionLookup = {
706
- // $and: []
707
- // };
708
- // if (filters.filter(a => (!a['$or'] && Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).length) {
709
- // filters.filter(a => (!a['$or'] && Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).forEach(filter => {
710
- // queryMatchConditionLookup['$and'].push(filter);
711
- // });
712
- // }
713
- // filterArrays.forEach(filter => {
714
- // queryMatchConditionLookup['$and'].push(filter);
715
- // });
716
- // if (queryMatchConditionLookup.$and.some(a => !a['$or'] || (a['$or'] && a['$or'].length)) || queryMatchConditionLookup.$and.length) {
717
- // query.push({
718
- // $match: queryMatchConditionLookup
719
- // });
720
- // }
721
- // // Group Queries and Projection
722
- // if (groupsRow.length) {
723
- // queryGroups.forEach(group => {
724
- // query.push(group);
725
- // });
726
- // if (reportType === 'Tabular Group') {
727
- // let tmpProj = deepCopy(queryGroups[queryGroups.length - 2].$group);
728
- // if (groupsRow.length === 1) {
729
- // tmpProj._id.gr_1 = '$_id.gr_1';
730
- // }
731
- // Object.keys(tmpProj).filter(a => a !== '_id').forEach(key => {
732
- // tmpProj[key] = 1;
733
- // });
734
- // Object.assign(tmpProj, tmpProj['_id']);
735
- // tmpProj['_id'] = 0;
736
- // query.push({
737
- // $project: tmpProj
738
- // });
739
- // }
740
- // }
741
- // else {
742
- // query.push({
743
- // $project: queryProjection
744
- // });
745
- // }
746
- // // Links
747
- // if (fieldsLink.length) {
748
- // if (fieldsLink.length === 1 && fieldsLink[0].field_first && fieldsLink[0].field_second) {
749
- // query.push({$match: {[fieldsLink[0].id]: 0}});
750
- // }
751
- // else {
752
- // let tmpAnds = [];
753
- // fieldsLink.filter(a => a.field_first && a.field_second).forEach(link => {
754
- // tmpAnds.push({[link.id]: 0});
755
- // });
756
- // if (tmpAnds.length) {
757
- // query.push({$match: {$and: tmpAnds}});
758
- // }
759
- // }
760
- // }
761
- // // SORT
434
+ query.push({ $group: queryGroup });
435
+ // SORT
762
436
  if (rootOptions.sort && reportType !== 'Tabular Group') {
763
437
  query.push({
764
438
  $sort: rootOptions.sort
765
439
  });
766
440
  }
767
- // Dated Grouping
768
- // if (date_field && date_interval) {
769
- // if (date_interval === 'Daily') {
770
- // query.push({
771
- // $group: {
772
- // _id: {
773
- // day: '$_id.day',
774
- // month: '$_id.month',
775
- // year: '$_id.year'
776
- // },
777
- // results: {
778
- // '$push': '$$ROOT'
779
- // }
780
- // }
781
- // });
782
- // }
783
- // else if (date_interval === 'Weekly') {
784
- // query.push({
785
- // $group: {
786
- // _id: {
787
- // week: '$_id.week',
788
- // // month: '$_id.month',
789
- // year: '$_id.year'
790
- // },
791
- // results: {
792
- // '$push': '$$ROOT'
793
- // }
794
- // }
795
- // });
796
- // }
797
- // else if (date_interval === 'Monthly') {
798
- // query.push({
799
- // $group: {
800
- // _id: {
801
- // month: '$_id.month',
802
- // year: '$_id.year'
803
- // },
804
- // results: {
805
- // '$push': '$$ROOT'
806
- // }
807
- // }
808
- // });
809
- // }
810
- // else if (date_interval === 'Quarterly') {
811
- // query.push({
812
- // $group: {
813
- // _id: {
814
- // month: '$_id.month',
815
- // year: '$_id.year'
816
- // },
817
- // results: {
818
- // '$push': '$$ROOT'
819
- // }
820
- // }
821
- // });
822
- // }
823
- // else if (date_interval === 'Yearly') {
824
- // query.push({
825
- // $group: {
826
- // _id: {
827
- // year: '$_id.year'
828
- // },
829
- // results: {
830
- // '$push': '$$ROOT'
831
- // }
832
- // }
833
- // });
834
- // }
835
- // }
836
- // GROUP TO GET TOTAL COUNT
837
- query.push({
838
- $group: {
839
- _id: null,
840
- count: { $sum: 1 },
841
- results: { $push: '$$ROOT' }
842
- }
843
- });
844
- if (rootOptions.limit) {
845
- // PROJECT TO SKIP/LIMIT
846
- query.push({
847
- $project: {
848
- count: 1,
849
- results: {
850
- $slice: ['$results', rootOptions.skip, rootOptions.limit]
851
- }
852
- }
853
- });
854
- if (queryTotals !== null) {
855
- query[query.length - 1].$project['totals'] = queryTotals;
856
- }
857
- }
858
- else if (queryTotals !== null) {
859
- query.push({
860
- $project: {
861
- count: 1,
862
- results: 1,
863
- totals: queryTotals
864
- }
865
- });
866
- }
867
441
  console.log('_____________ query __________');
868
442
  console.log(query);
869
443
  console.log(JSON.stringify(query, null, 2));
@@ -880,7 +454,23 @@ function loadReportBuilderMethods(methodManager) {
880
454
  console.log(err_1);
881
455
  return [3 /*break*/, 4];
882
456
  case 4:
883
- resolve(res);
457
+ tmpTotals = {};
458
+ fieldsTotal.forEach(function (totField) {
459
+ selectedFields.filter(function (b) { return b.fieldType === 'Number'; }).forEach(function (selField) {
460
+ if (totField.type === 'sum') {
461
+ tmpTotals[totField.id + '_' + selField.id] = res.map(function (a) { return a[totField.id + '_' + selField.id] || 0; }).reduce(function (a, b) { return a + b; }, 0);
462
+ }
463
+ else if (totField.type === 'avg') {
464
+ tmpTotals[totField.id + '_' + selField.id] = Math.round(res.map(function (a) { return a[totField.id + '_' + selField.id] || 0; }).reduce(function (a, b) { return a + b; }, 0) / res.length);
465
+ }
466
+ });
467
+ });
468
+ tmpRes = [{
469
+ count: res.length,
470
+ results: rootOptions.limit ? res.splice(0, rootOptions.limit) : res,
471
+ totals: tmpTotals
472
+ }];
473
+ resolve(tmpRes);
884
474
  return [2 /*return*/];
885
475
  }
886
476
  });
@@ -890,3 +480,806 @@ function loadReportBuilderMethods(methodManager) {
890
480
  });
891
481
  }
892
482
  exports.loadReportBuilderMethods = loadReportBuilderMethods;
483
+ // let queryGroupUnwindCollectionPaths = [];
484
+ // groupsRow.filter(a => a.treeItem.fieldPath.includes('$')).forEach(field => {
485
+ // let arrayPartData = field.treeItem.fieldPath.split('.$');
486
+ // let path = '$';
487
+ // for (let i = 0; i < arrayPartData.length - 1; i++) {
488
+ // path += arrayPartData[i];
489
+ // if (!queryGroupUnwindCollectionPaths.filter(a => a === path)[0]) {
490
+ // queryGroupUnwindCollectionPaths.push(path);
491
+ // }
492
+ // }
493
+ // });
494
+ // // Unwind
495
+ // let queryUnwindCollectionPaths = [];
496
+ // selectedFields.filter(a => a.fieldPath.includes('$')).forEach(field => {
497
+ // let arrayPartData = field.fieldPath.split('.$');
498
+ // let path = '$';
499
+ // for (let i = 0; i < arrayPartData.length - 1; i++) {
500
+ // path += arrayPartData[i];
501
+ // if (!queryUnwindCollectionPaths.some(a => a === path) && !queryGroupUnwindCollectionPaths.some(a => a === path)) {
502
+ // queryUnwindCollectionPaths.push(path);
503
+ // }
504
+ // }
505
+ // });
506
+ // //Links
507
+ // if (fieldsLink.length) {
508
+ // fieldsLink.filter(a => a.field_first && a.field_second).forEach(link => {
509
+ // queryGroup[link.id] = {$cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')]};
510
+ // });
511
+ // }
512
+ // if (rootOptions.sort && reportType === 'Tabular Group') {
513
+ // let correctSort = {};
514
+ // Object.keys(rootOptions.sort).forEach(key => {
515
+ // correctSort[selectedFields.filter(a => a.id === key)[0].fieldPath.replace(/\.\$/g, '')] = rootOptions.sort[key];
516
+ // });
517
+ // queryGroups.push({
518
+ // $sort: correctSort
519
+ // });
520
+ // }
521
+ /* --------------------- START IF GROUP ---------------------- */
522
+ // Lookups for Groups
523
+ // let groupQueries = [];
524
+ // groupsRow.forEach(row => {
525
+ // if (row.field.includes('$')) {
526
+ // let fieldData = row.field.split('.$');
527
+ // let fieldPath = '';
528
+ // for (let i = 0; i < fieldData.length - 1; i++) {
529
+ // fieldPath += fieldData[i];
530
+ // if (fieldPath.includes('(Lookup)')) {
531
+ // groupQueries.push({$lookup: {
532
+ // from: row.treeItem.lookup_collection,
533
+ // localField: row.treeItem.lookup_local_key,
534
+ // foreignField: row.treeItem.lookup_foreign_key,
535
+ // as: row.treeItem.lookup_as.replace(/\.\$/g, '')
536
+ // }});
537
+ // if (i === 0) {
538
+ // if (fieldsTotal.length) {
539
+ // let addFields = {$addFields: {}};
540
+ // fieldsTotal.forEach(total => {
541
+ // selectedFields.filter(a => !a.fieldPath.include('.$') && a.fieldType === 'Number').forEach(field => {
542
+ // addFields.$addFields[total.id + '_' + field.id] = {
543
+ // $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 }}]}]
544
+ // };
545
+ // });
546
+ // });
547
+ // if (Object.entries(addFields.$addFields).length > 0) {
548
+ // groupQueries.push(addFields);
549
+ // }
550
+ // }
551
+ // }
552
+ // // total_1_f_0: {
553
+ // // $divide: ['$loaded_miles.loaded_miles', {$multiply: [{$size: '$chemicals'}] } ]
554
+ // // },
555
+ // // total_1_f_1: {
556
+ // // $divide: ['$wo_number', {$size: '$chemicals'}]
557
+ // // }
558
+ // // groupQueries.push({'$unwind': {path: '$' + row.treeItem.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true}});
559
+ // }
560
+ // if (i === 0) {
561
+ // if (fieldsTotal.length) {
562
+ // let addFields = {$addFields: {}};
563
+ // fieldsTotal.forEach(total => {
564
+ // selectedFields.filter(a => !a.fieldPath.includes('.$') && a.fieldType === 'Number' && !groupQueries.some(b => b.$addFields && Object.keys(b.$addFields).includes(total.id + '_' + a.id))).forEach(field => {
565
+ // addFields.$addFields[total.id + '_' + field.id] = {
566
+ // $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), {$multiply: [{$cond: { if: { $gt: [{$size: '$' + fieldPath} , 0 ] }, then: {$size: '$' + fieldPath}, else: 1 }}]}]
567
+ // };
568
+ // });
569
+ // });
570
+ // if (Object.entries(addFields.$addFields).length > 0) {
571
+ // groupQueries.push(addFields);
572
+ // }
573
+ // }
574
+ // }
575
+ // groupQueries.push({'$unwind': {path: '$' + fieldPath, preserveNullAndEmptyArrays: true}});
576
+ // if (fieldsTotal.length) {
577
+ // let addFields = {$addFields: {}};
578
+ // fieldsTotal.forEach(total => {
579
+ // selectedFields.filter(a => a.fieldPath.replace(/\.\$/g, '').includes(fieldPath) && a.fieldPath.split('.$').length === 2 && a.fieldType === 'Number').forEach(field => {
580
+ // addFields.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
581
+ // });
582
+ // });
583
+ // if (Object.entries(addFields.$addFields).length > 0) {
584
+ // groupQueries.push(addFields);
585
+ // }
586
+ // }
587
+ // }
588
+ // }
589
+ // });
590
+ // if (!groupsRow.length) {
591
+ // selectedFields.forEach(field => {
592
+ // let fieldData = field.fieldPath.split('.$');
593
+ // let fieldPath = '';
594
+ // for (let i = 0; i < fieldData.length - 1; i++) {
595
+ // fieldPath += fieldData[i];
596
+ // if (fieldPath.includes('(Lookup)')) {
597
+ // groupQueries.push({$lookup: {
598
+ // from: field.lookup_collection,
599
+ // localField: field.lookup_local_key,
600
+ // foreignField: field.lookup_foreign_key,
601
+ // as: field.lookup_as.replace(/\.\$/g, '')
602
+ // }});
603
+ // if (i === 0) {
604
+ // if (fieldsTotal.length) {
605
+ // let addFields = {$addFields: {}};
606
+ // fieldsTotal.forEach(total => {
607
+ // selectedFields.filter(a => !a.fieldPath.include('.$') && a.fieldType === 'Number').forEach(field => {
608
+ // addFields.$addFields[total.id + '_' + field.id] = {
609
+ // $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 }}]}]
610
+ // };
611
+ // });
612
+ // });
613
+ // if (Object.entries(addFields.$addFields).length > 0) {
614
+ // groupQueries.push(addFields);
615
+ // }
616
+ // }
617
+ // }
618
+ // // total_1_f_0: {
619
+ // // $divide: ['$loaded_miles.loaded_miles', {$multiply: [{$size: '$chemicals'}] } ]
620
+ // // },
621
+ // // total_1_f_1: {
622
+ // // $divide: ['$wo_number', {$size: '$chemicals'}]
623
+ // // }
624
+ // // groupQueries.push({'$unwind': {path: '$' + field.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true}});
625
+ // }
626
+ // if (i === 0) {
627
+ // if (fieldsTotal.length) {
628
+ // let addFields = {$addFields: {}};
629
+ // fieldsTotal.forEach(total => {
630
+ // selectedFields.filter(a => !a.fieldPath.includes('.$') && a.fieldType === 'Number' && !groupQueries.some(b => b.$addFields && Object.keys(b.$addFields).includes(total.id + '_' + a.id))).forEach(field => {
631
+ // addFields.$addFields[total.id + '_' + field.id] = {
632
+ // $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), {$multiply: [{$cond: { if: { $gt: [{$size: '$' + fieldPath} , 0 ] }, then: {$size: '$' + fieldPath}, else: 1 }}]}]
633
+ // };
634
+ // });
635
+ // });
636
+ // if (Object.entries(addFields.$addFields).length > 0) {
637
+ // groupQueries.push(addFields);
638
+ // }
639
+ // }
640
+ // }
641
+ // groupQueries.push({'$unwind': {path: '$' + fieldPath, preserveNullAndEmptyArrays: true}});
642
+ // if (fieldsTotal.length) {
643
+ // let addFields = {$addFields: {}};
644
+ // fieldsTotal.forEach(total => {
645
+ // selectedFields.filter(a => a.fieldPath.replace(/\.\$/g, '').includes(fieldPath) && a.fieldPath.split('.$').length === 2 && a.fieldType === 'Number').forEach(field => {
646
+ // addFields.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
647
+ // });
648
+ // });
649
+ // if (Object.entries(addFields.$addFields).length > 0) {
650
+ // groupQueries.push(addFields);
651
+ // }
652
+ // }
653
+ // }
654
+ // });
655
+ // }
656
+ // // Add group lookups and unwinds to query
657
+ // query = query.concat(groupQueries);
658
+ // // GROUP
659
+ // if (groupsRow.length) {
660
+ // let queryGroup = {
661
+ // _id: {}
662
+ // };
663
+ // groupsRow.forEach(row => {
664
+ // queryGroup._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
665
+ // if (date_field && date_interval) {
666
+ // if (date_interval === 'Daily') {
667
+ // queryGroup._id['day'] = {'$dayOfMonth' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
668
+ // queryGroup._id['month'] = {'$month' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
669
+ // queryGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
670
+ // }
671
+ // else if (date_interval === 'Weekly') {
672
+ // queryGroup._id['week'] = {'$week' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
673
+ // // queryGroup._id['month'] = {'$month' : '$' + date_field.replace(/\.\$/g, '')};
674
+ // queryGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
675
+ // }
676
+ // else if (date_interval === 'Monthly') {
677
+ // queryGroup._id['month'] = {'$month' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
678
+ // queryGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
679
+ // }
680
+ // else if (date_interval === 'Quarterly') {
681
+ // queryGroup._id['month'] = {'$month' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
682
+ // queryGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
683
+ // }
684
+ // else if (date_interval === 'Yearly') {
685
+ // queryGroup._id['year'] = {'$year' : {'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': this.serverConfig['TIMEZONE']}};
686
+ // }
687
+ // // queryGroup[date_field.replace(/\.\$/g, '')] = {$first: '$' + date_field.replace(/\.\$/g, '')};
688
+ // }
689
+ // });
690
+ // selectedFields.forEach(field => {
691
+ // if (field.leafValueType === 'Average') {
692
+ // queryGroup[field.id] = {'$avg': '$' + field.fieldPath.replace(/\.\$/g, '')};
693
+ // }
694
+ // else if (field.leafValueType === 'Sum') {
695
+ // queryGroup[field.id] = {'$sum': '$' + field.fieldPath.replace(/\.\$/g, '')};
696
+ // }
697
+ // else if (field.leafValueType === 'Count') {
698
+ // queryGroup[field.id] = {'$sum': 1};
699
+ // }
700
+ // else if (field.leafValueType === 'Minimum') {
701
+ // queryGroup[field.id] = {'$min': '$' + field.fieldPath.replace(/\.\$/g, '')};
702
+ // }
703
+ // else if (field.leafValueType === 'Maximum') {
704
+ // queryGroup[field.id] = {'$max': '$' + field.fieldPath.replace(/\.\$/g, '')};
705
+ // }
706
+ // else if (field.leafValueType === 'First') {
707
+ // queryGroup[field.id] = {'$first': '$' + field.fieldPath.replace(/\.\$/g, '')};
708
+ // }
709
+ // else if (field.leafValueType === 'Last') {
710
+ // queryGroup[field.id] = {'$last': '$' + field.fieldPath.replace(/\.\$/g, '')};
711
+ // }
712
+ // else {
713
+ // queryGroup[field.id] = {'$push': '$' + field.fieldPath.replace(/\.\$/g, '')};
714
+ // }
715
+ // // if (field.fieldPath.includes('.$') && ) {
716
+ // // }
717
+ // });
718
+ // //Totals
719
+ // if (fieldsTotal.length) {
720
+ // fieldsTotal.forEach(total => {
721
+ // selectedFields.filter(a => a.fieldType === 'Number').forEach(field => {
722
+ // queryGroup[total.id + '_' + field.id] = {['$' + total.type]: '$' + total.id + '_' + field.id};
723
+ // });
724
+ // });
725
+ // }
726
+ // // Copy Group Arrays Moving Forward
727
+ // groupsRow.filter(a => a.field.includes('.$')).forEach(row => {
728
+ // queryGroup[row.field.split('.$')[0]] = {$first: '$' + row.field.split('.$')[0]};
729
+ // });
730
+ // selectedFields.filter(a => a.fieldPath.includes('.$')).forEach(field => {
731
+ // if (!queryGroup[field.fieldPath.split('.$')[0]]) {
732
+ // queryGroup[field.fieldPath.split('.$')[0]] = {$push: '$' + field.fieldPath.split('.$')[0]};
733
+ // }
734
+ // });
735
+ // query.push({$group: queryGroup});
736
+ // }
737
+ // else {
738
+ // let queryGroup = {
739
+ // _id: '$_id'
740
+ // };
741
+ // selectedFields.filter(a => !a.fieldPath.includes('.$')).forEach(field => {
742
+ // if (field.leafValueType === 'Average') {
743
+ // queryGroup[field.id] = {'$avg': '$' + field.fieldPath.replace(/\.\$/g, '')};
744
+ // }
745
+ // else if (field.leafValueType === 'Sum') {
746
+ // queryGroup[field.id] = {'$sum': '$' + field.fieldPath.replace(/\.\$/g, '')};
747
+ // }
748
+ // else if (field.leafValueType === 'Count') {
749
+ // queryGroup[field.id] = {'$sum': 1};
750
+ // }
751
+ // else if (field.leafValueType === 'Minimum') {
752
+ // queryGroup[field.id] = {'$min': '$' + field.fieldPath.replace(/\.\$/g, '')};
753
+ // }
754
+ // else if (field.leafValueType === 'Maximum') {
755
+ // queryGroup[field.id] = {'$max': '$' + field.fieldPath.replace(/\.\$/g, '')};
756
+ // }
757
+ // else if (field.leafValueType === 'First') {
758
+ // queryGroup[field.id] = {'$first': '$' + field.fieldPath.replace(/\.\$/g, '')};
759
+ // }
760
+ // else if (field.leafValueType === 'Last') {
761
+ // queryGroup[field.id] = {'$last': '$' + field.fieldPath.replace(/\.\$/g, '')};
762
+ // }
763
+ // else {
764
+ // queryGroup[field.id] = {'$push': '$' + field.fieldPath.replace(/\.\$/g, '')};
765
+ // }
766
+ // });
767
+ // //Totals
768
+ // if (fieldsTotal.length) {
769
+ // fieldsTotal.forEach(total => {
770
+ // selectedFields.filter(a => a.fieldType === 'Number').forEach(field => {
771
+ // queryGroup[total.id + '_' + field.id] = {['$' + total.type]: '$' + total.id + '_' + field.id};
772
+ // });
773
+ // });
774
+ // }
775
+ // // Copy Group Arrays Moving Forward
776
+ // groupsRow.filter(a => a.field.includes('.$')).forEach(row => {
777
+ // queryGroup[row.field.split('.$')[0]] = {$first: '$' + row.field.split('.$')[0]};
778
+ // });
779
+ // selectedFields.filter(a => a.fieldPath.includes('.$')).forEach(field => {
780
+ // if (!queryGroup[field.fieldPath.split('.$')[0]]) {
781
+ // queryGroup[field.fieldPath.split('.$')[0]] = {$push: '$' + field.fieldPath.split('.$')[0]};
782
+ // }
783
+ // });
784
+ // query.push({$group: queryGroup});
785
+ // }
786
+ // /* --------------------- END IF GROUP ---------------------- */
787
+ // // Lookup Selected Fields
788
+ // selectedFields.filter(a => a.fieldPath.includes('.$')).forEach(field => {
789
+ // // Unwind if from group
790
+ // if (groupsRow.length && !groupsRow.some(a => a.field.split('.$')[0] === field.fieldPath.split('.$')[0])) {
791
+ // query.push({$unwind: {
792
+ // path: '$' + field.fieldPath.split('.$')[0],
793
+ // preserveNullAndEmptyArrays: true
794
+ // }});
795
+ // }
796
+ // let path = '$';
797
+ // // Loop for each array value (Not Grouped!)
798
+ // for (let i = 0; i < field.fieldPath.split('.$').length; i++) {
799
+ // path += field.fieldPath.split('.$')[i];
800
+ // // Unwind
801
+ // if (i < field.fieldPath.split('.$').length - 1 && !groupsRow.some(a => a.field.split('.$')[0] === field.fieldPath.split('.$')[0])) {
802
+ // query.push({$unwind: {
803
+ // path: path,
804
+ // preserveNullAndEmptyArrays: true
805
+ // }});
806
+ // }
807
+ // // Link
808
+ // if (!groupsRow.some(a => a.field.split('.$')[0] === field.fieldPath.split('.$')[0])) {
809
+ // fieldsLink.filter(a => a.field_first && a.field_second).forEach(link => {
810
+ // let firstLink = link.field_first.split('.$.');
811
+ // firstLink.pop();
812
+ // firstLink = firstLink.join('.');
813
+ // let secondLink = link.field_second.split('.$.');
814
+ // secondLink.pop();
815
+ // secondLink = secondLink.join('.');
816
+ // if ('$' + firstLink === path || '$' + secondLink === path) {
817
+ // query.push(
818
+ // {
819
+ // $addFields: {
820
+ // [link.id]: {
821
+ // $cmp: [
822
+ // '$' + link.field_first.replace(/\.\$/g, ''),
823
+ // '$' + link.field_second.replace(/\.\$/g, '')
824
+ // ]
825
+ // }
826
+ // }
827
+ // },
828
+ // {
829
+ // $match: {
830
+ // [link.id]: 0
831
+ // }
832
+ // }
833
+ // );
834
+ // }
835
+ // });
836
+ // }
837
+ // //Totals
838
+ // if (i === field.fieldPath.split('.$').length - 1 && field.fieldType === 'Number') {
839
+ // fieldsTotal.forEach(total => {
840
+ // query.push({$addFields: {[total.id + '_' + field.id]: path}});
841
+ // });
842
+ // }
843
+ // }
844
+ // // Regroup
845
+ // let queryLoopGroup = {
846
+ // _id: {}
847
+ // };
848
+ // if (!groupsRow.length) {
849
+ // queryLoopGroup._id = '$_id';
850
+ // }
851
+ // groupsRow.forEach(row => {
852
+ // queryLoopGroup._id[row.id] = '$_id.' + row.id;
853
+ // if (date_field && date_interval) {
854
+ // if (date_interval === 'Daily') {
855
+ // queryLoopGroup._id['day'] = '$_id.day';
856
+ // queryLoopGroup._id['month'] = '$_id.month';
857
+ // queryLoopGroup._id['year'] = '$_id.year';
858
+ // }
859
+ // else if (date_interval === 'Weekly') {
860
+ // queryLoopGroup._id['week'] = '$_id.week';
861
+ // // queryGroup._id['month'] = {'$month' : '$' + date_field.replace(/\.\$/g, '')};
862
+ // queryLoopGroup._id['year'] = '$_id.year';
863
+ // }
864
+ // else if (date_interval === 'Monthly') {
865
+ // queryLoopGroup._id['month'] = '$_id.month';
866
+ // queryLoopGroup._id['year'] = '$_id.year';
867
+ // }
868
+ // else if (date_interval === 'Quarterly') {
869
+ // queryLoopGroup._id['month'] = '$_id.month';
870
+ // queryLoopGroup._id['year'] = '$_id.year';
871
+ // }
872
+ // else if (date_interval === 'Yearly') {
873
+ // queryLoopGroup._id['year'] = '$_id.year';
874
+ // }
875
+ // }
876
+ // });
877
+ // selectedFields.forEach(selField => {
878
+ // if (selField.id === field.id) {
879
+ // if (selField.leafValueType === 'Average') {
880
+ // queryLoopGroup[selField.id] = {'$avg': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, ''))};
881
+ // }
882
+ // else if (selField.leafValueType === 'Sum') {
883
+ // queryLoopGroup[selField.id] = {'$sum': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, ''))};
884
+ // }
885
+ // else if (selField.leafValueType === 'Count') {
886
+ // queryLoopGroup[selField.id] = {'$sum': 1};
887
+ // }
888
+ // else if (selField.leafValueType === 'Minimum') {
889
+ // queryLoopGroup[selField.id] = {'$min': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, ''))};
890
+ // }
891
+ // else if (selField.leafValueType === 'Maximum') {
892
+ // queryLoopGroup[selField.id] = {'$max': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, ''))};
893
+ // }
894
+ // else if (selField.leafValueType === 'First') {
895
+ // queryLoopGroup[selField.id] = {'$first': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, ''))};
896
+ // }
897
+ // else if (selField.leafValueType === 'Last') {
898
+ // queryLoopGroup[selField.id] = {'$last': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, ''))};
899
+ // }
900
+ // else {
901
+ // queryLoopGroup[selField.id] = {'$push': '$' + (selField.collection_name === rootCollectionName ? selField.fieldPath.replace(/\.\$/g, '') : selField.fieldPath.replace(/\.\$/g, ''))};
902
+ // }
903
+ // }
904
+ // else {
905
+ // queryLoopGroup[selField.id] = {'$first': '$' + selField.id};
906
+ // }
907
+ // });
908
+ // //Totals
909
+ // if (fieldsTotal.length) {
910
+ // fieldsTotal.forEach(total => {
911
+ // selectedFields.filter(a => a.fieldType === 'Number').forEach(selField => {
912
+ // if (selField.id === field.id) {
913
+ // queryLoopGroup[total.id + '_' + selField.id] = {['$' + total.type]: '$' + total.id + '_' + selField.id};
914
+ // }
915
+ // else {
916
+ // queryLoopGroup[total.id + '_' + selField.id] = {$first: '$' + total.id + '_' + selField.id};
917
+ // }
918
+ // });
919
+ // });
920
+ // }
921
+ // // Copy Group Arrays Moving Forward
922
+ // groupsRow.filter(a => a.field.includes('.$')).forEach(row => {
923
+ // queryLoopGroup[row.field.split('.$')[0]] = {$first: '$' + row.field.split('.$')[0]};
924
+ // });
925
+ // selectedFields.filter(a => a.fieldPath.includes('.$')).forEach(selField => {
926
+ // if (selField.id === field.id) {
927
+ // if (!queryLoopGroup[selField.fieldPath.split('.$')[0]]) {
928
+ // queryLoopGroup[selField.fieldPath.split('.$')[0]] = {$push: '$' + selField.fieldPath.split('.$')[0]};
929
+ // }
930
+ // }
931
+ // else {
932
+ // if (!queryLoopGroup[selField.fieldPath.split('.$')[0]]) {
933
+ // queryLoopGroup[selField.fieldPath.split('.$')[0]] = {$first: '$' + selField.fieldPath.split('.$')[0]};
934
+ // }
935
+ // }
936
+ // });
937
+ // query.push({$group: queryLoopGroup});
938
+ // // Sort
939
+ // });
940
+ // uniqueSelectedFieldCollections.filter(a => a !== rootCollectionName).forEach(uniqueCollection => {
941
+ // selectedFields.filter(a => a.collection_name === uniqueCollection).forEach(field => {
942
+ // if (!queryLookups.filter(a => a.as === field.lookup_as.replace(/\.\$/g, '')).length) {
943
+ // queryLookups.push({
944
+ // from: field.lookup_collection,
945
+ // localField: field.lookup_local_key,
946
+ // foreignField: field.lookup_foreign_key,
947
+ // as: field.lookup_as.replace(/\.\$/g, '')
948
+ // });
949
+ // }
950
+ // });
951
+ // });
952
+ // let queryGroupUnwindCollectionPaths = [];
953
+ // groupsRow.filter(a => a.treeItem.fieldPath.includes('$')).forEach(field => {
954
+ // let arrayPartData = field.treeItem.fieldPath.split('.$');
955
+ // let path = '$';
956
+ // for (let i = 0; i < arrayPartData.length - 1; i++) {
957
+ // path += arrayPartData[i];
958
+ // if (!queryGroupUnwindCollectionPaths.filter(a => a === path)[0]) {
959
+ // queryGroupUnwindCollectionPaths.push(path);
960
+ // }
961
+ // }
962
+ // });
963
+ // // Unwind
964
+ // let queryUnwindCollectionPaths = [];
965
+ // selectedFields.filter(a => a.fieldPath.includes('$')).forEach(field => {
966
+ // let arrayPartData = field.fieldPath.split('.$');
967
+ // let path = '$';
968
+ // for (let i = 0; i < arrayPartData.length - 1; i++) {
969
+ // path += arrayPartData[i];
970
+ // if (!queryUnwindCollectionPaths.some(a => a === path) && !queryGroupUnwindCollectionPaths.some(a => a === path)) {
971
+ // queryUnwindCollectionPaths.push(path);
972
+ // }
973
+ // }
974
+ // });
975
+ // //Links
976
+ // if (fieldsLink.length) {
977
+ // fieldsLink.filter(a => a.field_first && a.field_second).forEach(link => {
978
+ // queryGroup[link.id] = {$cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')]};
979
+ // });
980
+ // }
981
+ // if (rootOptions.sort && reportType === 'Tabular Group') {
982
+ // let correctSort = {};
983
+ // Object.keys(rootOptions.sort).forEach(key => {
984
+ // correctSort[selectedFields.filter(a => a.id === key)[0].fieldPath.replace(/\.\$/g, '')] = rootOptions.sort[key];
985
+ // });
986
+ // queryGroups.push({
987
+ // $sort: correctSort
988
+ // });
989
+ // }
990
+ // queryGroups.push({$group: queryGroup});
991
+ // if (reportType === 'Tabular Group') {
992
+ // for (let i = groupsRow.length - 1; i > 0; i--) {
993
+ // queryGroups.push({$sort: {['_id.' + groupsRow[i].id]: 1}});
994
+ // let tmpQueryGroup = {
995
+ // _id: {}
996
+ // };
997
+ // for (let j = 0; j < i; j++) {
998
+ // tmpQueryGroup._id[groupsRow[j].id] = '$_id.' + groupsRow[j].id;
999
+ // }
1000
+ // let tmpQueryGroupObj = {
1001
+ // [groupsRow[i].id]: '$_id.' + [groupsRow[i].id]
1002
+ // };
1003
+ // if (i === groupsRow.length - 1) {
1004
+ // selectedFields.forEach(field => {
1005
+ // tmpQueryGroupObj[field.id] = '$' + field.id;
1006
+ // });
1007
+ // }
1008
+ // else {
1009
+ // tmpQueryGroupObj[groupsRow[i + 1].id] = '$' + [groupsRow[i + 1].id];
1010
+ // }
1011
+ // fieldsTotal.forEach(total => {
1012
+ // selectedFields.filter(a => a.fieldType === 'Number').forEach(field => {
1013
+ // tmpQueryGroupObj[total.id + '_' + field.id] = '$' + total.id + '_' + field.id;
1014
+ // tmpQueryGroup[total.id + '_' + field.id] = {['$' + total.type]: '$' + total.id + '_' + field.id};
1015
+ // });
1016
+ // });
1017
+ // tmpQueryGroup[groupsRow[i].id] = {'$push': tmpQueryGroupObj};
1018
+ // queryGroups.push({$group: tmpQueryGroup});
1019
+ // }
1020
+ // queryGroups.push({$sort: {['_id.' + groupsRow[0].id]: 1}});
1021
+ // }
1022
+ // else if (reportType === 'Dated') {
1023
+ // // db.collection.aggregate([
1024
+ // // { "$group": {
1025
+ // // "_id": {
1026
+ // // "$toDate": {
1027
+ // // "$subtract": [
1028
+ // // { "$toLong": "$created_at" },
1029
+ // // { "$mod": [ { "$toLong": "$created_at" }, 1000 * 60 * 15 ] }
1030
+ // // ]
1031
+ // // }
1032
+ // // },
1033
+ // // "count": { "$sum": 1 }
1034
+ // // }}
1035
+ // // ])
1036
+ // }
1037
+ // }
1038
+ // //Projection
1039
+ // let queryProjection = {
1040
+ // _id: 1
1041
+ // };
1042
+ // selectedFields.forEach(field => {
1043
+ // if (field.leafValueType === 'Average') {
1044
+ // queryProjection[field.id] = {$avg: '$' + field.fieldPath.replace(/\.\$/g, '')};
1045
+ // }
1046
+ // else if (field.leafValueType === 'Sum') {
1047
+ // queryProjection[field.id] = {$sum: '$' + field.fieldPath.replace(/\.\$/g, '')};
1048
+ // }
1049
+ // else if (field.leafValueType === 'Count') {
1050
+ // queryProjection[field.id] = {$sum: 1};
1051
+ // }
1052
+ // else if (field.leafValueType === 'Minimum') {
1053
+ // queryProjection[field.id] = {$min: '$' + field.fieldPath.replace(/\.\$/g, '')};
1054
+ // }
1055
+ // else if (field.leafValueType === 'Maximum') {
1056
+ // queryProjection[field.id] = {$max: '$' + field.fieldPath.replace(/\.\$/g, '')};
1057
+ // }
1058
+ // else if (field.leafValueType === 'First') {
1059
+ // queryProjection[field.id] = {$slice: ['$' + field.fieldPath.replace(/\.\$/g, ''), 0]};
1060
+ // }
1061
+ // else if (field.leafValueType === 'Last') {
1062
+ // queryProjection[field.id] = {$slice: ['$' + field.fieldPath.replace(/\.\$/g, ''), -1]};
1063
+ // }
1064
+ // else {
1065
+ // queryProjection[field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
1066
+ // }
1067
+ // });
1068
+ // //Links
1069
+ // if (fieldsLink.length) {
1070
+ // fieldsLink.filter(a => a.field_first && a.field_second).forEach(link => {
1071
+ // queryProjection[link.id] = {$cmp: ['$' + link.field_first.replace(/\.\$/g, ''), '$' + link.field_second.replace(/\.\$/g, '')]};
1072
+ // });
1073
+ // }
1074
+ // //Totals
1075
+ // let queryTotals = null;
1076
+ // if (fieldsTotal.length && (reportType === 'Tabular' || reportType === 'Dated')) {
1077
+ // fieldsTotal.forEach(total => {
1078
+ // selectedFields.filter(a => a.fieldType === 'Number').forEach(field => {
1079
+ // if (!queryTotals) {
1080
+ // queryTotals = {};
1081
+ // }
1082
+ // queryTotals[total.id + '_' + field.id] = {['$' + total.type]: '$results.' + total.id + '_' + field.id};
1083
+ // });
1084
+ // });
1085
+ // }
1086
+ // // ---------------------------------------------------------------
1087
+ // // Unwind Pre-Lookup Arrays
1088
+ // queryUnwindCollectionPaths.filter(a => !a.includes('(Lookup)')).forEach(path => {
1089
+ // query.push({
1090
+ // $unwind: {
1091
+ // path: path,
1092
+ // preserveNullAndEmptyArrays: true
1093
+ // }
1094
+ // });
1095
+ // });
1096
+ // queryGroupUnwindCollectionPaths.filter(a => !a.includes('(Lookup)')).forEach(path => {
1097
+ // query.push({
1098
+ // $unwind: {
1099
+ // path: path,
1100
+ // preserveNullAndEmptyArrays: false
1101
+ // }
1102
+ // });
1103
+ // });
1104
+ // // Unwind Lookups
1105
+ // queryUnwindCollectionPaths.filter(a => a.includes('(Lookup)')).forEach(path => {
1106
+ // if (!query.filter(a => a.$unwind && a.$unwind.path === path).length) {
1107
+ // query.push({
1108
+ // $unwind: {
1109
+ // path: path,
1110
+ // preserveNullAndEmptyArrays: true
1111
+ // }
1112
+ // });
1113
+ // }
1114
+ // });
1115
+ // queryGroupUnwindCollectionPaths.filter(a => a.includes('(Lookup)')).forEach(path => {
1116
+ // if (!query.filter(a => a.$unwind && a.$unwind.path === path).length) {
1117
+ // query.push({
1118
+ // $unwind: {
1119
+ // path: path,
1120
+ // preserveNullAndEmptyArrays: false
1121
+ // }
1122
+ // });
1123
+ // }
1124
+ // });
1125
+ // // Group Unwinds
1126
+ // if (groupsRow.length) {
1127
+ // query = query.concat(queryGroupUnwind.filter(a => !query.some(b => b.$unwind && (b.$unwind.path === a.$unwind.path))));
1128
+ // }
1129
+ // // Array and Lookup Filters
1130
+ // let queryMatchConditionLookup = {
1131
+ // $and: []
1132
+ // };
1133
+ // if (filters.filter(a => (!a['$or'] && Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).length) {
1134
+ // filters.filter(a => (!a['$or'] && Object.keys(a).some(b => b.includes('(Lookup)'))) || (a['$or'] && a['$or'].some(b => Object.keys(b).some(c => c.includes('(Lookup)'))))).forEach(filter => {
1135
+ // queryMatchConditionLookup['$and'].push(filter);
1136
+ // });
1137
+ // }
1138
+ // filterArrays.forEach(filter => {
1139
+ // queryMatchConditionLookup['$and'].push(filter);
1140
+ // });
1141
+ // if (queryMatchConditionLookup.$and.some(a => !a['$or'] || (a['$or'] && a['$or'].length)) || queryMatchConditionLookup.$and.length) {
1142
+ // query.push({
1143
+ // $match: queryMatchConditionLookup
1144
+ // });
1145
+ // }
1146
+ // // Group Queries and Projection
1147
+ // if (groupsRow.length) {
1148
+ // queryGroups.forEach(group => {
1149
+ // query.push(group);
1150
+ // });
1151
+ // if (reportType === 'Tabular Group') {
1152
+ // let tmpProj = deepCopy(queryGroups[queryGroups.length - 2].$group);
1153
+ // if (groupsRow.length === 1) {
1154
+ // tmpProj._id.gr_1 = '$_id.gr_1';
1155
+ // }
1156
+ // Object.keys(tmpProj).filter(a => a !== '_id').forEach(key => {
1157
+ // tmpProj[key] = 1;
1158
+ // });
1159
+ // Object.assign(tmpProj, tmpProj['_id']);
1160
+ // tmpProj['_id'] = 0;
1161
+ // query.push({
1162
+ // $project: tmpProj
1163
+ // });
1164
+ // }
1165
+ // }
1166
+ // else {
1167
+ // query.push({
1168
+ // $project: queryProjection
1169
+ // });
1170
+ // }
1171
+ // // Links
1172
+ // if (fieldsLink.length) {
1173
+ // if (fieldsLink.length === 1 && fieldsLink[0].field_first && fieldsLink[0].field_second) {
1174
+ // query.push({$match: {[fieldsLink[0].id]: 0}});
1175
+ // }
1176
+ // else {
1177
+ // let tmpAnds = [];
1178
+ // fieldsLink.filter(a => a.field_first && a.field_second).forEach(link => {
1179
+ // tmpAnds.push({[link.id]: 0});
1180
+ // });
1181
+ // if (tmpAnds.length) {
1182
+ // query.push({$match: {$and: tmpAnds}});
1183
+ // }
1184
+ // }
1185
+ // }
1186
+ // Dated Grouping
1187
+ // if (date_field && date_interval) {
1188
+ // if (date_interval === 'Daily') {
1189
+ // query.push({
1190
+ // $group: {
1191
+ // _id: {
1192
+ // day: '$_id.day',
1193
+ // month: '$_id.month',
1194
+ // year: '$_id.year'
1195
+ // },
1196
+ // results: {
1197
+ // '$push': '$$ROOT'
1198
+ // }
1199
+ // }
1200
+ // });
1201
+ // }
1202
+ // else if (date_interval === 'Weekly') {
1203
+ // query.push({
1204
+ // $group: {
1205
+ // _id: {
1206
+ // week: '$_id.week',
1207
+ // // month: '$_id.month',
1208
+ // year: '$_id.year'
1209
+ // },
1210
+ // results: {
1211
+ // '$push': '$$ROOT'
1212
+ // }
1213
+ // }
1214
+ // });
1215
+ // }
1216
+ // else if (date_interval === 'Monthly') {
1217
+ // query.push({
1218
+ // $group: {
1219
+ // _id: {
1220
+ // month: '$_id.month',
1221
+ // year: '$_id.year'
1222
+ // },
1223
+ // results: {
1224
+ // '$push': '$$ROOT'
1225
+ // }
1226
+ // }
1227
+ // });
1228
+ // }
1229
+ // else if (date_interval === 'Quarterly') {
1230
+ // query.push({
1231
+ // $group: {
1232
+ // _id: {
1233
+ // month: '$_id.month',
1234
+ // year: '$_id.year'
1235
+ // },
1236
+ // results: {
1237
+ // '$push': '$$ROOT'
1238
+ // }
1239
+ // }
1240
+ // });
1241
+ // }
1242
+ // else if (date_interval === 'Yearly') {
1243
+ // query.push({
1244
+ // $group: {
1245
+ // _id: {
1246
+ // year: '$_id.year'
1247
+ // },
1248
+ // results: {
1249
+ // '$push': '$$ROOT'
1250
+ // }
1251
+ // }
1252
+ // });
1253
+ // }
1254
+ // }
1255
+ // GROUP TO GET TOTAL COUNT
1256
+ // query.push({
1257
+ // $group: {
1258
+ // _id: null,
1259
+ // count: {$sum: 1},
1260
+ // results: {$push: '$$ROOT'}
1261
+ // }
1262
+ // });
1263
+ // if (rootOptions.limit) {
1264
+ // // PROJECT TO SKIP/LIMIT
1265
+ // query.push({
1266
+ // $project: {
1267
+ // count: 1,
1268
+ // results: {
1269
+ // $slice: ['$results', rootOptions.skip, rootOptions.limit]
1270
+ // }
1271
+ // }
1272
+ // });
1273
+ // if (queryTotals !== null) {
1274
+ // query[query.length - 1].$project['totals'] = queryTotals;
1275
+ // }
1276
+ // }
1277
+ // else if (queryTotals !== null) {
1278
+ // query.push({
1279
+ // $project: {
1280
+ // count: 1,
1281
+ // results: 1,
1282
+ // totals: queryTotals
1283
+ // }
1284
+ // });
1285
+ // }