@resolveio/server-lib 20.12.47 → 20.12.48

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,67 @@ 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");
52
77
  var pagination_model_1 = require("../models/pagination.model");
53
78
  var resolveio_server_app_1 = require("../resolveio-server-app");
79
+ var report_builder_report_collection_1 = require("../collections/report-builder-report.collection");
54
80
  var common_1 = require("../util/common");
55
81
  var schema_report_builder_1 = require("../util/schema-report-builder");
82
+ function hasLayoutColumnFilters(filters) {
83
+ if (filters === void 0) { filters = []; }
84
+ var hasLayoutKey = function (obj) {
85
+ if (!obj || typeof obj !== 'object') {
86
+ return false;
87
+ }
88
+ return Object.keys(obj).some(function (key) {
89
+ if (key === '$or' || key === '$and') {
90
+ var branch = obj[key];
91
+ return Array.isArray(branch) && branch.some(hasLayoutKey);
92
+ }
93
+ return key.startsWith('layout_col_');
94
+ });
95
+ };
96
+ return (filters || []).some(hasLayoutKey);
97
+ }
56
98
  function loadReportBuilderMethods(methodManager) {
57
99
  methodManager.methods({
100
+ reportbuilderreportWithId: {
101
+ check: new simpl_schema_1.default({
102
+ id: {
103
+ type: String
104
+ }
105
+ }),
106
+ function: function (id) {
107
+ return report_builder_report_collection_1.ReportBuilderReports.findOne({ _id: id });
108
+ }
109
+ },
58
110
  reportBuilderBuildTree: {
59
111
  check: new simpl_schema_1.default({
60
112
  collection_root: {
@@ -127,13 +179,15 @@ function loadReportBuilderMethods(methodManager) {
127
179
  }),
128
180
  function: function (treeLeaf) {
129
181
  return __awaiter(this, void 0, void 0, function () {
182
+ var fieldPath;
130
183
  return __generator(this, function (_a) {
131
184
  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, ''))];
185
+ fieldPath = (treeLeaf && typeof treeLeaf.fieldPath === 'string') ? treeLeaf.fieldPath : '';
186
+ if (fieldPath.includes('(Lookup') || treeLeaf.lookup_collection) {
187
+ return [2 /*return*/, (0, schema_report_builder_1.mongoCommand)('distinct', treeLeaf.collection_name, fieldPath.replace(/^.+\(.+\) \(Lookup.*\)\.\$\./g, '').replace(/\.\$/g, ''))];
134
188
  }
135
189
  else {
136
- return [2 /*return*/, (0, schema_report_builder_1.mongoCommand)('distinct', treeLeaf.collection_name, treeLeaf.fieldPath.replace(/\.\$/g, ''))];
190
+ return [2 /*return*/, (0, schema_report_builder_1.mongoCommand)('distinct', treeLeaf.collection_name, fieldPath.replace(/\.\$/g, ''))];
137
191
  }
138
192
  }
139
193
  else {
@@ -145,6 +199,7 @@ function loadReportBuilderMethods(methodManager) {
145
199
  }
146
200
  },
147
201
  reportBuilderGetResults: {
202
+ bypassSession: true,
148
203
  check: new simpl_schema_1.default({
149
204
  reportType: {
150
205
  type: String
@@ -236,7 +291,7 @@ function loadReportBuilderMethods(methodManager) {
236
291
  }),
237
292
  function: function (reportType_1, rootCollectionName_1, rootOptions_1) {
238
293
  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;
294
+ var modelCollection, hasLayoutFilters, shouldDebugFilters, lookupAliases_1, _a, rootFilters_1, lookupFilters_1, additionalCollectionsMap_1, additionalCollections, logUnionDebug, unionQuery_1, _b, sortToUse, layoutSortAdd, remappedFilters, remappedArrayFilters, postMatchAnd, res_1, err_1, sample, tmpTotals_1, resultsOut, tmpRes_1, query_1, lookupDebug_1, initialQueryMatchCondition_1, sizes_1, divFields_1, queryMatchConditionLookup_1, matchStages, queryGroup_1, groupedSorts_1, dateFieldPath, queryProjection_1, _loop_1, i, res_2, err_2, sample, sampleSlim, tmpTotals_2, tmpRes;
240
295
  if (filters === void 0) { filters = []; }
241
296
  if (filterArrays === void 0) { filterArrays = []; }
242
297
  if (filterArrayFields === void 0) { filterArrayFields = []; }
@@ -248,18 +303,171 @@ function loadReportBuilderMethods(methodManager) {
248
303
  if (date_field === void 0) { date_field = ''; }
249
304
  if (date_interval === void 0) { date_interval = ''; }
250
305
  if (displayType === void 0) { displayType = ''; }
251
- return __generator(this, function (_b) {
252
- switch (_b.label) {
306
+ return __generator(this, function (_c) {
307
+ switch (_c.label) {
253
308
  case 0:
254
309
  modelCollection = resolveio_server_app_1.ResolveIOServer.getMongoManager().collection(rootCollectionName);
255
310
  if (!!modelCollection) return [3 /*break*/, 1];
256
311
  throw new Error('Error in Report builder get results: Invalid collection');
257
312
  case 1:
313
+ hasLayoutFilters = hasLayoutColumnFilters(filters) || hasLayoutColumnFilters(filterArrays);
314
+ shouldDebugFilters = hasLayoutFilters || ((filters || []).length > 0) || ((filterArrays || []).length > 0);
315
+ if (shouldDebugFilters) {
316
+ console.info('RB debug: inbound filters', {
317
+ reportType: reportType,
318
+ rootCollectionName: rootCollectionName,
319
+ filterCount: (filters || []).length,
320
+ filterArrayCount: (filterArrays || []).length,
321
+ hasLayoutFilters: hasLayoutFilters,
322
+ layoutColumns: (selectedFields || [])
323
+ .filter(function (f) { return typeof (f === null || f === void 0 ? void 0 : f.layoutColumnIndex) !== 'undefined'; })
324
+ .map(function (f) { return ({ id: f.id, layoutColumnIndex: f.layoutColumnIndex, fieldPath: f.fieldPath }); })
325
+ });
326
+ }
258
327
  filters = expandLayoutColumnFilters(filters, selectedFields);
259
328
  filterArrays = expandLayoutColumnFilters(filterArrays, selectedFields);
260
- lookupAliases = collectLookupAliases(selectedFields, filterArrayFields, groupsRow);
261
- _a = splitFiltersByLookup(filters, lookupAliases), rootFilters = _a.rootFilters, lookupFilters = _a.lookupFilters;
329
+ if (shouldDebugFilters) {
330
+ console.info('RB debug: expanded filters', { filters: filters, filterArrays: filterArrays });
331
+ }
332
+ lookupAliases_1 = collectLookupAliases(selectedFields, filterArrayFields, groupsRow);
333
+ _a = splitFiltersByLookup(filters, lookupAliases_1), rootFilters_1 = _a.rootFilters, lookupFilters_1 = _a.lookupFilters;
334
+ if (shouldDebugFilters) {
335
+ console.info('RB debug: split filters', {
336
+ rootFilters: rootFilters_1,
337
+ lookupFilters: lookupFilters_1,
338
+ lookupAliases: Array.from(lookupAliases_1 || [])
339
+ });
340
+ }
341
+ additionalCollectionsMap_1 = new Map();
342
+ (selectedFields || [])
343
+ .filter(function (f) { return f && f.lookup_collection; })
344
+ .forEach(function (f) {
345
+ var alias = f.lookup_as || f.lookup_collection;
346
+ var key = "".concat(f.lookup_collection, "::").concat(alias);
347
+ if (!additionalCollectionsMap_1.has(key)) {
348
+ additionalCollectionsMap_1.set(key, { collection: f.lookup_collection, alias: alias });
349
+ }
350
+ });
351
+ additionalCollections = Array.from(additionalCollectionsMap_1.values());
352
+ if (!additionalCollections.length) return [3 /*break*/, 6];
353
+ logUnionDebug = true;
354
+ unionQuery_1 = buildCollectionPipeline(rootCollectionName, '', selectedFields, filters.concat(rootFilters_1 || []), filterArrays.concat(lookupFilters_1 || []), true);
355
+ additionalCollections.forEach(function (cfg) {
356
+ unionQuery_1.push({
357
+ $unionWith: {
358
+ coll: cfg.collection,
359
+ pipeline: buildCollectionPipeline(cfg.collection, cfg.alias, selectedFields, filters.concat(rootFilters_1 || []), filterArrays.concat(lookupFilters_1 || []), false)
360
+ }
361
+ });
362
+ });
363
+ if (rootOptions.sort) {
364
+ _b = buildLayoutSortSpec(rootOptions.sort, selectedFields), sortToUse = _b.sortSpec, layoutSortAdd = _b.addFields;
365
+ if (Object.keys(layoutSortAdd).length) {
366
+ unionQuery_1.push({ $addFields: layoutSortAdd });
367
+ }
368
+ appendSafeSort(unionQuery_1, sortToUse, selectedFields, customFields);
369
+ }
370
+ remappedFilters = remapFiltersToIds(filters.concat(rootFilters_1 || []), selectedFields);
371
+ remappedArrayFilters = remapFiltersToIds(filterArrays.concat(lookupFilters_1 || []), selectedFields);
372
+ postMatchAnd = [];
373
+ if (remappedFilters.length) {
374
+ postMatchAnd.push.apply(postMatchAnd, __spreadArray([], __read(remappedFilters), false));
375
+ }
376
+ if (remappedArrayFilters.length) {
377
+ postMatchAnd.push.apply(postMatchAnd, __spreadArray([], __read(remappedArrayFilters), false));
378
+ }
379
+ if (postMatchAnd.length) {
380
+ unionQuery_1.push({ $match: { $and: postMatchAnd } });
381
+ }
382
+ if (logUnionDebug) {
383
+ console.info('RB debug: union pipeline summary', {
384
+ stageCount: unionQuery_1.length,
385
+ sort: rootOptions.sort || {},
386
+ postMatchApplied: postMatchAnd.length,
387
+ remappedFilters: remappedFilters,
388
+ remappedArrayFilters: remappedArrayFilters,
389
+ pipelineJson: JSON.stringify(unionQuery_1, null, 2)
390
+ });
391
+ }
392
+ res_1 = null;
393
+ _c.label = 2;
394
+ case 2:
395
+ _c.trys.push([2, 4, , 5]);
396
+ return [4 /*yield*/, modelCollection.aggregate(unionQuery_1, { allowDiskUse: true, readPreference: this.serverConfig['ROOT_URL'] !== 'http://localhost:4200' ? 'secondary' : 'primary' }, true)];
397
+ case 3:
398
+ res_1 = _c.sent();
399
+ return [3 /*break*/, 5];
400
+ case 4:
401
+ err_1 = _c.sent();
402
+ console.log(err_1);
403
+ return [3 /*break*/, 5];
404
+ case 5:
405
+ if (logUnionDebug) {
406
+ console.info('RB debug: aggregate result (union mode)', {
407
+ count: Array.isArray(res_1) ? res_1.length : 0
408
+ });
409
+ sample = Array.isArray(res_1) ? res_1.slice(0, 3) : [];
410
+ console.info('RB debug: sample results', JSON.stringify(sample, null, 2));
411
+ }
412
+ tmpTotals_1 = {};
413
+ if (res_1) {
414
+ fieldsTotal.forEach(function (totField) {
415
+ selectedFields.filter(function (b) { return b.fieldType === 'Number' || b.leafValueType === 'Count'; }).forEach(function (selField) {
416
+ var sum = res_1.map(function (a) {
417
+ var raw = a ? a[selField.id] : null;
418
+ if (Array.isArray(raw)) {
419
+ return raw
420
+ .map(function (v) { return (typeof v === 'number' ? v : Number(v)); })
421
+ .filter(function (v) { return !isNaN(v); })
422
+ .reduce(function (x, y) { return x + y; }, 0);
423
+ }
424
+ var num = typeof raw === 'number' ? raw : (raw !== null && raw !== undefined ? Number(raw) : 0);
425
+ return isNaN(num) ? 0 : num;
426
+ }).reduce(function (a, b) { return a + b; }, 0);
427
+ if (totField.type === 'sum') {
428
+ tmpTotals_1[totField.id + '_' + selField.id] = sum;
429
+ }
430
+ else if (totField.type === 'avg') {
431
+ tmpTotals_1[totField.id + '_' + selField.id] = res_1.length ? (0, common_1.round)(sum / res_1.length) : 0;
432
+ }
433
+ });
434
+ });
435
+ }
436
+ resultsOut = res_1 || [];
437
+ if (rootOptions.skip) {
438
+ resultsOut = resultsOut.slice(rootOptions.skip);
439
+ }
440
+ if (rootOptions.limit) {
441
+ resultsOut = resultsOut.slice(0, rootOptions.limit);
442
+ }
443
+ tmpRes_1 = [{
444
+ count: res_1 ? res_1.length : 0,
445
+ results: resultsOut,
446
+ totals: tmpTotals_1
447
+ }];
448
+ return [2 /*return*/, tmpRes_1];
449
+ case 6:
262
450
  query_1 = [];
451
+ lookupDebug_1 = {
452
+ incomingFilterArrayFields: (filterArrayFields || []).map(function (f) { return ({
453
+ id: f.id,
454
+ fieldPath: f.fieldPath,
455
+ lookup_as: f.lookup_as,
456
+ lookup_collection: f.lookup_collection,
457
+ lookup_local_key: f.lookup_local_key,
458
+ lookup_foreign_key: f.lookup_foreign_key
459
+ }); }),
460
+ selectedLookupFields: (selectedFields || []).filter(function (f) { return f && (f.lookup_collection || (f.fieldPath || '').includes('(Lookup')); }).map(function (f) { return ({
461
+ id: f.id,
462
+ fieldPath: f.fieldPath,
463
+ lookup_as: f.lookup_as,
464
+ lookup_collection: f.lookup_collection,
465
+ lookup_local_key: f.lookup_local_key,
466
+ lookup_foreign_key: f.lookup_foreign_key
467
+ }); }),
468
+ lookupsAdded: [],
469
+ unwindsAdded: []
470
+ };
263
471
  initialQueryMatchCondition_1 = {
264
472
  $and: []
265
473
  };
@@ -272,8 +480,8 @@ function loadReportBuilderMethods(methodManager) {
272
480
  // ]
273
481
  // });
274
482
  // });
275
- if (rootFilters.length) {
276
- rootFilters.forEach(function (filter) { return initialQueryMatchCondition_1['$and'].push(filter); });
483
+ if (rootFilters_1.length) {
484
+ rootFilters_1.forEach(function (filter) { return initialQueryMatchCondition_1['$and'].push(filter); });
277
485
  }
278
486
  // Add filter to query
279
487
  // 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) {
@@ -299,106 +507,86 @@ function loadReportBuilderMethods(methodManager) {
299
507
  foreignField: normalizeLookupField(filterField.lookup_foreign_key),
300
508
  as: filterField.lookup_as.replace(/\.\$/g, '')
301
509
  } });
510
+ lookupDebug_1.lookupsAdded.push(filterField.lookup_as.replace(/\.\$/g, ''));
302
511
  sizes_1.push(filterField.lookup_as.replace(/\.\$\./g, '_').replace(/\./g, '_'));
303
512
  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 } });
513
+ var unwindPath = '$' + filterField.lookup_as.replace(/\.\$/g, '');
514
+ query_1.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
515
+ lookupDebug_1.unwindsAdded.push(unwindPath);
305
516
  }
306
517
  }
307
518
  else {
308
519
  if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath.replace(/\./g, '_')); })) {
309
520
  sizes_1.push(fieldPath.replace(/\./g, '_'));
310
521
  query_1.push({ $addFields: (_b = {}, _b['size_' + fieldPath.replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath, []] } }, _b) });
311
- query_1.push({ '$unwind': { path: '$' + fieldPath, preserveNullAndEmptyArrays: true } });
522
+ var unwindPath = '$' + fieldPath;
523
+ query_1.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
524
+ lookupDebug_1.unwindsAdded.push(unwindPath);
312
525
  }
313
526
  }
314
527
  }
315
528
  });
316
529
  // Groups - Lookups / Sizes / Unwinds
317
530
  groupsRow.forEach(function (row) {
318
- var _a, _b;
319
- var _c;
320
- if (row.field.includes('$')) {
321
- var fieldData = row.field.split('.$');
531
+ var _a, _b, _c;
532
+ var rowField = (row && typeof row.field === 'string') ? row.field : '';
533
+ if (rowField.includes('$')) {
534
+ var fieldData = rowField.split('.$');
322
535
  var fieldPath_1 = '';
323
- for (var i = 0; i < fieldData.length - 1; i++) {
536
+ var _loop_2 = function (i) {
537
+ var _d, _e;
324
538
  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, ''); })) {
539
+ var lastSegment = fieldPath_1.split('.$')[fieldPath_1.split('.$').length - 1];
540
+ var hasLookup = !!((_a = row.treeItem) === null || _a === void 0 ? void 0 : _a.lookup_collection) || (lastSegment || '').includes('(Lookup');
541
+ 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)) {
542
+ var lookupAsRaw = row.treeItem.lookup_as || '';
543
+ var lookupAs_1 = lookupAsRaw.replace(/\.\$/g, '');
544
+ if (!query_1.some(function (a) { return a.$lookup && a.$lookup.as === lookupAs_1; })) {
327
545
  query_1.push({ $lookup: {
328
546
  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, '')
547
+ localField: normalizeLookupField(row.treeItem.lookup_local_key || ''),
548
+ foreignField: normalizeLookupField(row.treeItem.lookup_foreign_key || ''),
549
+ as: lookupAs_1
332
550
  } });
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 } });
551
+ lookupDebug_1.lookupsAdded.push(lookupAs_1);
552
+ sizes_1.push(lookupAsRaw.replace(/\.\$\./g, '_').replace(/\./g, '_'));
553
+ query_1.push({ $addFields: (_d = {}, _d['size_' + lookupAsRaw.replace(/\.\$\./g, '_').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + lookupAs_1.replace(/\./g, '_'), []] } }, _d) });
554
+ var unwindPath = '$' + lookupAs_1;
555
+ query_1.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
556
+ lookupDebug_1.unwindsAdded.push(unwindPath);
336
557
  }
