@resolveio/server-lib 20.12.47 → 20.12.49

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.
@@ -46,15 +46,51 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
46
46
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
47
  }
48
48
  };
49
+ var __read = (this && this.__read) || function (o, n) {
50
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
51
+ if (!m) return o;
52
+ var i = m.call(o), r, ar = [], e;
53
+ try {
54
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
+ }
56
+ catch (error) { e = { error: error }; }
57
+ finally {
58
+ try {
59
+ if (r && !r.done && (m = i["return"])) m.call(i);
60
+ }
61
+ finally { if (e) throw e.error; }
62
+ }
63
+ return ar;
64
+ };
65
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
66
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
67
+ if (ar || !(i in from)) {
68
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
69
+ ar[i] = from[i];
70
+ }
71
+ }
72
+ return to.concat(ar || Array.prototype.slice.call(from));
73
+ };
49
74
  Object.defineProperty(exports, "__esModule", { value: true });
50
75
  exports.loadReportBuilderMethods = loadReportBuilderMethods;
51
76
  var simpl_schema_1 = require("simpl-schema");
77
+ var report_builder_report_collection_1 = require("../collections/report-builder-report.collection");
52
78
  var pagination_model_1 = require("../models/pagination.model");
53
79
  var resolveio_server_app_1 = require("../resolveio-server-app");
54
80
  var common_1 = require("../util/common");
55
81
  var schema_report_builder_1 = require("../util/schema-report-builder");