337
558
  }
338
559
  else {
339
560
  if (!query_1.some(function (a) { return a.$addFields && Object.keys(a.$addFields).includes('size_' + fieldPath_1.replace(/\.\$\./g, '.').replace(/\./g, '_')); })) {
340
561
  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 } });
562
+ query_1.push({ $addFields: (_e = {}, _e['size_' + fieldPath_1.replace(/\.\$\./g, '.').replace(/\./g, '_')] = { $size: { $ifNull: ['$' + fieldPath_1.replace(/\.\$\./g, '.'), []] } }, _e) });
563
+ var unwindPath = '$' + fieldPath_1.replace(/\.\$\./g, '.');
564
+ query_1.push({ '$unwind': { path: unwindPath, preserveNullAndEmptyArrays: true } });
565
+ lookupDebug_1.unwindsAdded.push(unwindPath);
343
566
  }
344
567
  }
345
568
  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 = '';
569
+ };
355
570
  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
- }
571
+ _loop_2(i);
388
572
  }
389
573
  }
390
574
  });
391
575
  divFields_1 = { $addFields: {} };
392
576
  fieldsTotal.filter(function (a) { return a.type === 'sum'; }).forEach(function (total) {
393
577
  selectedFields.filter(function (a) { return a.fieldType === 'Number' || a.leafValueType === 'Count'; }).forEach(function (field) {
578
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
579
+ if (!fieldPath && field.leafValueType !== 'Count') {
580
+ return;
581
+ }
394
582
  var multFields = [];
395
- if (!field.fieldPath.includes('.$')) {
583
+ if (!fieldPath.includes('.$')) {
396
584
  sizes_1.forEach(function (size) {
397
585
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
398
586
  });
399
587
  }
400
588
  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) {
589
+ 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
590
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
403
591
  });
404
592
  }
@@ -410,7 +598,7 @@ function loadReportBuilderMethods(methodManager) {
410
598
  }
411
599
  else {
412
600
  divFields_1.$addFields[total.id + '_' + field.id] = {
413
- $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
601
+ $divide: ['$' + fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
414
602
  };
415
603
  }
416
604
  }
@@ -419,46 +607,58 @@ function loadReportBuilderMethods(methodManager) {
419
607
  divFields_1.$addFields[total.id + '_' + field.id] = '$count';
420
608
  }
421
609
  else {
422
- divFields_1.$addFields[total.id + '_' + field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
610
+ divFields_1.$addFields[total.id + '_' + field.id] = '$' + fieldPath.replace(/\.\$/g, '');
423
611
  }
424
612
  }
425
613
  });