56
82
  function loadReportBuilderMethods(methodManager) {
57
83
  methodManager.methods({
84
+ reportbuilderreportWithId: {
85
+ check: new simpl_schema_1.default({
86
+ id: {
87
+ type: String
88
+ }
89
+ }),
90
+ function: function (id) {
91
+ return report_builder_report_collection_1.ReportBuilderReports.findOne({ _id: id });
92
+ }
93
+ },
58
94
  reportBuilderBuildTree: {
59
95
  check: new simpl_schema_1.default({
60
96
  collection_root: {
@@ -127,13 +163,15 @@ function loadReportBuilderMethods(methodManager) {
127
163
  }),
128
164
  function: function (treeLeaf) {
129
165
  return __awaiter(this, void 0, void 0, function () {
166
+ var fieldPath;
130
167
  return __generator(this, function (_a) {
131
168
  if (treeLeaf.fieldType === 'String') {
132
- if (treeLeaf.fieldPath.includes('(Lookup') || treeLeaf.lookup_collection) {
133
- return [2 /*return*/, (0, schema_report_builder_1.mongoCommand)('distinct', treeLeaf.collection_name, treeLeaf.fieldPath.replace(/^.+\(.+\) \(Lookup.*\)\.\$\./g, '').replace(/\.\$/g, ''))];
169
+ fieldPath = (treeLeaf && typeof treeLeaf.fieldPath === 'string') ? treeLeaf.fieldPath : '';
170
+ if (fieldPath.includes('(Lookup') || treeLeaf.lookup_collection) {
171
+ return [2 /*return*/, (0, schema_report_builder_1.mongoCommand)('distinct', treeLeaf.collection_name, fieldPath.replace(/^.+\(.+\) \(Lookup.*\)\.\$\./g, '').replace(/\.\$/g, ''))];
134
172
  }
135
173
  else {
136
- return [2 /*return*/, (0, schema_report_builder_1.mongoCommand)('distinct', treeLeaf.collection_name, treeLeaf.fieldPath.replace(/\.\$/g, ''))];
174
+ return [2 /*return*/, (0, schema_report_builder_1.mongoCommand)('distinct', treeLeaf.collection_name, fieldPath.replace(/\.\$/g, ''))];
137
175
  }
138
176
  }
139
177
  else {
@@ -145,6 +183,7 @@ function loadReportBuilderMethods(methodManager) {
145
183
  }
146
184
  },
147
185
  reportBuilderGetResults: {
186
+ bypassSession: true,
148
187
  check: new simpl_schema_1.default({
149
188
  reportType: {
150
189
  type: String
@@ -236,7 +275,7 @@ function loadReportBuilderMethods(methodManager) {
236
275
  }),
237
276
  function: function (reportType_1, rootCollectionName_1, rootOptions_1) {
238
277
  return __awaiter(this, arguments, void 0, function (reportType, rootCollectionName, rootOptions, filters, filterArrays, filterArrayFields, selectedFields, customFields, groupsRow, fieldsTotal, fieldsLink, date_field, date_interval, displayType) {
239
- var modelCollection, lookupAliases, _a, rootFilters, lookupFilters, query_1, initialQueryMatchCondition_1, sizes_1, divFields_1, queryMatchConditionLookup_1, queryGroup_1, groupedSorts_1, queryProjection_1, _loop_1, i, res_1, err_1, tmpTotals_1, tmpRes;
278
+ var modelCollection, lookupAliases, _a, rootFilters_1, lookupFilters_1, additionalCollectionsMap_1, additionalCollections, unionQuery_1, _b, sortToUse, layoutSortAdd, remappedFilters, remappedArrayFilters, postMatchAnd, res_1, err_1, tmpTotals_1, resultsOut, tmpRes_1, query_1, initialQueryMatchCondition_1, sizes_1, divFields_1, queryMatchConditionLookup_1, queryGroup_1, groupedSorts_1, dateFieldPath, queryProjection_1, _loop_1, i, res_2, err_2, tmpTotals_2, tmpRes;
240
279
  if (filters === void 0) { filters = []; }
241
280
  if (filterArrays === void 0) { filterArrays = []; }
242
281
  if (filterArrayFields === void 0) { filterArrayFields = []; }
@@ -248,8 +287,8 @@ function loadReportBuilderMethods(methodManager) {
248
287
  if (date_field === void 0) { date_field = ''; }
249
288
  if (date_interval === void 0) { date_interval = ''; }
250
289
  if (displayType === void 0) { displayType = ''; }
251
- return __generator(this, function (_b) {
252
- switch (_b.label) {
290
+ return __generator(this, function (_c) {
291
+ switch (_c.label) {
253
292
  case 0:
254
293
  modelCollection = resolveio_server_app_1.ResolveIOServer.getMongoManager().collection(rootCollectionName);
255
294
  if (!!modelCollection) return [3 /*break*/, 1];
@@ -258,7 +297,98 @@ function loadReportBuilderMethods(methodManager) {
258
297
  filters = expandLayoutColumnFilters(filters, selectedFields);
259
298
  filterArrays = expandLayoutColumnFilters(filterArrays, selectedFields);
260
299
  lookupAliases = collectLookupAliases(selectedFields, filterArrayFields, groupsRow);
261
- _a = splitFiltersByLookup(filters, lookupAliases), rootFilters = _a.rootFilters, lookupFilters = _a.lookupFilters;
300
+ _a = splitFiltersByLookup(filters, lookupAliases), rootFilters_1 = _a.rootFilters, lookupFilters_1 = _a.lookupFilters;
301
+ additionalCollectionsMap_1 = new Map();
302
+ (selectedFields || [])
303
+ .filter(function (f) { return f && f.lookup_collection; })
304
+ .forEach(function (f) {
305
+ var alias = f.lookup_as || f.lookup_collection;
306
+ var key = "".concat(f.lookup_collection, "::").concat(alias);
307
+ if (!additionalCollectionsMap_1.has(key)) {
308
+ additionalCollectionsMap_1.set(key, { collection: f.lookup_collection, alias: alias });
309
+ }
310
+ });
311
+ additionalCollections = Array.from(additionalCollectionsMap_1.values());
312
+ if (!additionalCollections.length) return [3 /*break*/, 6];
313
+ unionQuery_1 = buildCollectionPipeline(rootCollectionName, '', selectedFields, filters.concat(rootFilters_1 || []), filterArrays.concat(lookupFilters_1 || []), true);
314
+ additionalCollections.forEach(function (cfg) {
315
+ unionQuery_1.push({
316
+ $unionWith: {
317
+ coll: cfg.collection,
318
+ pipeline: buildCollectionPipeline(cfg.collection, cfg.alias, selectedFields, filters.concat(rootFilters_1 || []), filterArrays.concat(lookupFilters_1 || []), false)
319
+ }
320
+ });
321
+ });
322
+ if (rootOptions.sort) {
323
+ _b = buildLayoutSortSpec(rootOptions.sort, selectedFields), sortToUse = _b.sortSpec, layoutSortAdd = _b.addFields;
324
+ if (Object.keys(layoutSortAdd).length) {
325
+ unionQuery_1.push({ $addFields: layoutSortAdd });
326
+ }
327
+ appendSafeSort(unionQuery_1, sortToUse, selectedFields, customFields);
328
+ }
329
+ remappedFilters = remapFiltersToIds(filters.concat(rootFilters_1 || []), selectedFields);
330
+ remappedArrayFilters = remapFiltersToIds(filterArrays.concat(lookupFilters_1 || []), selectedFields);
331
+ postMatchAnd = [];
332
+ if (remappedFilters.length) {
333
+ postMatchAnd.push.apply(postMatchAnd, __spreadArray([], __read(remappedFilters), false));
334
+ }
335
+ if (remappedArrayFilters.length) {
336
+ postMatchAnd.push.apply(postMatchAnd, __spreadArray([], __read(remappedArrayFilters), false));
337
+ }
338
+ if (postMatchAnd.length) {
339
+ unionQuery_1.push({ $match: { $and: postMatchAnd } });
340
+ }
341
+ res_1 = null;
342
+ _c.label = 2;
343
+ case 2:
344
+ _c.trys.push([2, 4, , 5]);
345
+ return [4 /*yield*/, modelCollection.aggregate(unionQuery_1, { allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary' }, true)];
346
+ case 3:
347
+ res_1 = _c.sent();
348
+ return [3 /*break*/, 5];
349
+ case 4:
350
+ err_1 = _c.sent();
351
+ console.log(err_1);
352
+ return [3 /*break*/, 5];
353
+ case 5:
354
+ tmpTotals_1 = {};
355
+ if (res_1) {
356
+ fieldsTotal.forEach(function (totField) {
357
+ selectedFields.filter(function (b) { return b.fieldType === 'Number' || b.leafValueType === 'Count'; }).forEach(function (selField) {
358
+ var sum = res_1.map(function (a) {
359
+ var raw = a ? a[selField.id] : null;
360
+ if (Array.isArray(raw)) {
361
+ return raw
362
+ .map(function (v) { return (typeof v === 'number' ? v : Number(v)); })
363
+ .filter(function (v) { return !isNaN(v); })
364
+ .reduce(function (x, y) { return x + y; }, 0);
365
+ }
366
+ var num = typeof raw === 'number' ? raw : (raw !== null && raw !== undefined ? Number(raw) : 0);
367
+ return isNaN(num) ? 0 : num;
368
+ }).reduce(function (a, b) { return a + b; }, 0);
369
+ if (totField.type === 'sum') {
370
+ tmpTotals_1[totField.id + '_' + selField.id] = sum;
371
+ }
372
+ else if (totField.type === 'avg') {
373
+ tmpTotals_1[totField.id + '_' + selField.id] = res_1.length ? (0, common_1.round)(sum / res_1.length) : 0;
374
+ }
375
+ });
376
+ });
377
+ }
378
+ resultsOut = res_1 || [];
379
+ if (rootOptions.skip) {
380
+ resultsOut = resultsOut.slice(rootOptions.skip);
381
+ }
382
+ if (rootOptions.limit) {
383
+ resultsOut = resultsOut.slice(0, rootOptions.limit);
384
+ }
385
+ tmpRes_1 = [{
386
+ count: res_1 ? res_1.length : 0,
387
+ results: resultsOut,
388
+ totals: tmpTotals_1
389
+ }];
390
+ return [2 /*return*/, tmpRes_1];
391
+ case 6:
262
392
  query_1 = [];
263
393
  initialQueryMatchCondition_1 = {
264
394
  $and: []
@@ -272,8 +402,8 @@ function loadReportBuilderMethods(methodManager) {
272
402
  // ]
273
403
  // });
274
404
  // });
275
- if (rootFilters.length) {
276
- rootFilters.forEach(function (filter) { return initialQueryMatchCondition_1['$and'].push(filter); });
405
+ if (rootFilters_1.length) {
406
+ rootFilters_1.forEach(function (filter) { return initialQueryMatchCondition_1['$and'].push(filter); });
277
407
  }
278
408
  // Add filter to query
279
409
  // 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 || selectedFields.filter(a => !a.fieldPath.includes('(Lookup')).length) {
@@ -301,104 +431,78 @@ function loadReportBuilderMethods(methodManager) {
301
431
  } });
302
432
  sizes_1.push(filterField.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
303
433
  query_1.push({ $addFields: (_a = {}, _a['size_' + filterField.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + filterField.lookup_as.replace(/\.\$/g, '').replace(/\./g, '_'), []] } }, _a) });
304
- query_1.push({ '$unwind': { path: '$' + filterField.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
434
+ var unwindPath = '$' + filterField.lookup_as.replace(/\.\$/g, '');
435
+ query_1.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
305
436
  }
306
437
  }
307
438
  else {
308
439
  if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath.replace(/\./g, '_')); })) {
309
440
  sizes_1.push(fieldPath.replace(/\./g, '_'));
310
441
  query_1.push({ $addFields: (_b = {}, _b['size_' + fieldPath.replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath, []] } }, _b) });
311
- query_1.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
442
+ var unwindPath = '$' + fieldPath;
443
+ query_1.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
312
444
  }
313
445
  }
314
446
  }
315
447
  });
316
448
  // Groups - Lookups / Sizes / Unwinds
317
449
  groupsRow.forEach(function (row) {
318
- var _a, _b;
319
- var _c;
320
- if (row.field.includes('$')) {
321
- var fieldData = row.field.split('.$');
450
+ var _a, _b, _c;
451
+ var rowField = (row && typeof row.field === 'string') ? row.field : '';
452
+ if (rowField.includes('$')) {
453
+ var fieldData = rowField.split('.$');
322
454
  var fieldPath_1 = '';
323
- for (var i = 0; i < fieldData.length - 1; i++) {
455
+ var _loop_2 = function (i) {
456
+ var _d, _e;
324
457
  fieldPath_1 += fieldData[i];
325
- if (((_c = row.treeItem) === null || _c === void 0 ? void 0 : _c.lookup_collection) || fieldPath_1.split('.$')[fieldPath_1.split('.$').length - 1].includes('(Lookup')) {
326
- if (!query_1.some(function (a) { return a.$lookup && a.$lookup.as === row.treeItem.lookup_as.replace(/\.\$/g, ''); })) {
458
+ var lastSegment = fieldPath_1.split('.$')[fieldPath_1.split('.$').length - 1];
459
+ var hasLookup = !!((_a = row.treeItem) === null || _a === void 0 ? void 0 : _a.lookup_collection) || (lastSegment || '').includes('(Lookup');
460
+ if (hasLookup && ((_b = row.treeItem) === null || _b === void 0 ? void 0 : _b.lookup_collection) && ((_c = row.treeItem) === null || _c === void 0 ? void 0 : _c.lookup_as)) {
461
+ var lookupAsRaw = row.treeItem.lookup_as || '';
462
+ var lookupAs_1 = lookupAsRaw.replace(/\.\$/g, '');
463
+ if (!query_1.some(function (a) { return a.$lookup && a.$lookup.as === lookupAs_1; })) {
327
464
  query_1.push({ $lookup: {
328
465
  from: row.treeItem.lookup_collection,
329
- localField: normalizeLookupField(row.treeItem.lookup_local_key),
330
- foreignField: normalizeLookupField(row.treeItem.lookup_foreign_key),
331
- as: row.treeItem.lookup_as.replace(/\.\$/g, '')
466
+ localField: normalizeLookupField(row.treeItem.lookup_local_key || ''),
467
+ foreignField: normalizeLookupField(row.treeItem.lookup_foreign_key || ''),
468
+ as: lookupAs_1
332
469
  } });
333
- sizes_1.push(row.treeItem.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
334
- query_1.push({ $addFields: (_a = {}, _a['size_' + row.treeItem.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + row.treeItem.lookup_as.replace(/\.\$/g, '').replace(/\./g, '_'), []] } }, _a) });
335
- query_1.push({ '$unwind': { path: '$' + row.treeItem.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
470
+ sizes_1.push(lookupAsRaw.replace(/\.\$\./g, '_').replace(/\./g, '_'));
471
+ query_1.push({ $addFields: (_d = {}, _d['size_' + lookupAsRaw.replace(/\.\$\./g, '_').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + lookupAs_1.replace(/\./g, '_'), []] } }, _d) });
472
+ var unwindPath = '$' + lookupAs_1;
473
+ query_1.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
336
474
  }
337
475
  }
338
476
  else {
339
477
  if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath_1.replace(/\.\$\./g, '.').replace(/\./g, '_')); })) {
340
478
  sizes_1.push(fieldPath_1.replace(/\.\$\./g, '.').replace(/\./g, '_'));
341
- query_1.push({ $addFields: (_b = {}, _b['size_' + fieldPath_1.replace(/\.\$\./g, '.').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath_1.replace(/\.\$\./g, '.'), []] } }, _b) });
342
- query_1.push({ '$unwind': { path: '$' + fieldPath_1.replace(/\.\$\./g, '.'), preserveNullAndEmptyArrays: true } });
479
+ query_1.push({ $addFields: (_e = {}, _e['size_' + fieldPath_1.replace(/\.\$\./g, '.').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath_1.replace(/\.\$\./g, '.'), []] } }, _e) });
480
+ var unwindPath = '$' + fieldPath_1.replace(/\.\$\./g, '.');
481
+ query_1.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
343
482
  }
344
483
  }
345
484
  fieldPath_1 += '.$';
346
- }
347
- }
348
- });
349
- // Selected Fields - Lookups / Sizes / Unwinds
350
- selectedFields.forEach(function (field) {
351
- var _a, _b, _c;
352
- if (field.fieldPath.includes('$')) {
353
- var fieldData = field.fieldPath.split('.$');
354
- var fieldPath_2 = '';
485
+ };
355
486
  for (var i = 0; i < fieldData.length - 1; i++) {
356
- fieldPath_2 += fieldData[i];
357
- if (field.lookup_collection || fieldPath_2.split('.$')[fieldPath_2.split('.$').length - 1].includes('(Lookup')) {
358
- if (!query_1.some(function (a) { return a.$lookup && a.$lookup.as === field.lookup_as.replace(/\.\$/g, ''); })) {
359
- query_1.push({ $lookup: {
360
- from: field.lookup_collection,
361
- localField: normalizeLookupField(field.lookup_local_key),
362
- foreignField: normalizeLookupField(field.lookup_foreign_key),
363
- as: field.lookup_as.replace(/\.\$/g, '')
364
- } });
365
- sizes_1.push(field.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
366
- query_1.push({ $addFields: (_a = {}, _a['size_' + field.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + field.lookup_as.replace(/\.\$/g, '').replace(/\./g, '_'), []] } }, _a) });
367
- query_1.push({ '$unwind': { path: '$' + field.lookup_as.replace(/\.\$/g, ''), preserveNullAndEmptyArrays: true } });
368
- }
369
- else {
370
- if (!fieldData[i].includes('(Lookup')) {
371
- if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath_2.replace(/\./g, '_')); })) {
372
- sizes_1.push(fieldPath_2.replace(/\./g, '_'));
373
- query_1.push({ $addFields: (_b = {}, _b['size_' + fieldPath_2.replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath_2, []] } }, _b) });
374
- query_1.push({ '$unwind': { path: '$' + fieldPath_2, preserveNullAndEmptyArrays: true } });
375
- }
376
- }
377
- }
378
- }
379
- else {
380
- if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath_2.replace(/\./g, '_')); })) {
381
- sizes_1.push(fieldPath_2.replace(/\./g, '_'));
382
- query_1.push({ $addFields: (_c = {}, _c['size_' + fieldPath_2.replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath_2, []] } }, _c) });
383
- }
384
- if (field.leafValueType !== 'Count' && !query_1.some(function (a) { return a.$unwind && a.$unwind.path === '$' + fieldPath_2; })) {
385
- query_1.push({ '$unwind': { path: '$' + fieldPath_2, preserveNullAndEmptyArrays: true } });
386
- }
387
- }
487
+ _loop_2(i);
388
488
  }
389
489
  }
390
490
  });
391
491
  divFields_1 = { $addFields: {} };
392
492
  fieldsTotal.filter(function (a) { return a.type === 'sum'; }).forEach(function (total) {
393
493
  selectedFields.filter(function (a) { return a.fieldType === 'Number' || a.leafValueType === 'Count'; }).forEach(function (field) {
494
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
495
+ if (!fieldPath && field.leafValueType !== 'Count') {
496
+ return;
497
+ }
394
498
  var multFields = [];
395
- if (!field.fieldPath.includes('.$')) {
499
+ if (!fieldPath.includes('.$')) {
396
500
  sizes_1.forEach(function (size) {
397
501
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
398
502
  });
399
503
  }
400
504
  else {
401
- sizes_1.filter(function (a) { return !field.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !filterArrayFields.filter(function (a) { return a.fieldPath; }).some(function (b) { return b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }); }).forEach(function (size) {
505
+ sizes_1.filter(function (a) { return !fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !filterArrayFields.filter(function (a) { return a.fieldPath; }).some(function (b) { return b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }); }).forEach(function (size) {
402
506
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
403
507
  });
404
508
  }
@@ -410,7 +514,7 @@ function loadReportBuilderMethods(methodManager) {
410
514
  }
411
515
  else {
412
516
  divFields_1.$addFields[total.id + '_' + field.id] = {
413
- $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
517
+ $divide: ['$' + fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
414
518
  };
415
519
  }
416
520
  }
@@ -419,46 +523,58 @@ function loadReportBuilderMethods(methodManager) {
419
523
  divFields_1.$addFields[total.id + '_' + field.id] = '$count';
420
524
  }
421
525
  else {
422
- divFields_1.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
526
+ divFields_1.$addFields[total.id + '_' + field.id] = '$' + fieldPath.replace(/\.\$/g, '');
423
527
  }
424
528
  }
425
529
  });
426
530
  });
427
531
  selectedFields.filter(function (a) { return a.fieldType === 'Number' && a.leafValueType === 'Sum'; }).forEach(function (field) {
532
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
533
+ if (!fieldPath) {
534
+ return;
535
+ }
428
536
  var multFields = [];
429
- sizes_1.filter(function (a) { return !field.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !groupsRow.some(function (b) { return b.field.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !filterArrayFields.filter(function (a) { return a.fieldPath; }).some(function (b) { return b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }); }).forEach(function (size) {
537
+ sizes_1.filter(function (a) { return !fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !groupsRow.some(function (b) { return (b.field || '').replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !filterArrayFields.filter(function (a) { return a.fieldPath; }).some(function (b) { return b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }); }).forEach(function (size) {
430
538
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
431
539
  });
432
540
  if (multFields.length) {
433
- divFields_1.$addFields[field.fieldPath.replace(/\.\$/g, '')] = {
434
- $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
541
+ divFields_1.$addFields[fieldPath.replace(/\.\$/g, '')] = {
542
+ $divide: ['$' + fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
435
543
  };
436
544
  }
437
545
  });
438
546
  selectedFields.filter(function (a) { return a.leafValueType === 'Count'; }).forEach(function (field) {
547
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
548
+ if (!fieldPath) {
549
+ return;
550
+ }
439
551
  var multFields = [];
440
- sizes_1.filter(function (a) { return !field.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !groupsRow.some(function (b) { return b.field.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !filterArrayFields.filter(function (a) { return a.fieldPath; }).some(function (b) { return b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }); }).forEach(function (size) {
552
+ sizes_1.filter(function (a) { return !fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) && !groupsRow.some(function (b) { return (b.field || '').replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !filterArrayFields.filter(function (a) { return a.fieldPath; }).some(function (b) { return b.fieldPath.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }) && !fieldsLink.some(function (b) { return b.field_first.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a) || b.field_second.replace(/\.\$\./g, '_').replace(/\./g, '_').includes(a); }); }).forEach(function (size) {
441
553
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
442
554
  });
443
555
  if (multFields.length) {
444
- divFields_1.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = {
556
+ divFields_1.$addFields['count_' + fieldPath.replace(/\.\$/g, '')] = {
445
557
  $divide: ['$count', { $multiply: multFields }]
446
558
  };
447
559
  }
448
560
  else {
449
- if (reportType !== 'Dated' && sizes_1.filter(function (a) { return field.fieldPath.replace(/\.\$\./g, '_').includes(a); }).length) {
450
- sizes_1.filter(function (a) { return field.fieldPath.replace(/\.\$\./g, '_').includes(a); }).forEach(function (size) {
451
- divFields_1.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = '$size_' + size;
561
+ if (reportType !== 'Dated' && sizes_1.filter(function (a) { return fieldPath.replace(/\.\$\./g, '_').includes(a); }).length) {
562
+ sizes_1.filter(function (a) { return fieldPath.replace(/\.\$\./g, '_').includes(a); }).forEach(function (size) {
563
+ divFields_1.$addFields['count_' + fieldPath.replace(/\.\$/g, '')] = '$size_' + size;
452
564
  });
453
565
  }
454
566
  else {
455
- divFields_1.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = '$count';
567
+ divFields_1.$addFields['count_' + fieldPath.replace(/\.\$/g, '')] = '$count';
456
568
  }
457
569
  }
458
570
  });
459
571
  fieldsTotal.filter(function (a) { return a.type === 'avg'; }).forEach(function (total) {
460
572
  selectedFields.filter(function (a) { return a.fieldType === 'Number' || a.leafValueType === 'Count'; }).forEach(function (field) {
461
- divFields_1.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
573
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
574
+ if (!fieldPath && field.leafValueType !== 'Count') {
575
+ return;
576
+ }
577
+ divFields_1.$addFields[total.id + '_' + field.id] = '$' + fieldPath.replace(/\.\$/g, '');
462
578
  });
463
579
  });
464
580
  if (Object.keys(divFields_1.$addFields).length > 0) {
@@ -542,8 +658,8 @@ function loadReportBuilderMethods(methodManager) {
542
658
  queryMatchConditionLookup_1 = {
543
659
  $and: []
544
660
  };
545
- if (lookupFilters.length) {
546
- lookupFilters.forEach(function (filter) { return queryMatchConditionLookup_1['$and'].push(filter); });
661
+ if (lookupFilters_1.length) {
662
+ lookupFilters_1.forEach(function (filter) { return queryMatchConditionLookup_1['$and'].push(filter); });
547
663
  }
548
664
  filterArrays.forEach(function (filter) {
549
665
  queryMatchConditionLookup_1['$and'].push(filter);
@@ -564,7 +680,10 @@ function loadReportBuilderMethods(methodManager) {
564
680
  Object.keys(rootOptions.sort).forEach(function (sortField) {
565
681
  var selField = selectedFields.find(function (a) { return a.id === sortField; });
566
682
  if (selField) {
567
- groupedSorts_1[selField.fieldPath.replace(/\.\$/g, '')] = rootOptions.sort[sortField];
683
+ var sortPath = (selField && typeof selField.fieldPath === 'string') ? selField.fieldPath.replace(/\.\$/g, '') : '';
684
+ if (sortPath) {
685
+ groupedSorts_1[sortPath] = rootOptions.sort[sortField];
686
+ }
568
687
  }
569
688
  });
570
689
  if (Object.keys(groupedSorts_1).length > 0) {
@@ -574,79 +693,93 @@ function loadReportBuilderMethods(methodManager) {
574
693
  }
575
694
  }
576
695
  }
577
- groupsRow.forEach(function (row) {
578
- queryGroup_1._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
579
- if (date_field && date_interval) {
696
+ if (groupsRow.length && date_field && date_interval) {
697
+ dateFieldPath = (typeof date_field === 'string') ? date_field.replace(/\.\$/g, '') : '';
698
+ if (dateFieldPath) {
580
699
  if (date_interval === 'Seconds') {
581
- queryGroup_1._id['second'] = { '$second': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
582
- queryGroup_1._id['minute'] = { '$minute': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
583
- queryGroup_1._id['hour'] = { '$hour': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
584
- queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
585
- queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
586
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
700
+ queryGroup_1._id['second'] = { '$second': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
701
+ queryGroup_1._id['minute'] = { '$minute': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
702
+ queryGroup_1._id['hour'] = { '$hour': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
703
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
704
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
705
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
587
706
  }
588
707
  else if (date_interval === 'Minutes') {
589
- queryGroup_1._id['minute'] = { '$minute': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
590
- queryGroup_1._id['hour'] = { '$hour': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
591
- queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
592
- queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
593
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
708
+ queryGroup_1._id['minute'] = { '$minute': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
709
+ queryGroup_1._id['hour'] = { '$hour': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
710
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
711
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
712
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
594
713
  }
595
714
  else if (date_interval === 'Hours') {
596
- queryGroup_1._id['hour'] = { '$hour': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
597
- queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
598
- queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
599
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
715
+ queryGroup_1._id['hour'] = { '$hour': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
716
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
717
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
718
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
600
719
  }
601
720
  else if (date_interval === 'Daily') {
602
- queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
603
- queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
604
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
721
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
722
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
723
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
605
724
  }
606
725
  else if (date_interval === 'Weekly') {
607
- queryGroup_1._id['week'] = { '$isoWeek': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
608
- queryGroup_1._id['year'] = { '$isoWeekYear': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
726
+ queryGroup_1._id['week'] = { '$isoWeek': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
727
+ queryGroup_1._id['year'] = { '$isoWeekYear': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
609
728
  }
610
729
  else if (date_interval === 'Monthly') {
611
- queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
612
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
730
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
731
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
613
732
  }
614
733
  else if (date_interval === 'Quarterly') {
615
- queryGroup_1._id['month'] = { '$month': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
616
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
734
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
735
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
617
736
  }
618
737
  else if (date_interval === 'Yearly') {
619
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
738
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
620
739
  }
621
740
  }
741
+ }
742
+ groupsRow.forEach(function (row) {
743
+ var rowField = (row && typeof row.field === 'string') ? row.field : '';
744
+ if (!rowField || !(row === null || row === void 0 ? void 0 : row.id)) {
745
+ return;
746
+ }
747
+ queryGroup_1._id[row.id] = '$' + rowField.replace(/\.\$/g, '');
622
748
  });
623
749
  selectedFields.forEach(function (field) {
750
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
751
+ if (!fieldPath) {
752
+ if (field.leafValueType === 'Count') {
753
+ queryGroup_1[field.id] = { '$sum': 1 };
754
+ }
755
+ return;
756
+ }
624
757
  if (field.leafValueType === 'Average') {
625
- queryGroup_1[field.id] = { '$avg': '$' + field.fieldPath.replace(/\.\$/g, '') };
758
+ queryGroup_1[field.id] = { '$avg': '$' + fieldPath.replace(/\.\$/g, '') };
626
759
  }
627
760
  else if (field.leafValueType === 'Sum') {
628
- queryGroup_1[field.id] = { '$sum': '$' + field.fieldPath.replace(/\.\$/g, '') };
761
+ queryGroup_1[field.id] = { '$sum': '$' + fieldPath.replace(/\.\$/g, '') };
629
762
  }
630
763
  else if (field.leafValueType === 'Count') {
631
- queryGroup_1[field.id] = { '$sum': '$count_' + field.fieldPath.replace(/\.\$/g, '') };
764
+ queryGroup_1[field.id] = { '$sum': '$count_' + fieldPath.replace(/\.\$/g, '') };
632
765
  }
633
766
  else if (field.leafValueType === 'Minimum') {
634
- queryGroup_1[field.id] = { '$min': '$' + field.fieldPath.replace(/\.\$/g, '') };
767
+ queryGroup_1[field.id] = { '$min': '$' + fieldPath.replace(/\.\$/g, '') };
635
768
  }
636
769
  else if (field.leafValueType === 'Maximum') {
637
- queryGroup_1[field.id] = { '$max': '$' + field.fieldPath.replace(/\.\$/g, '') };
770
+ queryGroup_1[field.id] = { '$max': '$' + fieldPath.replace(/\.\$/g, '') };
638
771
  }
639
772
  else if (field.leafValueType === 'First') {
640
- queryGroup_1[field.id] = { '$first': '$' + field.fieldPath.replace(/\.\$/g, '') };
773
+ queryGroup_1[field.id] = { '$first': '$' + fieldPath.replace(/\.\$/g, '') };
641
774
  }
642
775
  else if (field.leafValueType === 'Last') {
643
- queryGroup_1[field.id] = { '$last': '$' + field.fieldPath.replace(/\.\$/g, '') };
776
+ queryGroup_1[field.id] = { '$last': '$' + fieldPath.replace(/\.\$/g, '') };
644
777
  }
645
778
  else if (field.leafValueType === 'Unique') {
646
- queryGroup_1[field.id] = { '$addToSet': '$' + field.fieldPath.replace(/\.\$/g, '') };
779
+ queryGroup_1[field.id] = { '$addToSet': '$' + fieldPath.replace(/\.\$/g, '') };
647
780
  }
648
781
  else {
649
- queryGroup_1[field.id] = { '$push': { $ifNull: ['$' + field.fieldPath.replace(/\.\$/g, ''), null] } };
782
+ queryGroup_1[field.id] = { '$push': { $ifNull: ['$' + fieldPath.replace(/\.\$/g, ''), null] } };
650
783
  }
651
784
  });
652
785
  customFields.forEach(function (cust) {
@@ -703,23 +836,27 @@ function loadReportBuilderMethods(methodManager) {
703
836
  _id: 1
704
837
  };
705
838
  selectedFields.forEach(function (field) {
839
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
840
+ if (!fieldPath && field.leafValueType !== 'Count') {
841
+ return;
842
+ }
706
843
  if (field.leafValueType === 'Average') {
707
- queryProjection_1[field.id] = { $avg: '$' + field.fieldPath.replace(/\.\$/g, '') };
844
+ queryProjection_1[field.id] = { $avg: '$' + fieldPath.replace(/\.\$/g, '') };
708
845
  }
709
846
  else if (field.leafValueType === 'Sum') {
710
- queryProjection_1[field.id] = { $sum: '$' + field.fieldPath.replace(/\.\$/g, '') };
847
+ queryProjection_1[field.id] = { $sum: '$' + fieldPath.replace(/\.\$/g, '') };
711
848
  }
712
849
  else if (field.leafValueType === 'Count') {
713
850
  queryProjection_1[field.id] = { $sum: 1 };
714
851
  }
715
852
  else if (field.leafValueType === 'Minimum') {
716
- queryProjection_1[field.id] = { $min: '$' + field.fieldPath.replace(/\.\$/g, '') };
853
+ queryProjection_1[field.id] = { $min: '$' + fieldPath.replace(/\.\$/g, '') };
717
854
  }
718
855
  else if (field.leafValueType === 'Maximum') {
719
- queryProjection_1[field.id] = { $max: '$' + field.fieldPath.replace(/\.\$/g, '') };
856
+ queryProjection_1[field.id] = { $max: '$' + fieldPath.replace(/\.\$/g, '') };
720
857
  }
721
858
  else {
722
- queryProjection_1[field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
859
+ queryProjection_1[field.id] = '$' + fieldPath.replace(/\.\$/g, '');
723
860
  }
724
861
  });
725
862
  customFields.forEach(function (cust) {
@@ -763,10 +900,10 @@ function loadReportBuilderMethods(methodManager) {
763
900
  }
764
901
  if (reportType === 'Group' && groupsRow.length > 1) {
765
902
  _loop_1 = function (i) {
766
- var _c;
903
+ var _d;
767
904
  var projQuery = { _id: 1 };
768
905
  projQuery[groupsRow[i].id] = {
769
- _id: (_c = {}, _c[groupsRow[i].id] = '$_id.' + groupsRow[i].id, _c)
906
+ _id: (_d = {}, _d[groupsRow[i].id] = '$_id.' + groupsRow[i].id, _d)
770
907
  };
771
908
  if (i === groupsRow.length - 1) {
772
909
  selectedFields.forEach(function (field) {
@@ -834,44 +971,44 @@ function loadReportBuilderMethods(methodManager) {
834
971
  _loop_1(i);
835
972
  }
836
973
  }
837
- res_1 = null;
838
- _b.label = 2;
839
- case 2:
840
- _b.trys.push([2, 4, , 5]);
974
+ res_2 = null;
975
+ _c.label = 7;
976
+ case 7:
977
+ _c.trys.push([7, 9, , 10]);
841
978
  return [4 /*yield*/, modelCollection.aggregate(query_1, { allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary' }, true)];
842
- case 3:
843
- res_1 = _b.sent();
844
- return [3 /*break*/, 5];
845
- case 4:
846
- err_1 = _b.sent();
847
- console.log(err_1);
848
- return [3 /*break*/, 5];
849
- case 5:
850
- tmpTotals_1 = {};
851
- if (res_1) {
979
+ case 8:
980
+ res_2 = _c.sent();
981
+ return [3 /*break*/, 10];
982
+ case 9:
983
+ err_2 = _c.sent();
984
+ console.log(err_2);
985
+ return [3 /*break*/, 10];
986
+ case 10:
987
+ tmpTotals_2 = {};
988
+ if (res_2) {
852
989
  fieldsTotal.forEach(function (totField) {
853
990
  selectedFields.filter(function (b) { return b.fieldType === 'Number' || b.leafValueType === 'Count'; }).forEach(function (selField) {
854
991
  if (totField.type === 'sum') {
855
- tmpTotals_1[totField.id + '_' + selField.id] = res_1.map(function (a) { return a[totField.id + '_' + selField.id] || 0; }).reduce(function (a, b) { return a + b; }, 0);
992
+ tmpTotals_2[totField.id + '_' + selField.id] = res_2.map(function (a) { return a[totField.id + '_' + selField.id] || 0; }).reduce(function (a, b) { return a + b; }, 0);
856
993
  }
857
994
  else if (totField.type === 'avg') {
858
- tmpTotals_1[totField.id + '_' + selField.id] = (0, common_1.round)(res_1.map(function (a) { return a[totField.id + '_' + selField.id] || 0; }).reduce(function (a, b) { return a + b; }, 0) / res_1.length);
995
+ tmpTotals_2[totField.id + '_' + selField.id] = (0, common_1.round)(res_2.map(function (a) { return a[totField.id + '_' + selField.id] || 0; }).reduce(function (a, b) { return a + b; }, 0) / res_2.length);
859
996
  }
860
997
  });
861
998
  customFields.forEach(function (custField) {
862
999
  if (totField.type === 'sum') {
863
- tmpTotals_1[totField.id + '_' + custField.selFieldId] = res_1.map(function (a) { return a[totField.id + '_' + custField.selFieldId] || 0; }).reduce(function (a, b) { return a + b; }, 0);
1000
+ tmpTotals_2[totField.id + '_' + custField.selFieldId] = res_2.map(function (a) { return a[totField.id + '_' + custField.selFieldId] || 0; }).reduce(function (a, b) { return a + b; }, 0);
864
1001
  }
865
1002
  else if (totField.type === 'avg') {
866
- tmpTotals_1[totField.id + '_' + custField.selFieldId] = (0, common_1.round)(res_1.map(function (a) { return a[totField.id + '_' + custField.selFieldId] || 0; }).reduce(function (a, b) { return a + b; }, 0) / res_1.length);
1003
+ tmpTotals_2[totField.id + '_' + custField.selFieldId] = (0, common_1.round)(res_2.map(function (a) { return a[totField.id + '_' + custField.selFieldId] || 0; }).reduce(function (a, b) { return a + b; }, 0) / res_2.length);
867
1004
  }
868
1005
  });
869
1006
  });
870
1007
  }
871
1008
  tmpRes = [{
872
- count: res_1 ? res_1.length : 0,
873
- results: res_1 ? (rootOptions.limit ? res_1.splice(0, rootOptions.limit) : res_1) : [],
874
- totals: tmpTotals_1
1009
+ count: res_2 ? res_2.length : 0,
1010
+ results: res_2 ? (rootOptions.limit ? res_2.splice(0, rootOptions.limit) : res_2) : [],
1011
+ totals: tmpTotals_2
875
1012
  }];
876
1013
  return [2 /*return*/, tmpRes];
877
1014
  }
@@ -1045,7 +1182,9 @@ function splitFiltersByLookup(filters, lookupAliases) {
1045
1182
  var rootFilters = [];
1046
1183
  var lookupFilters = [];
1047
1184
  (filters || []).forEach(function (filter) {
1048
- if (filterContainsLookup(filter, lookupAliases)) {
1185
+ var summary = summarizeFilterTargets(filter, lookupAliases);
1186
+ if (summary.hasLookup) {
1187
+ // If the filter mixes root + lookup, keep it together in lookupFilters so it stays a single $match/$or
1049
1188
  lookupFilters.push(filter);
1050
1189
  }
1051
1190
  else {
@@ -1054,17 +1193,33 @@ function splitFiltersByLookup(filters, lookupAliases) {
1054
1193
  });
1055
1194
  return { rootFilters: rootFilters, lookupFilters: lookupFilters };
1056
1195
  }
1057
- function filterContainsLookup(filter, lookupAliases) {
1196
+ function summarizeFilterTargets(filter, lookupAliases) {
1197
+ var result = { hasLookup: false, hasRoot: false };
1058
1198
  if (!filter || typeof filter !== 'object') {
1059
- return false;
1199
+ return result;
1060
1200
  }
1061
- return Object.keys(filter).some(function (key) {
1201
+ Object.keys(filter).forEach(function (key) {
1062
1202
  if (key === '$or' || key === '$and') {
1063
1203
  var branch = filter[key];
1064
- return Array.isArray(branch) && branch.some(function (child) { return filterContainsLookup(child, lookupAliases); });
1204
+ if (Array.isArray(branch)) {
1205
+ branch.forEach(function (child) {
1206
+ var childSummary = summarizeFilterTargets(child, lookupAliases);
1207
+ result.hasLookup = result.hasLookup || childSummary.hasLookup;
1208
+ result.hasRoot = result.hasRoot || childSummary.hasRoot;
1209
+ });
1210
+ }
1211
+ }
1212
+ else {
1213
+ var isLookup = isLookupPath(key, lookupAliases);
1214
+ if (isLookup) {
1215
+ result.hasLookup = true;
1216
+ }
1217
+ else {
1218
+ result.hasRoot = true;
1219
+ }
1065
1220
  }
1066
- return isLookupPath(key, lookupAliases);
1067
1221
  });
1222
+ return result;
1068
1223
  }
1069
1224
  function isLookupPath(path, lookupAliases) {
1070
1225
  if (!path) {
@@ -1086,6 +1241,222 @@ function extractLookupAlias(path) {
1086
1241
  function normalizeLookupAlias(alias) {
1087
1242
  return (alias || '').replace(/\.\$/g, '').trim();
1088
1243
  }
1244
+ // Helpers to support union-based joins (collection_joins without local/foreign key)
1245
+ function stripAliasFromPath(path, alias) {
1246
+ if (!path) {
1247
+ return path;
1248
+ }
1249
+ var cleanAlias = alias.replace(/\.\$/g, '');
1250
+ var cleanPath = path.replace(/\.\$/g, '');
1251
+ if (cleanPath.startsWith(cleanAlias + '.')) {
1252
+ return cleanPath.substring(cleanAlias.length + 1);
1253
+ }
1254
+ return cleanPath;
1255
+ }
1256
+ function buildCollectionPipeline(collectionName, alias, selectedFields, filters, filterArrays, isRoot) {
1257
+ if (selectedFields === void 0) { selectedFields = []; }
1258
+ if (filters === void 0) { filters = []; }
1259
+ if (filterArrays === void 0) { filterArrays = []; }
1260
+ if (isRoot === void 0) { isRoot = false; }
1261
+ var pipeline = [];
1262
+ var matchClauses = [];
1263
+ var matchArrayClauses = [];
1264
+ var targetAlias = isRoot ? '' : alias.replace(/\.\$/g, '');
1265
+ var mapFilterForCollection = function (filterObj, toArray) {
1266
+ if (!filterObj || typeof filterObj !== 'object') {
1267
+ return;
1268
+ }
1269
+ var mapped = mapFilterPaths(filterObj, targetAlias, isRoot);
1270
+ if (mapped) {
1271
+ (toArray ? matchArrayClauses : matchClauses).push(mapped);
1272
+ }
1273
+ };
1274
+ (filters || []).forEach(function (f) { return mapFilterForCollection(f, false); });
1275
+ (filterArrays || []).forEach(function (f) { return mapFilterForCollection(f, true); });
1276
+ if (matchClauses.length || matchArrayClauses.length) {
1277
+ var match = { $and: __spreadArray(__spreadArray([], __read(matchClauses), false), __read(matchArrayClauses), false) };
1278
+ pipeline.push({ $match: match });
1279
+ if (process.env.NODE_ENV !== 'production') {
1280
+ console.info('RB debug: collection pipeline match', {
1281
+ collection: collectionName,
1282
+ alias: targetAlias || collectionName,
1283
+ matchJson: JSON.stringify(match, null, 2)
1284
+ });
1285
+ }
1286
+ }
1287
+ // Projection mapping selected fields for this collection
1288
+ var projection = { _id: 1, __rb_collection: targetAlias || collectionName };
1289
+ (selectedFields || [])
1290
+ .filter(function (f) { return isFieldForCollection(f, collectionName, targetAlias); })
1291
+ .forEach(function (f) {
1292
+ var mappedPath = stripAliasFromPath(f.fieldPath || '', targetAlias || f.lookup_as || '');
1293
+ if (f.leafValueType === 'Average') {
1294
+ projection[f.id] = { $avg: '$' + mappedPath };
1295
+ }
1296
+ else if (f.leafValueType === 'Sum') {
1297
+ projection[f.id] = { $sum: '$' + mappedPath };
1298
+ }
1299
+ else if (f.leafValueType === 'Count') {
1300
+ projection[f.id] = { $sum: 1 };
1301
+ }
1302
+ else if (f.leafValueType === 'Minimum') {
1303
+ projection[f.id] = { $min: '$' + mappedPath };
1304
+ }
1305
+ else if (f.leafValueType === 'Maximum') {
1306
+ projection[f.id] = { $max: '$' + mappedPath };
1307
+ }
1308
+ else {
1309
+ projection[f.id] = '$' + mappedPath;
1310
+ }
1311
+ });
1312
+ pipeline.push({ $project: projection });
1313
+ return pipeline;
1314
+ }
1315
+ function isFieldForCollection(field, collectionName, alias) {
1316
+ if (!field) {
1317
+ return false;
1318
+ }
1319
+ // Root collection check
1320
+ if (!alias) {
1321
+ return field.collection_name === collectionName && (!field.lookup_collection || field.lookup_collection === '');
1322
+ }
1323
+ // Joined collection check
1324
+ return field.lookup_collection === collectionName || (field.lookup_as && field.lookup_as.replace(/\.\$/g, '') === alias);
1325
+ }
1326
+ function mapFilterPaths(filter, alias, isRoot) {
1327
+ if (!filter || typeof filter !== 'object') {
1328
+ return null;
1329
+ }
1330
+ if (Array.isArray(filter)) {
1331
+ return filter.map(function (f) { return mapFilterPaths(f, alias, isRoot); });
1332
+ }
1333
+ if (filter.$or) {
1334
+ var mapped = filter.$or.map(function (f) { return mapFilterPaths(f, alias, isRoot); }).filter(Boolean);
1335
+ return mapped.length ? { $or: mapped } : null;
1336
+ }
1337
+ if (filter.$and) {
1338
+ var mapped = filter.$and.map(function (f) { return mapFilterPaths(f, alias, isRoot); }).filter(Boolean);
1339
+ return mapped.length ? { $and: mapped } : null;
1340
+ }
1341
+ var out = {};
1342
+ Object.keys(filter).forEach(function (key) {
1343
+ var cleanKey = key.replace(/\.\$/g, '');
1344
+ if (!alias) {
1345
+ // root collection: ignore keys that start with a lookup alias
1346
+ if (cleanKey.includes('(Lookup')) {
1347
+ return;
1348
+ }
1349
+ if (lookupAliasMatches(cleanKey, alias)) {
1350
+ return;
1351
+ }
1352
+ out[cleanKey] = filter[key];
1353
+ }
1354
+ else {
1355
+ if (cleanKey.startsWith(alias + '.')) {
1356
+ out[cleanKey.substring(alias.length + 1)] = filter[key];
1357
+ }
1358
+ }
1359
+ });
1360
+ return Object.keys(out).length ? out : null;
1361
+ }
1362
+ function lookupAliasMatches(path, alias) {
1363
+ if (!path || !alias) {
1364
+ return false;
1365
+ }
1366
+ return path.startsWith(alias + '.') || path === alias;
1367
+ }
1368
+ function buildLayoutSortSpec(sortSpec, selectedFields) {
1369
+ if (sortSpec === void 0) { sortSpec = {}; }
1370
+ if (selectedFields === void 0) { selectedFields = []; }
1371
+ var outSort = __assign({}, sortSpec);
1372
+ var addFields = {};
1373
+ Object.keys(sortSpec || {}).forEach(function (key) {
1374
+ if (!key.startsWith('layout_col_')) {
1375
+ return;
1376
+ }
1377
+ var normalized = key.replace(/^layout_col_/, '');
1378
+ var parts = normalized.split('_');
1379
+ var idx = parseInt(parts[parts.length - 1], 10);
1380
+ if (isNaN(idx)) {
1381
+ return;
1382
+ }
1383
+ var layoutFields = (selectedFields || []).filter(function (f) { return typeof (f === null || f === void 0 ? void 0 : f.layoutColumnIndex) !== 'undefined' && f.layoutColumnIndex === idx; }).map(function (f) { return f.id; }).filter(Boolean);
1384
+ if (!layoutFields.length) {
1385
+ return;
1386
+ }
1387
+ // Build nested $ifNull chain to coalesce across layout column targets
1388
+ var coalesce = '';
1389
+ for (var i = layoutFields.length - 1; i >= 0; i--) {
1390
+ var fieldPath = '$' + layoutFields[i];
1391
+ if (i === layoutFields.length - 1) {
1392
+ coalesce = fieldPath;
1393
+ }
1394
+ else {
1395
+ coalesce = { $ifNull: [fieldPath, coalesce] };
1396
+ }
1397
+ }
1398
+ var sortKey = 'sort_' + key;
1399
+ addFields[sortKey] = coalesce;
1400
+ delete outSort[key];
1401
+ outSort[sortKey] = sortSpec[key];
1402
+ });
1403
+ return { sortSpec: outSort, addFields: addFields };
1404
+ }
1405
+ function remapFiltersToIds(filters, selectedFields) {
1406
+ if (filters === void 0) { filters = []; }
1407
+ if (selectedFields === void 0) { selectedFields = []; }
1408
+ var byPath = new Map();
1409
+ var layoutMap = new Map();
1410
+ (selectedFields || []).forEach(function (f) {
1411
+ if ((f === null || f === void 0 ? void 0 : f.fieldPath) && (f === null || f === void 0 ? void 0 : f.id)) {
1412
+ byPath.set(f.fieldPath.replace(/\.\$/g, ''), f.id);
1413
+ }
1414
+ if (typeof (f === null || f === void 0 ? void 0 : f.layoutColumnIndex) !== 'undefined') {
1415
+ var arr = layoutMap.get(f.layoutColumnIndex) || [];
1416
+ arr.push(f.id);
1417
+ layoutMap.set(f.layoutColumnIndex, arr);
1418
+ }
1419
+ });
1420
+ var remapObj = function (obj) {
1421
+ if (!obj || typeof obj !== 'object') {
1422
+ return obj;
1423
+ }
1424
+ if (Array.isArray(obj)) {
1425
+ return obj.map(remapObj);
1426
+ }
1427
+ if (obj.$or) {
1428
+ var mapped = obj.$or.map(remapObj).filter(Boolean);
1429
+ return mapped.length ? { $or: mapped } : null;
1430
+ }
1431
+ if (obj.$and) {
1432
+ var mapped = obj.$and.map(remapObj).filter(Boolean);
1433
+ return mapped.length ? { $and: mapped } : null;
1434
+ }
1435
+ var out = {};
1436
+ Object.keys(obj).forEach(function (key) {
1437
+ var cleanKey = key.replace(/\.\$/g, '');
1438
+ if (cleanKey.startsWith('layout_col_')) {
1439
+ // map to all field ids in that layout column index
1440
+ var normalized = cleanKey.replace(/^layout_col_/, '');
1441
+ var parts = normalized.split('_');
1442
+ var idx = parseInt(parts[parts.length - 1], 10);
1443
+ var targets = layoutMap.get(idx) || [];
1444
+ if (targets.length) {
1445
+ var mappedVal_1 = remapObj(obj[key]);
1446
+ out.$or = targets.map(function (id) {
1447
+ var _a;
1448
+ return (_a = {}, _a[id] = mappedVal_1, _a);
1449
+ });
1450
+ return;
1451
+ }
1452
+ }
1453
+ var mappedKey = byPath.get(cleanKey) || cleanKey;
1454
+ out[mappedKey] = remapObj(obj[key]);
1455
+ });
1456
+ return Object.keys(out).length ? out : null;
1457
+ };
1458
+ return (filters || []).map(remapObj).filter(Boolean);
1459
+ }
1089
1460
  function expandLayoutColumnFilters(filters, selectedFields) {
1090
1461
  if (filters === void 0) { filters = []; }
1091
1462
  if (selectedFields === void 0) { selectedFields = []; }