426
614
  });
427
615
  selectedFields.filter(function (a) { return a.fieldType === 'Number' && a.leafValueType === 'Sum'; }).forEach(function (field) {
616
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
617
+ if (!fieldPath) {
618
+ return;
619
+ }
428
620
  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) {
621
+ 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
622
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
431
623
  });
432
624
  if (multFields.length) {
433
- divFields_1.$addFields[field.fieldPath.replace(/\.\$/g, '')] = {
434
- $divide: ['$' + field.fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
625
+ divFields_1.$addFields[fieldPath.replace(/\.\$/g, '')] = {
626
+ $divide: ['$' + fieldPath.replace(/\.\$/g, ''), { $multiply: multFields }]
435
627
  };
436
628
  }
437
629
  });
438
630
  selectedFields.filter(function (a) { return a.leafValueType === 'Count'; }).forEach(function (field) {
631
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
632
+ if (!fieldPath) {
633
+ return;
634
+ }
439
635
  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) {
636
+ 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
637
  multFields.push({ $cond: { if: { $gt: ['$size_' + size, 0] }, then: '$size_' + size, else: 1 } });
442
638
  });
443
639
  if (multFields.length) {
444
- divFields_1.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = {
640
+ divFields_1.$addFields['count_' + fieldPath.replace(/\.\$/g, '')] = {
445
641
  $divide: ['$count', { $multiply: multFields }]
446
642
  };
447
643
  }
448
644
  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;
645
+ if (reportType !== 'Dated' && sizes_1.filter(function (a) { return fieldPath.replace(/\.\$\./g, '_').includes(a); }).length) {
646
+ sizes_1.filter(function (a) { return fieldPath.replace(/\.\$\./g, '_').includes(a); }).forEach(function (size) {
647
+ divFields_1.$addFields['count_' + fieldPath.replace(/\.\$/g, '')] = '$size_' + size;
452
648
  });
453
649
  }
454
650
  else {
455
- divFields_1.$addFields['count_' + field.fieldPath.replace(/\.\$/g, '')] = '$count';
651
+ divFields_1.$addFields['count_' + fieldPath.replace(/\.\$/g, '')] = '$count';
456
652
  }
457
653
  }
458
654
  });
459
655
  fieldsTotal.filter(function (a) { return a.type === 'avg'; }).forEach(function (total) {
460
656
  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, '');
657
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
658
+ if (!fieldPath && field.leafValueType !== 'Count') {
659
+ return;
660
+ }
661
+ divFields_1.$addFields[total.id + '_' + field.id] = '$' + fieldPath.replace(/\.\$/g, '');
462
662
  });
463
663
  });
464
664
  if (Object.keys(divFields_1.$addFields).length > 0) {
@@ -542,8 +742,8 @@ function loadReportBuilderMethods(methodManager) {
542
742
  queryMatchConditionLookup_1 = {
543
743
  $and: []
544
744
  };
545
- if (lookupFilters.length) {
546
- lookupFilters.forEach(function (filter) { return queryMatchConditionLookup_1['$and'].push(filter); });
745
+ if (lookupFilters_1.length) {
746
+ lookupFilters_1.forEach(function (filter) { return queryMatchConditionLookup_1['$and'].push(filter); });
547
747
  }
548
748
  filterArrays.forEach(function (filter) {
549
749
  queryMatchConditionLookup_1['$and'].push(filter);
@@ -551,6 +751,20 @@ function loadReportBuilderMethods(methodManager) {
551
751
  if (queryMatchConditionLookup_1.$and.length) {
552
752
  query_1.push({ $match: queryMatchConditionLookup_1 });
553
753
  }
754
+ if (shouldDebugFilters) {
755
+ matchStages = query_1.filter(function (stage) { return !!stage.$match; });
756
+ console.info('RB debug: pipeline summary before aggregate', {
757
+ stageCount: query_1.length,
758
+ matchStages: matchStages,
759
+ matchStagesJson: JSON.stringify(matchStages, null, 2)
760
+ });
761
+ console.info('RB debug: join stages', {
762
+ incomingFilterArrayFields: lookupDebug_1.incomingFilterArrayFields,
763
+ selectedLookupFields: lookupDebug_1.selectedLookupFields,
764
+ lookupsAdded: lookupDebug_1.lookupsAdded,
765
+ unwindsAdded: lookupDebug_1.unwindsAdded
766
+ });
767
+ }
554
768
  queryGroup_1 = {
555
769
  _id: {}
556
770
  };
@@ -564,7 +778,10 @@ function loadReportBuilderMethods(methodManager) {
564
778
  Object.keys(rootOptions.sort).forEach(function (sortField) {
565
779
  var selField = selectedFields.find(function (a) { return a.id === sortField; });
566
780
  if (selField) {
567
- groupedSorts_1[selField.fieldPath.replace(/\.\$/g, '')] = rootOptions.sort[sortField];
781
+ var sortPath = (selField && typeof selField.fieldPath === 'string') ? selField.fieldPath.replace(/\.\$/g, '') : '';
782
+ if (sortPath) {
783
+ groupedSorts_1[sortPath] = rootOptions.sort[sortField];
784
+ }
568
785
  }
569
786
  });
570
787
  if (Object.keys(groupedSorts_1).length > 0) {
@@ -574,79 +791,93 @@ function loadReportBuilderMethods(methodManager) {
574
791
  }
575
792
  }
576
793
  }
577
- groupsRow.forEach(function (row) {
578
- queryGroup_1._id[row.id] = '$' + row.field.replace(/\.\$/g, '');
579
- if (date_field && date_interval) {
794
+ if (groupsRow.length && date_field && date_interval) {
795
+ dateFieldPath = (typeof date_field === 'string') ? date_field.replace(/\.\$/g, '') : '';
796
+ if (dateFieldPath) {
580
797
  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' } };
798
+ queryGroup_1._id['second'] = { '$second': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
799
+ queryGroup_1._id['minute'] = { '$minute': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
800
+ queryGroup_1._id['hour'] = { '$hour': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
801
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
802
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
803
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
587
804
  }
588
805
  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' } };
806
+ queryGroup_1._id['minute'] = { '$minute': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
807
+ queryGroup_1._id['hour'] = { '$hour': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
808
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
809
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
810
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
594
811
  }
595
812
  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' } };
813
+ queryGroup_1._id['hour'] = { '$hour': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
814
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
815
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
816
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
600
817
  }
601
818
  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' } };
819
+ queryGroup_1._id['day'] = { '$dayOfMonth': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
820
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
821
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
605
822
  }
606
823
  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' } };
824
+ queryGroup_1._id['week'] = { '$isoWeek': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
825
+ queryGroup_1._id['year'] = { '$isoWeekYear': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
609
826
  }
610
827
  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' } };
828
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
829
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
613
830
  }
614
831
  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' } };
832
+ queryGroup_1._id['month'] = { '$month': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
833
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
617
834
  }
618
835
  else if (date_interval === 'Yearly') {
619
- queryGroup_1._id['year'] = { '$year': { 'date': '$' + date_field.replace(/\.\$/g, ''), 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
836
+ queryGroup_1._id['year'] = { '$year': { 'date': '$' + dateFieldPath, 'timezone': process.env.TZ_CLIENT || 'America/Chicago' } };
620
837
  }
621
838
  }
839
+ }
840
+ groupsRow.forEach(function (row) {
841
+ var rowField = (row && typeof row.field === 'string') ? row.field : '';
842
+ if (!rowField || !(row === null || row === void 0 ? void 0 : row.id)) {
843
+ return;
844
+ }
845
+ queryGroup_1._id[row.id] = '$' + rowField.replace(/\.\$/g, '');
622
846
  });
623
847
  selectedFields.forEach(function (field) {
848
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
849
+ if (!fieldPath) {
850
+ if (field.leafValueType === 'Count') {
851
+ queryGroup_1[field.id] = { '$sum': 1 };
852
+ }
853
+ return;
854
+ }
624
855
  if (field.leafValueType === 'Average') {
625
- queryGroup_1[field.id] = { '$avg': '$' + field.fieldPath.replace(/\.\$/g, '') };
856
+ queryGroup_1[field.id] = { '$avg': '$' + fieldPath.replace(/\.\$/g, '') };
626
857
  }
627
858
  else if (field.leafValueType === 'Sum') {
628
- queryGroup_1[field.id] = { '$sum': '$' + field.fieldPath.replace(/\.\$/g, '') };
859
+ queryGroup_1[field.id] = { '$sum': '$' + fieldPath.replace(/\.\$/g, '') };
629
860
  }
630
861
  else if (field.leafValueType === 'Count') {
631
- queryGroup_1[field.id] = { '$sum': '$count_' + field.fieldPath.replace(/\.\$/g, '') };
862
+ queryGroup_1[field.id] = { '$sum': '$count_' + fieldPath.replace(/\.\$/g, '') };
632
863
  }
633
864
  else if (field.leafValueType === 'Minimum') {
634
- queryGroup_1[field.id] = { '$min': '$' + field.fieldPath.replace(/\.\$/g, '') };
865
+ queryGroup_1[field.id] = { '$min': '$' + fieldPath.replace(/\.\$/g, '') };
635
866
  }
636
867
  else if (field.leafValueType === 'Maximum') {
637
- queryGroup_1[field.id] = { '$max': '$' + field.fieldPath.replace(/\.\$/g, '') };
868
+ queryGroup_1[field.id] = { '$max': '$' + fieldPath.replace(/\.\$/g, '') };
638
869
  }
639
870
  else if (field.leafValueType === 'First') {
640
- queryGroup_1[field.id] = { '$first': '$' + field.fieldPath.replace(/\.\$/g, '') };
871
+ queryGroup_1[field.id] = { '$first': '$' + fieldPath.replace(/\.\$/g, '') };
641
872
  }
642
873
  else if (field.leafValueType === 'Last') {
643
- queryGroup_1[field.id] = { '$last': '$' + field.fieldPath.replace(/\.\$/g, '') };
874
+ queryGroup_1[field.id] = { '$last': '$' + fieldPath.replace(/\.\$/g, '') };
644
875
  }
645
876
  else if (field.leafValueType === 'Unique') {
646
- queryGroup_1[field.id] = { '$addToSet': '$' + field.fieldPath.replace(/\.\$/g, '') };
877
+ queryGroup_1[field.id] = { '$addToSet': '$' + fieldPath.replace(/\.\$/g, '') };
647
878
  }
648
879
  else {
649
- queryGroup_1[field.id] = { '$push': { $ifNull: ['$' + field.fieldPath.replace(/\.\$/g, ''), null] } };
880
+ queryGroup_1[field.id] = { '$push': { $ifNull: ['$' + fieldPath.replace(/\.\$/g, ''), null] } };
650
881
  }
651
882
  });
652
883
  customFields.forEach(function (cust) {
@@ -703,23 +934,27 @@ function loadReportBuilderMethods(methodManager) {
703
934
  _id: 1
704
935
  };
705
936
  selectedFields.forEach(function (field) {
937
+ var fieldPath = (field && typeof field.fieldPath === 'string') ? field.fieldPath : '';
938
+ if (!fieldPath && field.leafValueType !== 'Count') {
939
+ return;
940
+ }
706
941
  if (field.leafValueType === 'Average') {
707
- queryProjection_1[field.id] = { $avg: '$' + field.fieldPath.replace(/\.\$/g, '') };
942
+ queryProjection_1[field.id] = { $avg: '$' + fieldPath.replace(/\.\$/g, '') };
708
943
  }
709
944
  else if (field.leafValueType === 'Sum') {
710
- queryProjection_1[field.id] = { $sum: '$' + field.fieldPath.replace(/\.\$/g, '') };
945
+ queryProjection_1[field.id] = { $sum: '$' + fieldPath.replace(/\.\$/g, '') };
711
946
  }
712
947
  else if (field.leafValueType === 'Count') {
713
948
  queryProjection_1[field.id] = { $sum: 1 };
714
949
  }
715
950
  else if (field.leafValueType === 'Minimum') {
716
- queryProjection_1[field.id] = { $min: '$' + field.fieldPath.replace(/\.\$/g, '') };
951
+ queryProjection_1[field.id] = { $min: '$' + fieldPath.replace(/\.\$/g, '') };
717
952
  }
718
953
  else if (field.leafValueType === 'Maximum') {
719
- queryProjection_1[field.id] = { $max: '$' + field.fieldPath.replace(/\.\$/g, '') };
954
+ queryProjection_1[field.id] = { $max: '$' + fieldPath.replace(/\.\$/g, '') };
720
955
  }
721
956
  else {
722
- queryProjection_1[field.id] = '$' + field.fieldPath.replace(/\.\$/g, '');
957
+ queryProjection_1[field.id] = '$' + fieldPath.replace(/\.\$/g, '');
723
958
  }
724
959
  });
725
960
  customFields.forEach(function (cust) {
@@ -755,6 +990,13 @@ function loadReportBuilderMethods(methodManager) {
755
990
  });
756
991
  });
757
992
  }
993
+ // Debug only: expose raw lookup payloads for inspection
994
+ if (shouldDebugFilters && lookupAliases_1 && lookupAliases_1.size) {
995
+ Array.from(lookupAliases_1).forEach(function (alias) {
996
+ var debugKey = '__debug_lookup_' + alias.replace(/\s+/g, '_').replace(/\./g, '_');
997
+ queryProjection_1[debugKey] = '$' + alias.replace(/\.\$/g, '');
998
+ });
999
+ }
758
1000
  query_1.push({ $project: queryProjection_1 });
759
1001
  }
760
1002
  // SORT
@@ -763,10 +1005,10 @@ function loadReportBuilderMethods(methodManager) {
763
1005
  }
764
1006
  if (reportType === 'Group' && groupsRow.length > 1) {
765
1007
  _loop_1 = function (i) {
766
- var _c;
1008
+ var _d;
767
1009
  var projQuery = { _id: 1 };
768
1010
  projQuery[groupsRow[i].id] = {
769
- _id: (_c = {}, _c[groupsRow[i].id] = '$_id.' + groupsRow[i].id, _c)
1011
+ _id: (_d = {}, _d[groupsRow[i].id] = '$_id.' + groupsRow[i].id, _d)
770
1012
  };
771
1013
  if (i === groupsRow.length - 1) {
772
1014
  selectedFields.forEach(function (field) {
@@ -834,44 +1076,69 @@ function loadReportBuilderMethods(methodManager) {
834
1076
  _loop_1(i);
835
1077
  }
836
1078
  }
837
- res_1 = null;
838
- _b.label = 2;
839
- case 2:
840
- _b.trys.push([2, 4, , 5]);
1079
+ res_2 = null;
1080
+ _c.label = 7;
1081
+ case 7:
1082
+ _c.trys.push([7, 9, , 10]);
841
1083
  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) {
1084
+ case 8:
1085
+ res_2 = _c.sent();
1086
+ return [3 /*break*/, 10];
1087
+ case 9:
1088
+ err_2 = _c.sent();
1089
+ console.log(err_2);
1090
+ return [3 /*break*/, 10];
1091
+ case 10:
1092
+ if (shouldDebugFilters) {
1093
+ console.info('RB debug: aggregate result', {
1094
+ count: Array.isArray(res_2) ? res_2.length : 0
1095
+ });
1096
+ sample = Array.isArray(res_2) ? res_2.slice(0, 3) : [];
1097
+ sampleSlim = sample.map(function (r) {
1098
+ var out = { _id: r === null || r === void 0 ? void 0 : r._id };
1099
+ (selectedFields || []).forEach(function (f) {
1100
+ if (r && Object.prototype.hasOwnProperty.call(r, f.id)) {
1101
+ out[f.id] = r[f.id];
1102
+ }
1103
+ });
1104
+ // Also surface raw lookup payloads to debug missing data
1105
+ Array.from(lookupAliases_1 || []).forEach(function (alias) {
1106
+ var debugKey = '__debug_lookup_' + alias.replace(/\s+/g, '_').replace(/\./g, '_');
1107
+ if (r) {
1108
+ out[debugKey] = Object.prototype.hasOwnProperty.call(r, debugKey) ? r[debugKey] : '__missing__';
1109
+ // also show original alias if present
1110
+ out["raw_".concat(alias)] = Object.prototype.hasOwnProperty.call(r, alias) ? r[alias] : '__missing__';
1111
+ }
1112
+ });
1113
+ return out;
1114
+ });
1115
+ console.info('RB debug: sample results', JSON.stringify(sampleSlim, null, 2));
1116
+ }
1117
+ tmpTotals_2 = {};
1118
+ if (res_2) {
852
1119
  fieldsTotal.forEach(function (totField) {
853
1120
  selectedFields.filter(function (b) { return b.fieldType === 'Number' || b.leafValueType === 'Count'; }).forEach(function (selField) {
854
1121
  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);
1122
+ 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
1123
  }
857
1124
  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);
1125
+ 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
1126
  }
860
1127
  });
861
1128
  customFields.forEach(function (custField) {
862
1129
  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);
1130
+ 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
1131
  }
865
1132
  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);
1133
+ 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
1134
  }
868
1135
  });
869
1136
  });
870
1137
  }
871
1138
  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
1139
+ count: res_2 ? res_2.length : 0,
1140
+ results: res_2 ? (rootOptions.limit ? res_2.splice(0, rootOptions.limit) : res_2) : [],
1141
+ totals: tmpTotals_2
875
1142
  }];
876
1143
  return [2 /*return*/, tmpRes];
877
1144
  }
@@ -1045,7 +1312,9 @@ function splitFiltersByLookup(filters, lookupAliases) {
1045
1312
  var rootFilters = [];
1046
1313
  var lookupFilters = [];
1047
1314
  (filters || []).forEach(function (filter) {
1048
- if (filterContainsLookup(filter, lookupAliases)) {
1315
+ var summary = summarizeFilterTargets(filter, lookupAliases);
1316
+ if (summary.hasLookup) {
1317
+ // If the filter mixes root + lookup, keep it together in lookupFilters so it stays a single $match/$or
1049
1318
  lookupFilters.push(filter);
1050
1319
  }
1051
1320
  else {
@@ -1054,17 +1323,33 @@ function splitFiltersByLookup(filters, lookupAliases) {
1054
1323
  });
1055
1324
  return { rootFilters: rootFilters, lookupFilters: lookupFilters };
1056
1325
  }
1057
- function filterContainsLookup(filter, lookupAliases) {
1326
+ function summarizeFilterTargets(filter, lookupAliases) {
1327
+ var result = { hasLookup: false, hasRoot: false };
1058
1328
  if (!filter || typeof filter !== 'object') {
1059
- return false;
1329
+ return result;
1060
1330
  }
1061
- return Object.keys(filter).some(function (key) {
1331
+ Object.keys(filter).forEach(function (key) {
1062
1332
  if (key === '$or' || key === '$and') {
1063
1333
  var branch = filter[key];
1064
- return Array.isArray(branch) && branch.some(function (child) { return filterContainsLookup(child, lookupAliases); });
1334
+ if (Array.isArray(branch)) {
1335
+ branch.forEach(function (child) {
1336
+ var childSummary = summarizeFilterTargets(child, lookupAliases);
1337
+ result.hasLookup = result.hasLookup || childSummary.hasLookup;
1338
+ result.hasRoot = result.hasRoot || childSummary.hasRoot;
1339
+ });
1340
+ }
1341
+ }
1342
+ else {
1343
+ var isLookup = isLookupPath(key, lookupAliases);
1344
+ if (isLookup) {
1345
+ result.hasLookup = true;
1346
+ }
1347
+ else {
1348
+ result.hasRoot = true;
1349
+ }
1065
1350
  }
1066
- return isLookupPath(key, lookupAliases);
1067
1351
  });
1352
+ return result;
1068
1353
  }
1069
1354
  function isLookupPath(path, lookupAliases) {
1070
1355
  if (!path) {
@@ -1086,6 +1371,222 @@ function extractLookupAlias(path) {
1086
1371
  function normalizeLookupAlias(alias) {
1087
1372
  return (alias || '').replace(/\.\$/g, '').trim();
1088
1373
  }
1374
+ // Helpers to support union-based joins (collection_joins without local/foreign key)
1375
+ function stripAliasFromPath(path, alias) {
1376
+ if (!path) {
1377
+ return path;
1378
+ }
1379
+ var cleanAlias = alias.replace(/\.\$/g, '');
1380
+ var cleanPath = path.replace(/\.\$/g, '');
1381
+ if (cleanPath.startsWith(cleanAlias + '.')) {
1382
+ return cleanPath.substring(cleanAlias.length + 1);
1383
+ }
1384
+ return cleanPath;
1385
+ }
1386
+ function buildCollectionPipeline(collectionName, alias, selectedFields, filters, filterArrays, isRoot) {
1387
+ if (selectedFields === void 0) { selectedFields = []; }
1388
+ if (filters === void 0) { filters = []; }
1389
+ if (filterArrays === void 0) { filterArrays = []; }
1390
+ if (isRoot === void 0) { isRoot = false; }
1391
+ var pipeline = [];
1392
+ var matchClauses = [];
1393
+ var matchArrayClauses = [];
1394
+ var targetAlias = isRoot ? '' : alias.replace(/\.\$/g, '');
1395
+ var mapFilterForCollection = function (filterObj, toArray) {
1396
+ if (!filterObj || typeof filterObj !== 'object') {
1397
+ return;
1398
+ }
1399
+ var mapped = mapFilterPaths(filterObj, targetAlias, isRoot);
1400
+ if (mapped) {
1401
+ (toArray ? matchArrayClauses : matchClauses).push(mapped);
1402
+ }
1403
+ };
1404
+ (filters || []).forEach(function (f) { return mapFilterForCollection(f, false); });
1405
+ (filterArrays || []).forEach(function (f) { return mapFilterForCollection(f, true); });
1406
+ if (matchClauses.length || matchArrayClauses.length) {
1407
+ var match = { $and: __spreadArray(__spreadArray([], __read(matchClauses), false), __read(matchArrayClauses), false) };
1408
+ pipeline.push({ $match: match });
1409
+ if (process.env.NODE_ENV !== 'production') {
1410
+ console.info('RB debug: collection pipeline match', {
1411
+ collection: collectionName,
1412
+ alias: targetAlias || collectionName,
1413
+ matchJson: JSON.stringify(match, null, 2)
1414
+ });
1415
+ }
1416
+ }
1417
+ // Projection mapping selected fields for this collection
1418
+ var projection = { _id: 1, __rb_collection: targetAlias || collectionName };
1419
+ (selectedFields || [])
1420
+ .filter(function (f) { return isFieldForCollection(f, collectionName, targetAlias); })
1421
+ .forEach(function (f) {
1422
+ var mappedPath = stripAliasFromPath(f.fieldPath || '', targetAlias || f.lookup_as || '');
1423
+ if (f.leafValueType === 'Average') {
1424
+ projection[f.id] = { $avg: '$' + mappedPath };
1425
+ }
1426
+ else if (f.leafValueType === 'Sum') {
1427
+ projection[f.id] = { $sum: '$' + mappedPath };
1428
+ }
1429
+ else if (f.leafValueType === 'Count') {
1430
+ projection[f.id] = { $sum: 1 };
1431
+ }
1432
+ else if (f.leafValueType === 'Minimum') {
1433
+ projection[f.id] = { $min: '$' + mappedPath };
1434
+ }
1435
+ else if (f.leafValueType === 'Maximum') {
1436
+ projection[f.id] = { $max: '$' + mappedPath };
1437
+ }
1438
+ else {
1439
+ projection[f.id] = '$' + mappedPath;
1440
+ }
1441
+ });
1442
+ pipeline.push({ $project: projection });
1443
+ return pipeline;
1444
+ }
1445
+ function isFieldForCollection(field, collectionName, alias) {
1446
+ if (!field) {
1447
+ return false;
1448
+ }
1449
+ // Root collection check
1450
+ if (!alias) {
1451
+ return field.collection_name === collectionName && (!field.lookup_collection || field.lookup_collection === '');
1452
+ }
1453
+ // Joined collection check
1454
+ return field.lookup_collection === collectionName || (field.lookup_as && field.lookup_as.replace(/\.\$/g, '') === alias);
1455
+ }
1456
+ function mapFilterPaths(filter, alias, isRoot) {
1457
+ if (!filter || typeof filter !== 'object') {
1458
+ return null;
1459
+ }
1460
+ if (Array.isArray(filter)) {
1461
+ return filter.map(function (f) { return mapFilterPaths(f, alias, isRoot); });
1462
+ }
1463
+ if (filter.$or) {
1464
+ var mapped = filter.$or.map(function (f) { return mapFilterPaths(f, alias, isRoot); }).filter(Boolean);
1465
+ return mapped.length ? { $or: mapped } : null;
1466
+ }
1467
+ if (filter.$and) {
1468
+ var mapped = filter.$and.map(function (f) { return mapFilterPaths(f, alias, isRoot); }).filter(Boolean);
1469
+ return mapped.length ? { $and: mapped } : null;
1470
+ }
1471
+ var out = {};
1472
+ Object.keys(filter).forEach(function (key) {
1473
+ var cleanKey = key.replace(/\.\$/g, '');
1474
+ if (!alias) {
1475
+ // root collection: ignore keys that start with a lookup alias
1476
+ if (cleanKey.includes('(Lookup')) {
1477
+ return;
1478
+ }
1479
+ if (lookupAliasMatches(cleanKey, alias)) {
1480
+ return;
1481
+ }
1482
+ out[cleanKey] = filter[key];
1483
+ }
1484
+ else {
1485
+ if (cleanKey.startsWith(alias + '.')) {
1486
+ out[cleanKey.substring(alias.length + 1)] = filter[key];
1487
+ }
1488
+ }
1489
+ });
1490
+ return Object.keys(out).length ? out : null;
1491
+ }
1492
+ function lookupAliasMatches(path, alias) {
1493
+ if (!path || !alias) {
1494
+ return false;
1495
+ }
1496
+ return path.startsWith(alias + '.') || path === alias;
1497
+ }
1498
+ function buildLayoutSortSpec(sortSpec, selectedFields) {
1499
+ if (sortSpec === void 0) { sortSpec = {}; }
1500
+ if (selectedFields === void 0) { selectedFields = []; }
1501
+ var outSort = __assign({}, sortSpec);
1502
+ var addFields = {};
1503
+ Object.keys(sortSpec || {}).forEach(function (key) {
1504
+ if (!key.startsWith('layout_col_')) {
1505
+ return;
1506
+ }
1507
+ var normalized = key.replace(/^layout_col_/, '');
1508
+ var parts = normalized.split('_');
1509
+ var idx = parseInt(parts[parts.length - 1], 10);
1510
+ if (isNaN(idx)) {
1511
+ return;
1512
+ }
1513
+ 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);
1514
+ if (!layoutFields.length) {
1515
+ return;
1516
+ }
1517
+ // Build nested $ifNull chain to coalesce across layout column targets
1518
+ var coalesce = '';
1519
+ for (var i = layoutFields.length - 1; i >= 0; i--) {
1520
+ var fieldPath = '$' + layoutFields[i];
1521
+ if (i === layoutFields.length - 1) {
1522
+ coalesce = fieldPath;
1523
+ }
1524
+ else {
1525
+ coalesce = { $ifNull: [fieldPath, coalesce] };
1526
+ }
1527
+ }
1528
+ var sortKey = 'sort_' + key;
1529
+ addFields[sortKey] = coalesce;
1530
+ delete outSort[key];
1531
+ outSort[sortKey] = sortSpec[key];
1532
+ });
1533
+ return { sortSpec: outSort, addFields: addFields };
1534
+ }
1535
+ function remapFiltersToIds(filters, selectedFields) {
1536
+ if (filters === void 0) { filters = []; }
1537
+ if (selectedFields === void 0) { selectedFields = []; }
1538
+ var byPath = new Map();
1539
+ var layoutMap = new Map();
1540
+ (selectedFields || []).forEach(function (f) {
1541
+ if ((f === null || f === void 0 ? void 0 : f.fieldPath) && (f === null || f === void 0 ? void 0 : f.id)) {
1542
+ byPath.set(f.fieldPath.replace(/\.\$/g, ''), f.id);
1543
+ }
1544
+ if (typeof (f === null || f === void 0 ? void 0 : f.layoutColumnIndex) !== 'undefined') {
1545
+ var arr = layoutMap.get(f.layoutColumnIndex) || [];
1546
+ arr.push(f.id);
1547
+ layoutMap.set(f.layoutColumnIndex, arr);
1548
+ }
1549
+ });
1550
+ var remapObj = function (obj) {
1551
+ if (!obj || typeof obj !== 'object') {
1552
+ return obj;
1553
+ }
1554
+ if (Array.isArray(obj)) {
1555
+ return obj.map(remapObj);
1556
+ }
1557
+ if (obj.$or) {
1558
+ var mapped = obj.$or.map(remapObj).filter(Boolean);
1559
+ return mapped.length ? { $or: mapped } : null;
1560
+ }
1561
+ if (obj.$and) {
1562
+ var mapped = obj.$and.map(remapObj).filter(Boolean);
1563
+ return mapped.length ? { $and: mapped } : null;
1564
+ }
1565
+ var out = {};
1566
+ Object.keys(obj).forEach(function (key) {
1567
+ var cleanKey = key.replace(/\.\$/g, '');
1568
+ if (cleanKey.startsWith('layout_col_')) {
1569
+ // map to all field ids in that layout column index
1570
+ var normalized = cleanKey.replace(/^layout_col_/, '');
1571
+ var parts = normalized.split('_');
1572
+ var idx = parseInt(parts[parts.length - 1], 10);
1573
+ var targets = layoutMap.get(idx) || [];
1574
+ if (targets.length) {
1575
+ var mappedVal_1 = remapObj(obj[key]);
1576
+ out.$or = targets.map(function (id) {
1577
+ var _a;
1578
+ return (_a = {}, _a[id] = mappedVal_1, _a);
1579
+ });
1580
+ return;
1581
+ }
1582
+ }
1583
+ var mappedKey = byPath.get(cleanKey) || cleanKey;
1584
+ out[mappedKey] = remapObj(obj[key]);
1585
+ });
1586
+ return Object.keys(out).length ? out : null;
1587
+ };
1588
+ return (filters || []).map(remapObj).filter(Boolean);
1589
+ }
1089
1590
  function expandLayoutColumnFilters(filters, selectedFields) {
1090
1591
  if (filters === void 0) { filters = []; }
1091
1592
  if (selectedFields === void 0) { selectedFields = []; }