@resolveio/server-lib 20.12.63 → 20.12.64

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.
@@ -87,7 +87,6 @@ exports.loadCronJobMethods = loadCronJobMethods;
87
87
  var Excel = require("exceljs");
88
88
  var moment = require("moment-timezone");
89
89
  var simpl_schema_1 = require("simpl-schema");
90
- var XLSX = require("xlsx");
91
90
  var cron_job_collection_1 = require("../collections/cron-job.collection");
92
91
  var file_collection_1 = require("../collections/file.collection");
93
92
  var report_builder_report_collection_1 = require("../collections/report-builder-report.collection");
@@ -270,6 +269,401 @@ function resolveFieldRefToLeafId(fieldRef, report) {
270
269
  }
271
270
  return fieldRef;
272
271
  }
272
+ function buildCollectionKeysFromReport(report) {
273
+ var keys = [];
274
+ if (report === null || report === void 0 ? void 0 : report.collection_root) {
275
+ keys.push(report.collection_root);
276
+ }
277
+ ((report === null || report === void 0 ? void 0 : report.collection_joins) || []).forEach(function (join) {
278
+ if (!join) {
279
+ return;
280
+ }
281
+ var alias = (join.alias || '').trim();
282
+ if (alias && !keys.includes(alias)) {
283
+ keys.push(alias);
284
+ }
285
+ else if (join.collection && !keys.includes(join.collection)) {
286
+ keys.push(join.collection);
287
+ }
288
+ });
289
+ return keys.length ? keys : ['root'];
290
+ }
291
+ function buildLayoutColumnsFromFields(report, fields) {
292
+ if (fields === void 0) { fields = []; }
293
+ var keys = buildCollectionKeysFromReport(report);
294
+ return (fields || []).map(function (field, index) {
295
+ var header = field.columnName || field.fieldName || "Column ".concat(index + 1);
296
+ var isCustom = (((field === null || field === void 0 ? void 0 : field.id) || (field === null || field === void 0 ? void 0 : field.fieldPath) || '') + '').startsWith('c_') || (field === null || field === void 0 ? void 0 : field.fieldPathName) === 'Custom Field';
297
+ var mappings = keys.map(function (key) {
298
+ var matchesKey = key === report.collection_root
299
+ ? (field.collection_name === report.collection_root || isCustom)
300
+ : (key === (field.lookup_as || '').trim()) || key === field.collection_name;
301
+ if (matchesKey) {
302
+ return {
303
+ collection: key,
304
+ mode: 'variable',
305
+ fieldPath: field.fieldPath || '',
306
+ fieldId: field.id || "f_layout_".concat(index),
307
+ text: '',
308
+ leafValueType: field.leafValueType || 'Value',
309
+ leafFormatType: field.leafFormatType || ''
310
+ };
311
+ }
312
+ return {
313
+ collection: key,
314
+ mode: 'text',
315
+ fieldPath: '',
316
+ fieldId: '',
317
+ text: '',
318
+ leafValueType: 'Value',
319
+ leafFormatType: ''
320
+ };
321
+ });
322
+ return {
323
+ id: field.id ? "layout_".concat(field.id) : "layout_".concat(index),
324
+ header: header,
325
+ mappings: mappings
326
+ };
327
+ });
328
+ }
329
+ function ensureLayoutHasCustomField(report, layout, customId, columnName, leafValueType) {
330
+ if (layout === void 0) { layout = []; }
331
+ if (!layout || !customId) {
332
+ return;
333
+ }
334
+ var hasCustomField = (layout || []).some(function (col) { return ((col === null || col === void 0 ? void 0 : col.mappings) || []).some(function (m) {
335
+ return (m === null || m === void 0 ? void 0 : m.mode) === 'variable' && (m.fieldId === customId || m.fieldPath === customId);
336
+ }); });
337
+ if (hasCustomField) {
338
+ return;
339
+ }
340
+ var keys = buildCollectionKeysFromReport(report);
341
+ var rootKey = (report === null || report === void 0 ? void 0 : report.collection_root) || '';
342
+ var header = columnName || customId;
343
+ var mappings = keys.map(function (key) {
344
+ if (key === rootKey) {
345
+ return {
346
+ collection: key,
347
+ mode: 'variable',
348
+ fieldPath: customId,
349
+ fieldId: customId,
350
+ text: '',
351
+ leafValueType: leafValueType || 'Value',
352
+ leafFormatType: 'Number'
353
+ };
354
+ }
355
+ return {
356
+ collection: key,
357
+ mode: 'text',
358
+ fieldPath: '',
359
+ fieldId: '',
360
+ text: '',
361
+ leafValueType: 'Value',
362
+ leafFormatType: ''
363
+ };
364
+ });
365
+ layout.push({
366
+ id: "layout_".concat(customId),
367
+ header: header,
368
+ mappings: mappings
369
+ });
370
+ }
371
+ function ensureLayoutIncludesCustomFields(report, layout) {
372
+ if (layout === void 0) { layout = []; }
373
+ var fieldsCustom = (report === null || report === void 0 ? void 0 : report.fields_custom) || [];
374
+ if (!fieldsCustom.length) {
375
+ return layout;
376
+ }
377
+ fieldsCustom.forEach(function (custom) {
378
+ ensureLayoutHasCustomField(report, layout, custom === null || custom === void 0 ? void 0 : custom.id, custom === null || custom === void 0 ? void 0 : custom.columnName, custom === null || custom === void 0 ? void 0 : custom.leafValueType);
379
+ });
380
+ return layout;
381
+ }
382
+ function getLayoutColumnsFromReport(report) {
383
+ var layout = [];
384
+ if ((report === null || report === void 0 ? void 0 : report.fields_layout) && report.fields_layout.length) {
385
+ layout = (0, common_1.deepCopy)(report.fields_layout);
386
+ }
387
+ else {
388
+ layout = buildLayoutColumnsFromFields(report, (report === null || report === void 0 ? void 0 : report.fields_selected) || []);
389
+ }
390
+ return ensureLayoutIncludesCustomFields(report, layout);
391
+ }
392
+ function syncSelectedFieldsFromLayout(report, layoutColumns) {
393
+ if (layoutColumns === void 0) { layoutColumns = []; }
394
+ var fields = [];
395
+ var sourceFields = (0, common_1.deepCopy)((report === null || report === void 0 ? void 0 : report.fields_selected) || []);
396
+ var byId = new Map();
397
+ var byPath = new Map();
398
+ sourceFields.forEach(function (f) {
399
+ if (f === null || f === void 0 ? void 0 : f.id) {
400
+ byId.set(f.id, f);
401
+ }
402
+ if (f === null || f === void 0 ? void 0 : f.fieldPath) {
403
+ byPath.set(f.fieldPath, f);
404
+ }
405
+ });
406
+ layoutColumns.forEach(function (col, colIndex) {
407
+ (col.mappings || []).forEach(function (map, mapIndex) {
408
+ if (map.mode === 'variable' && map.fieldPath) {
409
+ var baseField = byId.get(map.fieldId) || byPath.get(map.fieldPath);
410
+ if (!baseField) {
411
+ return;
412
+ }
413
+ var clone = (0, common_1.deepCopy)(baseField);
414
+ clone.columnName = col.header || baseField.columnName || baseField.fieldPathName || 'Column';
415
+ clone.show = (typeof map.show === 'boolean')
416
+ ? map.show
417
+ : (typeof baseField.show === 'boolean' ? baseField.show : true);
418
+ clone.leafValueType = map.leafValueType || clone.leafValueType;
419
+ clone.leafFormatType = map.leafFormatType || clone.leafFormatType;
420
+ clone.id = map.fieldId || clone.id || "f_layout_".concat(colIndex, "_").concat(mapIndex);
421
+ clone.layoutCollection = map.collection;
422
+ clone.layoutColumnIndex = colIndex;
423
+ if (!map.fieldId) {
424
+ map.fieldId = clone.id;
425
+ }
426
+ fields.push(clone);
427
+ }
428
+ });
429
+ });
430
+ return fields;
431
+ }
432
+ function materializeLayoutRow(report, layoutColumns, selectedFields, row) {
433
+ var materialized = { _id: row === null || row === void 0 ? void 0 : row._id };
434
+ var hasDataForCollection = function (collection) {
435
+ if (!collection) {
436
+ return false;
437
+ }
438
+ return (selectedFields || []).some(function (f) {
439
+ return f.layoutCollection === collection &&
440
+ row &&
441
+ Object.prototype.hasOwnProperty.call(row, f.id) &&
442
+ row[f.id] !== undefined &&
443
+ row[f.id] !== null &&
444
+ row[f.id] !== '';
445
+ });
446
+ };
447
+ (layoutColumns || []).forEach(function (col, colIndex) {
448
+ var values = [];
449
+ (col.mappings || []).forEach(function (map) {
450
+ if (map.mode === 'text' && map.text) {
451
+ if (hasDataForCollection(map.collection)) {
452
+ values.push({ collection: map.collection, value: map.text });
453
+ }
454
+ }
455
+ else if (map.mode === 'variable' && map.fieldId && row && Object.prototype.hasOwnProperty.call(row, map.fieldId)) {
456
+ values.push({ collection: map.collection, value: row[map.fieldId] });
457
+ }
458
+ });
459
+ materialized[colIndex] = values;
460
+ });
461
+ return materialized;
462
+ }
463
+ function getLayoutCellExportValue(report, layoutRow, colIndex) {
464
+ if (!layoutRow || layoutRow[colIndex] === undefined || layoutRow[colIndex] === null) {
465
+ return '';
466
+ }
467
+ var cellValues = Array.isArray(layoutRow[colIndex]) ? layoutRow[colIndex] : [layoutRow[colIndex]];
468
+ var filtered = cellValues.filter(function (v) { return v !== undefined && v !== null && v.value !== undefined && v.value !== null && v.value !== ''; });
469
+ if (!filtered.length) {
470
+ return '';
471
+ }
472
+ var rootCollection = report === null || report === void 0 ? void 0 : report.collection_root;
473
+ var preferred = filtered.find(function (v) { return v.collection === rootCollection; }) || filtered[0];
474
+ var value = preferred === null || preferred === void 0 ? void 0 : preferred.value;
475
+ if (value === undefined || value === null) {
476
+ return '';
477
+ }
478
+ if (Array.isArray(value)) {
479
+ return value;
480
+ }
481
+ return typeof value === 'string' ? value.trim().replace(/\t/g, '').replace(/\n/g, '') : value;
482
+ }
483
+ function getPrimaryFieldForLayoutColumn(col, selectedFields) {
484
+ if (!(col === null || col === void 0 ? void 0 : col.mappings)) {
485
+ return null;
486
+ }
487
+ var target = col.mappings.find(function (m) { return m.mode === 'variable' && m.fieldId; });
488
+ if (!target) {
489
+ return null;
490
+ }
491
+ return (selectedFields || []).find(function (f) { return f.id === target.fieldId; }) || null;
492
+ }
493
+ var STRING_DATE_FORMATS = [
494
+ moment.ISO_8601,
495
+ 'MM/DD/YYYY',
496
+ 'M/D/YYYY',
497
+ 'MM/DD/YYYY h:mm A',
498
+ 'M/D/YYYY h:mm A',
499
+ 'MM/DD/YYYY hh:mm A',
500
+ 'M/D/YYYY hh:mm A',
501
+ 'MM/DD/YYYY h:mm:ss A',
502
+ 'M/D/YYYY h:mm:ss A',
503
+ 'MM/DD/YYYY hh:mm:ss A',
504
+ 'M/D/YYYY hh:mm:ss A',
505
+ 'MM/DD/YYYY H:mm',
506
+ 'M/D/YYYY H:mm',
507
+ 'MM/DD/YYYY HH:mm',
508
+ 'M/D/YYYY HH:mm',
509
+ 'MM/DD/YYYY H:mm:ss',
510
+ 'M/D/YYYY H:mm:ss',
511
+ 'MM/DD/YYYY HH:mm:ss',
512
+ 'M/D/YYYY HH:mm:ss'
513
+ ];
514
+ function parseMoment(value) {
515
+ if (value === null || value === undefined) {
516
+ return null;
517
+ }
518
+ if (moment.isMoment(value)) {
519
+ return value;
520
+ }
521
+ if (value instanceof Date || typeof value === 'number') {
522
+ var m_1 = moment(value);
523
+ return m_1.isValid() ? m_1 : null;
524
+ }
525
+ if (typeof value === 'string' || value instanceof String) {
526
+ var str = "".concat(value).trim();
527
+ if (!str) {
528
+ return null;
529
+ }
530
+ var m_2 = moment(str, STRING_DATE_FORMATS, true);
531
+ if (m_2.isValid()) {
532
+ return m_2;
533
+ }
534
+ var loose = moment(str, STRING_DATE_FORMATS, false);
535
+ if (loose.isValid()) {
536
+ return loose;
537
+ }
538
+ var jsDateStr = str.replace(/\s*\([^)]*\)\s*$/, '');
539
+ var jsDate = moment(jsDateStr, 'ddd MMM DD YYYY HH:mm:ss [GMT]ZZ', true);
540
+ if (jsDate.isValid()) {
541
+ return jsDate;
542
+ }
543
+ if (/[T:\\/\\-]/.test(str) || /GMT|UTC/i.test(str)) {
544
+ var fallback = moment(str);
545
+ return fallback.isValid() ? fallback : null;
546
+ }
547
+ return null;
548
+ }
549
+ var m = moment(value);
550
+ return m.isValid() ? m : null;
551
+ }
552
+ function parseExcelNumber(value) {
553
+ if (typeof value === 'number') {
554
+ return Number.isFinite(value) ? value : null;
555
+ }
556
+ if (typeof value !== 'string') {
557
+ return null;
558
+ }
559
+ var s = value.trim();
560
+ if (!s) {
561
+ return null;
562
+ }
563
+ var negative = false;
564
+ var parenMatch = s.match(/^\((.*)\)$/);
565
+ if (parenMatch) {
566
+ negative = true;
567
+ s = parenMatch[1].trim();
568
+ }
569
+ s = s
570
+ .replace(/[\t\n\r]/g, '')
571
+ .replace(/\$/g, '')
572
+ .replace(/,/g, '');
573
+ s = s.trim();
574
+ if (!s) {
575
+ return null;
576
+ }
577
+ var num = Number(s);
578
+ if (!Number.isFinite(num)) {
579
+ return null;
580
+ }
581
+ return negative ? -num : num;
582
+ }
583
+ function isExcelNumericField(field) {
584
+ return !!field && (field.fieldType === 'Number' ||
585
+ field.leafValueType === 'Count' ||
586
+ field.leafValueType === 'Sum' ||
587
+ field.leafValueType === 'Average');
588
+ }
589
+ function writeExcelCell(cell, value, fieldMeta) {
590
+ if (value === null || value === undefined) {
591
+ cell.value = '';
592
+ return;
593
+ }
594
+ if ((fieldMeta === null || fieldMeta === void 0 ? void 0 : fieldMeta.fieldType) === 'Date') {
595
+ var rawValue = Array.isArray(value) ? value.find(function (v) { return v !== null && v !== undefined && v !== ''; }) : value;
596
+ var m = parseMoment(rawValue);
597
+ if (m) {
598
+ var timezone = process.env.TZ_CLIENT;
599
+ var local = timezone ? moment.tz(m.toDate(), timezone) : m.clone().local();
600
+ var leafFormatType = fieldMeta === null || fieldMeta === void 0 ? void 0 : fieldMeta.leafFormatType;
601
+ var excelSerial = (Date.UTC(local.year(), local.month(), local.date(), local.hour(), local.minute(), local.second(), local.millisecond()) - Date.UTC(1899, 11, 30)) / 86400000;
602
+ if (leafFormatType === 'Date' || leafFormatType === 'Date_long') {
603
+ cell.value = Math.floor(excelSerial);
604
+ }
605
+ else if (leafFormatType === 'Time' || leafFormatType === 'DateTime' || leafFormatType === 'DateTime_long') {
606
+ cell.value = excelSerial;
607
+ }
608
+ else {
609
+ cell.value = local.toDate();
610
+ }
611
+ switch (leafFormatType) {
612
+ case 'Time':
613
+ cell.numFmt = 'h:mm AM/PM';
614
+ break;
615
+ case 'DateTime':
616
+ case 'DateTime_long':
617
+ cell.numFmt = 'mm/dd/yyyy h:mm AM/PM';
618
+ break;
619
+ case 'Date':
620
+ cell.numFmt = 'mm/dd/yyyy';
621
+ break;
622
+ case 'Date_long':
623
+ default:
624
+ cell.numFmt = 'mm/dd/yyyy';
625
+ break;
626
+ }
627
+ return;
628
+ }
629
+ }
630
+ if (Array.isArray(value)) {
631
+ cell.value = value.join(', ');
632
+ return;
633
+ }
634
+ if (isExcelNumericField(fieldMeta)) {
635
+ var parsed = parseExcelNumber(value);
636
+ if (parsed !== null) {
637
+ cell.value = parsed;
638
+ if ((fieldMeta === null || fieldMeta === void 0 ? void 0 : fieldMeta.leafFormatType) === 'Currency') {
639
+ cell.numFmt = '"$"#,##0.00;[Red]-"$"#,##0.00';
640
+ }
641
+ else if ((fieldMeta === null || fieldMeta === void 0 ? void 0 : fieldMeta.leafFormatType) === 'Number' || (fieldMeta === null || fieldMeta === void 0 ? void 0 : fieldMeta.leafValueType) === 'Count') {
642
+ cell.numFmt = '#,##0';
643
+ }
644
+ return;
645
+ }
646
+ }
647
+ if (typeof value === 'string') {
648
+ cell.value = value.replace(/\t/g, '').replace(/\n/g, '');
649
+ }
650
+ else {
651
+ cell.value = value;
652
+ }
653
+ }
654
+ function getMaxRows(row) {
655
+ var keys = Object.keys(row || {});
656
+ var maxArray = [];
657
+ for (var i = 0; i < keys.length; i++) {
658
+ if (Array.isArray(row[keys[i]]) && row[keys[i]].length > maxArray.length) {
659
+ maxArray = row[keys[i]];
660
+ }
661
+ else if (maxArray.length === 0) {
662
+ maxArray = [row[keys[i]]];
663
+ }
664
+ }
665
+ return maxArray;
666
+ }
273
667
  function applyClientGroupSortToData(results, report, sorts) {
274
668
  if (sorts === void 0) { sorts = []; }
275
669
  if (!Array.isArray(results) || !results.length) {
@@ -451,7 +845,7 @@ function loadCronJobMethods(methodManager) {
451
845
  }),
452
846
  function: function (data) {
453
847
  return __awaiter(this, void 0, void 0, function () {
454
- var report, fieldsObj_1, count_1, idRemap_1, groupIds_1, userSorts, userSortByField_1, groupSorts, nonGroupSorts, effectiveSorts, sortObj_1, totalsForQuery, rootOptions, filters_1, filterArrayFields_1, filterArrays_1, res, results_1, reportTotals, customFields, exportFields_1, lines_1, tmpHeaders_1, wb, ws, wbout, _a, _b, email, e_2_1, wb, ws_1, currentRow_1, row, copy, widths_1, i, now, buffer, _c, _d, email, e_3_1, err_1, datedUniqueDates_1, datedUniqueGroups_1, datedData_1, reportTotalGroups_1, reportTotalDates_1, _loop_1, i, tmpResults, wb, ws, currentRow, currentCol_1, row_1, _loop_2, i, i, total, j, field, buffer, _e, _f, email, e_4_1, err_2, err_3;
848
+ var report, layoutColumns_1, selectedFields, fieldsObj_1, selectedFieldsForQuery_1, groupIds_1, userSorts, userSortByField_1, groupSorts, nonGroupSorts, effectiveSorts, sortObj_1, totalsForQuery, rootOptions, filters_1, filterArrayFields_1, filterArrays_1, res, results_1, reportTotals, customFields, exportFields_1, wb, ws_1, currentRow_1, row_1, useLayout_1, headers_1, exportResults, buffer, _a, _b, email, e_2_1, err_1, wb, ws_2, currentRow_2, row, copy, widths_1, i, now, buffer, _c, _d, email, e_3_1, err_2, datedUniqueDates_1, datedUniqueGroups_1, datedData_1, reportTotalGroups_1, reportTotalDates_1, _loop_1, i, tmpResults, wb, ws, currentRow, currentCol_1, row_2, _loop_2, i, i, total, j, field, buffer, _e, _f, email, e_4_1, err_3, err_4;
455
849
  var e_2, _g, e_3, _h, e_4, _j;
456
850
  return __generator(this, function (_k) {
457
851
  switch (_k.label) {
@@ -460,9 +854,32 @@ function loadCronJobMethods(methodManager) {
460
854
  report = _k.sent();
461
855
  _k.label = 2;
462
856
  case 2:
463
- _k.trys.push([2, 39, , 40]);
857
+ _k.trys.push([2, 43, , 44]);
858
+ layoutColumns_1 = getLayoutColumnsFromReport(report);
859
+ selectedFields = syncSelectedFieldsFromLayout(report, layoutColumns_1);
860
+ report.fields_selected = selectedFields;
861
+ report.fields_layout = layoutColumns_1;
862
+ (report.fields_selected || []).forEach(function (field, index) {
863
+ if (!(field === null || field === void 0 ? void 0 : field.id)) {
864
+ field.id = "f_".concat(index);
865
+ }
866
+ });
867
+ (report.fields_custom || []).forEach(function (custom) {
868
+ if (!custom) {
869
+ return;
870
+ }
871
+ if (!custom.selFieldId && custom.id) {
872
+ var match = (report.fields_selected || []).find(function (field) { return field.fieldPath === custom.id; });
873
+ if (match === null || match === void 0 ? void 0 : match.id) {
874
+ custom.selFieldId = match.id;
875
+ }
876
+ }
877
+ });
464
878
  report.fields_selected.forEach(function (field) {
465
879
  var _a, _b;
880
+ if (!(field === null || field === void 0 ? void 0 : field.fieldPath)) {
881
+ return;
882
+ }
466
883
  var dotPath = field.fieldPath.replace(/\.\$/g, '');
467
884
  var fieldData = dotPath.split('.');
468
885
  field.fieldPathObj = null;
@@ -475,26 +892,14 @@ function loadCronJobMethods(methodManager) {
475
892
  }
476
893
  }
477
894
  });
478
- if (!((report.fields_selected && report.fields_selected.length) || (report.groups_row && report.groups_row.length))) return [3 /*break*/, 38];
895
+ if (!((report.fields_selected && report.fields_selected.length) || (report.groups_row && report.groups_row.length))) return [3 /*break*/, 42];
479
896
  fieldsObj_1 = {};
480
- count_1 = 0;
481
- idRemap_1 = {};
897
+ selectedFieldsForQuery_1 = (report.fields_selected || []).filter(function (field) { return !(((field === null || field === void 0 ? void 0 : field.fieldPath) || '').startsWith('c_')); });
482
898
  report.fields_sort = report.fields_sort || [];
483
- report.fields_selected.forEach(function (field) {
484
- if (field.collection_name === report.collection_root) {
899
+ selectedFieldsForQuery_1.forEach(function (field) {
900
+ if (field.collection_name === report.collection_root && field.fieldPathObj) {
485
901
  fieldsObj_1 = (0, common_1.mergeDeep)(fieldsObj_1, field.fieldPathObj);
486
902
  }
487
- var oldId = field['id'];
488
- var newId = 'f_' + count_1;
489
- if (oldId) {
490
- idRemap_1[oldId] = newId;
491
- }
492
- var sortIndex = report.fields_sort.findIndex(function (a) { return a.field === oldId; });
493
- if (sortIndex >= 0) {
494
- report.fields_sort[sortIndex].field = newId;
495
- }
496
- field['id'] = newId;
497
- count_1 += 1;
498
903
  });
499
904
  groupIds_1 = (report.groups_row || []).map(function (g) { return g.id; }).filter(Boolean);
500
905
  userSorts = (report.fields_sort || []).filter(function (s) { return !!s.field; });
@@ -513,9 +918,6 @@ function loadCronJobMethods(methodManager) {
513
918
  if (!targetField) {
514
919
  return;
515
920
  }
516
- if (!targetField.startsWith('gr_') && !targetField.startsWith('layout_col_')) {
517
- targetField = idRemap_1[targetField] || targetField;
518
- }
519
921
  if (targetField.startsWith('layout_col_')) {
520
922
  var resolved = resolveFieldRefToLeafId(targetField, report);
521
923
  targetField = resolved || targetField;
@@ -537,7 +939,7 @@ function loadCronJobMethods(methodManager) {
537
939
  if (ref.startsWith('layout_col_')) {
538
940
  return resolveFieldRefToLeafId(ref, report);
539
941
  }
540
- return idRemap_1[ref] || ref;
942
+ return ref;
541
943
  })
542
944
  .filter(function (f) { return !!f; });
543
945
  return __assign(__assign({}, total), { fields: mappedFields });
@@ -552,6 +954,13 @@ function loadCronJobMethods(methodManager) {
552
954
  filters_1 = [];
553
955
  filterArrayFields_1 = [];
554
956
  filterArrays_1 = [];
957
+ selectedFieldsForQuery_1
958
+ .filter(function (f) { return (f.fieldPath || '').includes('.$.'); })
959
+ .forEach(function (sel) {
960
+ if (!filterArrayFields_1.some(function (f) { return (f === null || f === void 0 ? void 0 : f.fieldPath) === sel.fieldPath; })) {
961
+ filterArrayFields_1.push(sel);
962
+ }
963
+ });
555
964
  (report.fields_filter || []).forEach(function (filterAnd) {
556
965
  var ors = [];
557
966
  var hasArrayTarget = false;
@@ -569,7 +978,7 @@ function loadCronJobMethods(methodManager) {
569
978
  }
570
979
  if (isArrayTarget) {
571
980
  hasArrayTarget = true;
572
- var leaf_1 = (report.fields_selected || []).find(function (a) { return a.fieldPath === path; });
981
+ var leaf_1 = selectedFieldsForQuery_1.find(function (a) { return a.fieldPath === path; });
573
982
  if (leaf_1 && !filterArrayFields_1.some(function (f) { return (f === null || f === void 0 ? void 0 : f.fieldPath) === leaf_1.fieldPath; })) {
574
983
  filterArrayFields_1.push(leaf_1);
575
984
  }
@@ -586,10 +995,10 @@ function loadCronJobMethods(methodManager) {
586
995
  }
587
996
  }
588
997
  });
589
- return [4 /*yield*/, this.callMethod('reportBuilderGetResults', report.type, report.collection_root, rootOptions, filters_1, filterArrays_1, filterArrayFields_1, report.fields_selected, report.fields_custom, report.groups_row, totalsForQuery, report.fields_link, report.id_date_field || null, report.date_interval || null, report.group_type)];
998
+ return [4 /*yield*/, this.callMethod('reportBuilderGetResults', report.type, report.collection_root, rootOptions, filters_1, filterArrays_1, filterArrayFields_1, selectedFieldsForQuery_1, report.fields_custom, report.groups_row, totalsForQuery, report.fields_link, report.id_date_field || null, report.date_interval || null, report.group_type)];
590
999
  case 3:
591
1000
  res = _k.sent();
592
- if (!(res && res[0])) return [3 /*break*/, 38];
1001
+ if (!(res && res[0])) return [3 /*break*/, 42];
593
1002
  results_1 = res[0].results;
594
1003
  reportTotals = res[0].totals;
595
1004
  if (report.type === 'Group') {
@@ -597,7 +1006,7 @@ function loadCronJobMethods(methodManager) {
597
1006
  }
598
1007
  customFields = (report.fields_custom || []).map(function (cust) { return (__assign(__assign({}, cust), { id: cust.selFieldId, fieldType: 'Number', leafValueType: cust.leafValueType || 'Value', leafFormatType: 'Number', columnName: cust.columnName || cust.id, show: true })); });
599
1008
  exportFields_1 = report.fields_selected.filter(function (a) { return a.show; }).concat(customFields);
600
- if (!(report.type === 'List')) return [3 /*break*/, 12];
1009
+ if (!(report.type === 'List')) return [3 /*break*/, 16];
601
1010
  exportFields_1.forEach(function (field) {
602
1011
  if ((field.fieldType === 'Number' || field.leafValueType === 'Count') && field.leafFormatType === 'Number') {
603
1012
  results_1.filter(function (a) { return a[field.id] !== null && a[field.id] !== undefined; }).forEach(function (result) {
@@ -660,94 +1069,141 @@ function loadCronJobMethods(methodManager) {
660
1069
  });
661
1070
  }
662
1071
  });
663
- lines_1 = [];
664
- tmpHeaders_1 = {};
1072
+ wb = new Excel.Workbook();
1073
+ ws_1 = wb.addWorksheet('RB_1', { views: [{ showGridLines: true }] });
1074
+ wb.properties.date1904 = false;
1075
+ wb.calcProperties.fullCalcOnLoad = true;
1076
+ currentRow_1 = 1;
1077
+ row_1 = ws_1.getRow(currentRow_1);
1078
+ row_1.getCell(2).font = {
1079
+ name: 'Arial',
1080
+ bold: true,
1081
+ size: 14
1082
+ };
1083
+ row_1.getCell(4).font = {
1084
+ name: 'Arial',
1085
+ size: 14
1086
+ };
1087
+ row_1.getCell(2).value = 'Report Name:';
1088
+ row_1.getCell(4).value = report.report_name;
1089
+ currentRow_1 += 1;
1090
+ row_1 = ws_1.getRow(currentRow_1);
1091
+ row_1.getCell(2).font = {
1092
+ name: 'Arial',
1093
+ bold: true,
1094
+ size: 14
1095
+ };
1096
+ row_1.getCell(4).font = {
1097
+ name: 'Arial',
1098
+ size: 14
1099
+ };
1100
+ row_1.getCell(2).value = 'Run Date:';
1101
+ row_1.getCell(4).value = moment().format('LLL');
1102
+ currentRow_1 += 2;
1103
+ row_1 = ws_1.getRow(currentRow_1);
1104
+ useLayout_1 = (layoutColumns_1 && layoutColumns_1.length > 0);
1105
+ headers_1 = [];
665
1106
  report.groups_row.forEach(function (group) {
666
- tmpHeaders_1[group.id] = group.columnName;
1107
+ headers_1.push(group.columnName);
667
1108
  });
668
- exportFields_1.forEach(function (header) {
669
- tmpHeaders_1[header.columnName] = header.columnName;
1109
+ if (useLayout_1) {
1110
+ layoutColumns_1.forEach(function (col, idx) {
1111
+ headers_1.push(col.header || "Column ".concat(idx + 1));
1112
+ });
1113
+ }
1114
+ else {
1115
+ exportFields_1.forEach(function (field) {
1116
+ headers_1.push(field.columnName);
1117
+ });
1118
+ }
1119
+ headers_1.forEach(function (header, headerIdx) {
1120
+ row_1.getCell(headerIdx + 1).value = header;
670
1121
  });
671
- wb = XLSX.utils.book_new();
672
- results_1.forEach(function (result) {
673
- var tmp = {};
1122
+ currentRow_1 += 1;
1123
+ row_1 = ws_1.getRow(currentRow_1);
1124
+ exportResults = (0, common_1.deepCopy)(results_1 || []);
1125
+ exportResults.forEach(function (result) {
1126
+ var currentCol = 1;
674
1127
  report.groups_row.forEach(function (group) {
675
- if (Array.isArray(result._id[group.id])) {
676
- tmp[group.columnName] = result._id[group.id].join(',');
677
- }
678
- else {
679
- if (group.treeItem.fieldType === 'Number') {
680
- tmp[group.columnName] = result._id[group.id] ? (typeof (result._id[group.id]) === 'string' ? parseFloat(result._id[group.id].replace(/,/g, '').replace(/\$/g, '')) : result._id[group.id]) : '';
681
- }
682
- else {
683
- tmp[group.columnName] = result._id[group.id] || '';
684
- }
685
- }
1128
+ var _a, _b;
1129
+ writeExcelCell(row_1.getCell(currentCol), (_b = (_a = result === null || result === void 0 ? void 0 : result._id) === null || _a === void 0 ? void 0 : _a[group.id]) !== null && _b !== void 0 ? _b : '', group.treeItem);
1130
+ currentCol += 1;
686
1131
  });
687
- exportFields_1.forEach(function (header) {
688
- if (Array.isArray(result[header.id])) {
689
- tmp[header.columnName] = result[header.id].join(',');
690
- }
691
- else {
692
- if (header.fieldType === 'Number' || header.leafValueType === 'Count') {
693
- tmp[header.columnName] = result[header.id] ? (typeof (result[header.id]) === 'string' ? parseFloat(result[header.id].replace(/,/g, '').replace(/\$/g, '')) : result[header.id]) : '';
694
- }
695
- else {
696
- tmp[header.columnName] = result[header.id] || '';
697
- }
698
- }
699
- });
700
- lines_1.push(tmp);
1132
+ if (useLayout_1) {
1133
+ var layoutRow_1 = materializeLayoutRow(report, layoutColumns_1, report.fields_selected, result);
1134
+ layoutColumns_1.forEach(function (col, colIdx) {
1135
+ var cellValue = getLayoutCellExportValue(report, layoutRow_1, colIdx);
1136
+ var primaryFieldMeta = getPrimaryFieldForLayoutColumn(col, report.fields_selected);
1137
+ writeExcelCell(row_1.getCell(currentCol), cellValue === undefined ? '' : cellValue, primaryFieldMeta);
1138
+ currentCol += 1;
1139
+ });
1140
+ }
1141
+ else {
1142
+ exportFields_1.forEach(function (field) {
1143
+ var _a;
1144
+ writeExcelCell(row_1.getCell(currentCol), (_a = result[field.id]) !== null && _a !== void 0 ? _a : '', field);
1145
+ currentCol += 1;
1146
+ });
1147
+ }
1148
+ currentRow_1 += 1;
1149
+ row_1 = ws_1.getRow(currentRow_1);
701
1150
  });
702
- ws = XLSX.utils.json_to_sheet(lines_1);
703
- XLSX.utils.book_append_sheet(wb, ws, 'RB Data');
704
- wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'base64' });
705
1151
  _k.label = 4;
706
1152
  case 4:
707
- _k.trys.push([4, 9, 10, 11]);
708
- _a = __values(data['emails']), _b = _a.next();
709
- _k.label = 5;
1153
+ _k.trys.push([4, 14, , 15]);
1154
+ return [4 /*yield*/, wb.xlsx.writeBuffer()];
710
1155
  case 5:
711
- if (!!_b.done) return [3 /*break*/, 8];
1156
+ buffer = _k.sent();
1157
+ _k.label = 6;
1158
+ case 6:
1159
+ _k.trys.push([6, 11, 12, 13]);
1160
+ _a = __values(data['emails']), _b = _a.next();
1161
+ _k.label = 7;
1162
+ case 7:
1163
+ if (!!_b.done) return [3 /*break*/, 10];
712
1164
  email = _b.value;
713
- return [4 /*yield*/, this.sendEmail(email, this.serverConfig['CLIENT_NAME'] + ' Scheduled Report - ' + report.report_name, '', "\n\t\t\t\t\t\t\t\t\t\t<b>" + this.serverConfig['CLIENT_NAME'] + " Automated Report</b><br>\n\t\t\t\t\t\t\t\t\t\t<b>Report Name: </b>" + report.report_name + "<br>\n\t\t\t\t\t\t\t\t\t\t<b>Prepared By: </b>" + data['user'] + "<br><br>\n\t\t\t\t\t\t\t\t\t\tAttached are the results of this automated report.<br><br>\n\t\t\t\t\t\t\t\t\t\tResolveIO<br><br>", [
1165
+ return [4 /*yield*/, this.sendEmail(email, this.serverConfig['CLIENT_NAME'] + ' Scheduled Report - ' + report.report_name, '', "\n\t\t\t\t\t\t\t\t\t\t\t<b>" + this.serverConfig['CLIENT_NAME'] + " Automated Report</b><br>\n\t\t\t\t\t\t\t\t\t\t\t<b>Report Name: </b>" + report.report_name + "<br>\n\t\t\t\t\t\t\t\t\t\t\t<b>Prepared By: </b>" + data['user'] + "<br><br>\n\t\t\t\t\t\t\t\t\t\t\tAttached are the results of this automated report.<br><br>\n\t\t\t\t\t\t\t\t\t\t\tResolveIO<br><br>", [
714
1166
  {
715
1167
  filename: report.report_name + '-' + moment().format('MM-DD-YYYY-hh-mm-A') + '.xlsx',
716
- content: wbout,
717
- encoding: 'base64'
1168
+ content: buffer
718
1169
  }
719
1170
  ], this.serverConfig['MAIL_FROM_REPORTS'], '')];
720
- case 6:
1171
+ case 8:
721
1172
  _k.sent();
722
- _k.label = 7;
723
- case 7:
724
- _b = _a.next();
725
- return [3 /*break*/, 5];
726
- case 8: return [3 /*break*/, 11];
1173
+ _k.label = 9;
727
1174
  case 9:
1175
+ _b = _a.next();
1176
+ return [3 /*break*/, 7];
1177
+ case 10: return [3 /*break*/, 13];
1178
+ case 11:
728
1179
  e_2_1 = _k.sent();
729
1180
  e_2 = { error: e_2_1 };
730
- return [3 /*break*/, 11];
731
- case 10:
1181
+ return [3 /*break*/, 13];
1182
+ case 12:
732
1183
  try {
733
1184
  if (_b && !_b.done && (_g = _a.return)) _g.call(_a);
734
1185
  }
735
1186
  finally { if (e_2) throw e_2.error; }
736
1187
  return [7 /*endfinally*/];
737
- case 11: return [3 /*break*/, 38];
738
- case 12:
739
- if (!(report.type === 'Group')) return [3 /*break*/, 25];
1188
+ case 13: return [3 /*break*/, 15];
1189
+ case 14:
1190
+ err_1 = _k.sent();
1191
+ console.log('Error writing excel export', err_1);
1192
+ return [3 /*break*/, 15];
1193
+ case 15: return [3 /*break*/, 42];
1194
+ case 16:
1195
+ if (!(report.type === 'Group')) return [3 /*break*/, 29];
740
1196
  exportFields_1.forEach(function (field) {
741
1197
  results_1.forEach(function (result) {
742
1198
  modifyDataTypeField(report, result, field, 1);
743
1199
  });
744
1200
  });
745
1201
  wb = new Excel.Workbook();
746
- ws_1 = wb.addWorksheet('RB_1', { views: [{ showGridLines: false }] });
1202
+ ws_2 = wb.addWorksheet('RB_1', { views: [{ showGridLines: false }] });
747
1203
  wb.properties.date1904 = false;
748
1204
  wb.calcProperties.fullCalcOnLoad = true;
749
- currentRow_1 = 1;
750
- row = ws_1.getRow(currentRow_1);
1205
+ currentRow_2 = 1;
1206
+ row = ws_2.getRow(currentRow_2);
751
1207
  row.getCell(2).font = {
752
1208
  name: 'Arial',
753
1209
  bold: true,
@@ -759,8 +1215,8 @@ function loadCronJobMethods(methodManager) {
759
1215
  };
760
1216
  row.getCell(2).value = 'Report Name:';
761
1217
  row.getCell(4).value = report.report_name;
762
- currentRow_1 += 1;
763
- row = ws_1.getRow(currentRow_1);
1218
+ currentRow_2 += 1;
1219
+ row = ws_2.getRow(currentRow_2);
764
1220
  row.getCell(2).font = {
765
1221
  name: 'Arial',
766
1222
  bold: true,
@@ -772,30 +1228,30 @@ function loadCronJobMethods(methodManager) {
772
1228
  };
773
1229
  row.getCell(2).value = 'Run Date:';
774
1230
  row.getCell(4).value = moment().format('LLL');
775
- currentRow_1 += 2;
1231
+ currentRow_2 += 2;
776
1232
  copy = (0, common_1.deepCopy)(results_1);
777
1233
  widths_1 = [];
778
1234
  copy.forEach(function (res) {
779
- currentRow_1 = tabGroupExcelRecursive(report, ws_1, currentRow_1, 1, res, exportFields_1);
1235
+ currentRow_2 = tabGroupExcelRecursive(report, ws_2, currentRow_2, 1, res, exportFields_1);
780
1236
  tabGroupExcelWidthRecursive(report, 1, res, widths_1, exportFields_1);
781
1237
  });
782
- for (i = 1; i < ws_1.columns.length; i++) {
783
- ws_1.columns[i].width = widths_1[i - 1];
1238
+ for (i = 1; i < ws_2.columns.length; i++) {
1239
+ ws_2.columns[i].width = widths_1[i - 1];
784
1240
  }
785
1241
  now = new Date();
786
- _k.label = 13;
787
- case 13:
788
- _k.trys.push([13, 23, , 24]);
1242
+ _k.label = 17;
1243
+ case 17:
1244
+ _k.trys.push([17, 27, , 28]);
789
1245
  return [4 /*yield*/, wb.xlsx.writeBuffer()];
790
- case 14:
1246
+ case 18:
791
1247
  buffer = _k.sent();
792
- _k.label = 15;
793
- case 15:
794
- _k.trys.push([15, 20, 21, 22]);
1248
+ _k.label = 19;
1249
+ case 19:
1250
+ _k.trys.push([19, 24, 25, 26]);
795
1251
  _c = __values(data['emails']), _d = _c.next();
796
- _k.label = 16;
797
- case 16:
798
- if (!!_d.done) return [3 /*break*/, 19];
1252
+ _k.label = 20;
1253
+ case 20:
1254
+ if (!!_d.done) return [3 /*break*/, 23];
799
1255
  email = _d.value;
800
1256
  return [4 /*yield*/, this.sendEmail(email, this.serverConfig['CLIENT_NAME'] + ' Scheduled Report - ' + report.report_name, '', "\n\t\t\t\t\t\t\t\t\t\t\t<b>" + this.serverConfig['CLIENT_NAME'] + " Automated Report</b><br>\n\t\t\t\t\t\t\t\t\t\t\t<b>Report Name: </b>" + report.report_name + "<br>\n\t\t\t\t\t\t\t\t\t\t\t<b>Prepared By: </b>" + data['user'] + "<br><br>\n\t\t\t\t\t\t\t\t\t\t\tAttached are the results of this automated report.<br><br>\n\t\t\t\t\t\t\t\t\t\t\tHave a great day!<br><br>\n\t\t\t\t\t\t\t\t\t\t\tResolveIO<br><br>", [
801
1257
  {
@@ -803,33 +1259,33 @@ function loadCronJobMethods(methodManager) {
803
1259
  content: buffer
804
1260
  }
805
1261
  ], this.serverConfig['MAIL_FROM_REPORTS'], '')];
806
- case 17:
1262
+ case 21:
807
1263
  _k.sent();
808
- _k.label = 18;
809
- case 18:
1264
+ _k.label = 22;
1265
+ case 22:
810
1266
  _d = _c.next();
811
- return [3 /*break*/, 16];
812
- case 19: return [3 /*break*/, 22];
813
- case 20:
1267
+ return [3 /*break*/, 20];
1268
+ case 23: return [3 /*break*/, 26];
1269
+ case 24:
814
1270
  e_3_1 = _k.sent();
815
1271
  e_3 = { error: e_3_1 };
816
- return [3 /*break*/, 22];
817
- case 21:
1272
+ return [3 /*break*/, 26];
1273
+ case 25:
818
1274
  try {
819
1275
  if (_d && !_d.done && (_h = _c.return)) _h.call(_c);
820
1276
  }
821
1277
  finally { if (e_3) throw e_3.error; }
822
1278
  return [7 /*endfinally*/];
823
- case 22: return [3 /*break*/, 24];
824
- case 23:
825
- err_1 = _k.sent();
826
- console.log('Error writing excel export', err_1);
827
- return [3 /*break*/, 24];
828
- case 24:
1279
+ case 26: return [3 /*break*/, 28];
1280
+ case 27:
1281
+ err_2 = _k.sent();
1282
+ console.log('Error writing excel export', err_2);
1283
+ return [3 /*break*/, 28];
1284
+ case 28:
829
1285
  ;
830
- return [3 /*break*/, 38];
831
- case 25:
832
- if (!(report.type === 'Dated')) return [3 /*break*/, 38];
1286
+ return [3 /*break*/, 42];
1287
+ case 29:
1288
+ if (!(report.type === 'Dated')) return [3 /*break*/, 42];
833
1289
  datedUniqueDates_1 = [];
834
1290
  datedUniqueGroups_1 = [];
835
1291
  datedData_1 = [];
@@ -1089,36 +1545,36 @@ function loadCronJobMethods(methodManager) {
1089
1545
  wb.calcProperties.fullCalcOnLoad = true;
1090
1546
  currentRow = 1;
1091
1547
  currentCol_1 = 1;
1092
- row_1 = ws.getRow(currentRow);
1093
- row_1.getCell(2).font = {
1548
+ row_2 = ws.getRow(currentRow);
1549
+ row_2.getCell(2).font = {
1094
1550
  name: 'Arial',
1095
1551
  bold: true,
1096
1552
  size: 14
1097
1553
  };
1098
- row_1.getCell(4).font = {
1554
+ row_2.getCell(4).font = {
1099
1555
  name: 'Arial',
1100
1556
  size: 14
1101
1557
  };
1102
- row_1.getCell(2).value = 'Report Name:';
1103
- row_1.getCell(4).value = report.report_name;
1558
+ row_2.getCell(2).value = 'Report Name:';
1559
+ row_2.getCell(4).value = report.report_name;
1104
1560
  currentRow += 1;
1105
- row_1 = ws.getRow(currentRow);
1106
- row_1.getCell(2).font = {
1561
+ row_2 = ws.getRow(currentRow);
1562
+ row_2.getCell(2).font = {
1107
1563
  name: 'Arial',
1108
1564
  bold: true,
1109
1565
  size: 14
1110
1566
  };
1111
- row_1.getCell(4).font = {
1567
+ row_2.getCell(4).font = {
1112
1568
  name: 'Arial',
1113
1569
  size: 14
1114
1570
  };
1115
- row_1.getCell(2).value = 'Run Date:';
1116
- row_1.getCell(4).value = moment().format('LLL');
1571
+ row_2.getCell(2).value = 'Run Date:';
1572
+ row_2.getCell(4).value = moment().format('LLL');
1117
1573
  currentRow += 2;
1118
- row_1 = ws.getRow(currentRow);
1574
+ row_2 = ws.getRow(currentRow);
1119
1575
  // Add group column headers
1120
1576
  report.groups_row.forEach(function (group) {
1121
- row_1.getCell(currentCol_1).value = group.columnName;
1577
+ row_2.getCell(currentCol_1).value = group.columnName;
1122
1578
  currentCol_1++;
1123
1579
  });
1124
1580
  // Add field headers
@@ -1126,46 +1582,46 @@ function loadCronJobMethods(methodManager) {
1126
1582
  // Add the date interval headers
1127
1583
  report.fields_selected.filter(function (a) { return a.show; }).forEach(function () {
1128
1584
  datedUniqueDates_1.forEach(function (date) {
1129
- row_1.getCell(currentCol_1).value = date.dateString;
1585
+ row_2.getCell(currentCol_1).value = date.dateString;
1130
1586
  currentCol_1++;
1131
1587
  });
1132
1588
  });
1133
1589
  // Add totals headers
1134
1590
  report.fields_total.forEach(function (total) {
1135
- row_1.getCell(currentCol_1).value = 'Totals - ' + (0, common_1.toTitleCase)(total.type);
1591
+ row_2.getCell(currentCol_1).value = 'Totals - ' + (0, common_1.toTitleCase)(total.type);
1136
1592
  currentCol_1++;
1137
1593
  });
1138
1594
  currentCol_1 = 1;
1139
1595
  currentRow += 1;
1140
- row_1 = ws.getRow(currentRow);
1596
+ row_2 = ws.getRow(currentRow);
1141
1597
  _loop_2 = function (i) {
1142
1598
  var group = datedUniqueGroups_1[i];
1143
1599
  var _loop_3 = function (j) {
1144
1600
  var field = report.fields_selected.filter(function (a) { return a.show; })[j];
1145
1601
  currentCol_1 = 1;
1146
- row_1 = ws.getRow(currentRow);
1602
+ row_2 = ws.getRow(currentRow);
1147
1603
  // Populate group data
1148
1604
  report.groups_row.forEach(function (groupRow) {
1149
- row_1.getCell(currentCol_1).value = (j === 0) ? group[groupRow.id] : '';
1605
+ row_2.getCell(currentCol_1).value = (j === 0) ? group[groupRow.id] : '';
1150
1606
  currentCol_1++;
1151
1607
  });
1152
1608
  // Populate field data
1153
- row_1.getCell(currentCol_1).value = field.columnName;
1609
+ row_2.getCell(currentCol_1).value = field.columnName;
1154
1610
  currentCol_1++;
1155
1611
  // Populate date interval data for each field
1156
1612
  for (var k = 0; k < datedUniqueDates_1.length; k++) {
1157
1613
  var result = datedData_1[k];
1158
1614
  if (result[i]) {
1159
- row_1.getCell(currentCol_1).value = result[i][field.id] ? result[i][field.id] : '';
1615
+ row_2.getCell(currentCol_1).value = result[i][field.id] ? result[i][field.id] : '';
1160
1616
  }
1161
1617
  else {
1162
- row_1.getCell(currentCol_1).value = '';
1618
+ row_2.getCell(currentCol_1).value = '';
1163
1619
  }
1164
1620
  currentCol_1++;
1165
1621
  }
1166
1622
  // Add totals for each field in the report
1167
1623
  for (var k = 0; k < report.fields_total.length; k++) {
1168
- row_1.getCell(currentCol_1).value = reportTotalGroups_1[i][field.id] ? reportTotalGroups_1[i][field.id] : '';
1624
+ row_2.getCell(currentCol_1).value = reportTotalGroups_1[i][field.id] ? reportTotalGroups_1[i][field.id] : '';
1169
1625
  currentCol_1++;
1170
1626
  }
1171
1627
  currentRow++; // Move to the next row for the next field
@@ -1182,9 +1638,9 @@ function loadCronJobMethods(methodManager) {
1182
1638
  if (reportTotals) {
1183
1639
  for (i = 0; i < report.fields_total.length; i++) {
1184
1640
  total = report.fields_total[i];
1185
- row_1 = ws.getRow(currentRow);
1641
+ row_2 = ws.getRow(currentRow);
1186
1642
  currentCol_1 = 1;
1187
- row_1.getCell(currentCol_1).value = (0, common_1.toTitleCase)(total.type) + ' Totals';
1643
+ row_2.getCell(currentCol_1).value = (0, common_1.toTitleCase)(total.type) + ' Totals';
1188
1644
  currentCol_1 += report.groups_row.length; // Skip group columns
1189
1645
  // Skip the date columns for the totals row
1190
1646
  report.fields_selected.filter(function (a) { return a.show; }).forEach(function () {
@@ -1196,25 +1652,25 @@ function loadCronJobMethods(methodManager) {
1196
1652
  // Set totals in the correct fields
1197
1653
  for (j = 0; j < report.fields_selected.filter(function (a) { return a.show; }).length; j++) {
1198
1654
  field = report.fields_selected.filter(function (a) { return a.show; })[j];
1199
- row_1.getCell(currentCol_1).value = reportTotals[total.id + '_' + field.id] || '';
1655
+ row_2.getCell(currentCol_1).value = reportTotals[total.id + '_' + field.id] || '';
1200
1656
  currentCol_1++;
1201
1657
  }
1202
1658
  currentRow++; // Move to the next row for the next total
1203
1659
  }
1204
1660
  }
1205
- _k.label = 26;
1206
- case 26:
1207
- _k.trys.push([26, 36, , 37]);
1661
+ _k.label = 30;
1662
+ case 30:
1663
+ _k.trys.push([30, 40, , 41]);
1208
1664
  return [4 /*yield*/, wb.xlsx.writeBuffer()];
1209
- case 27:
1665
+ case 31:
1210
1666
  buffer = _k.sent();
1211
- _k.label = 28;
1212
- case 28:
1213
- _k.trys.push([28, 33, 34, 35]);
1667
+ _k.label = 32;
1668
+ case 32:
1669
+ _k.trys.push([32, 37, 38, 39]);
1214
1670
  _e = __values(data['emails']), _f = _e.next();
1215
- _k.label = 29;
1216
- case 29:
1217
- if (!!_f.done) return [3 /*break*/, 32];
1671
+ _k.label = 33;
1672
+ case 33:
1673
+ if (!!_f.done) return [3 /*break*/, 36];
1218
1674
  email = _f.value;
1219
1675
  return [4 /*yield*/, this.sendEmail(email, this.serverConfig['CLIENT_NAME'] + ' Scheduled Report - ' + report.report_name, '', "\n\t\t\t\t\t\t\t\t\t\t\t<b>".concat(this.serverConfig['CLIENT_NAME'], " Automated Report</b><br>\n\t\t\t\t\t\t\t\t\t\t\t<b>Report Name: </b>").concat(report.report_name, "<br>\n\t\t\t\t\t\t\t\t\t\t\t<b>Prepared By: </b>").concat(data['user'], "<br><br>\n\t\t\t\t\t\t\t\t\t\t\tAttached are the results of this automated report.<br><br>\n\t\t\t\t\t\t\t\t\t\t\tResolveIO<br><br>"), [
1220
1676
  {
@@ -1222,35 +1678,35 @@ function loadCronJobMethods(methodManager) {
1222
1678
  content: buffer
1223
1679
  }
1224
1680
  ], this.serverConfig['MAIL_FROM_REPORTS'], '')];
1225
- case 30:
1681
+ case 34:
1226
1682
  _k.sent();
1227
- _k.label = 31;
1228
- case 31:
1683
+ _k.label = 35;
1684
+ case 35:
1229
1685
  _f = _e.next();
1230
- return [3 /*break*/, 29];
1231
- case 32: return [3 /*break*/, 35];
1232
- case 33:
1686
+ return [3 /*break*/, 33];
1687
+ case 36: return [3 /*break*/, 39];
1688
+ case 37:
1233
1689
  e_4_1 = _k.sent();
1234
1690
  e_4 = { error: e_4_1 };
1235
- return [3 /*break*/, 35];
1236
- case 34:
1691
+ return [3 /*break*/, 39];
1692
+ case 38:
1237
1693
  try {
1238
1694
  if (_f && !_f.done && (_j = _e.return)) _j.call(_e);
1239
1695
  }
1240
1696
  finally { if (e_4) throw e_4.error; }
1241
1697
  return [7 /*endfinally*/];
1242
- case 35: return [3 /*break*/, 37];
1243
- case 36:
1244
- err_2 = _k.sent();
1245
- console.log('Error writing excel export', err_2);
1246
- return [3 /*break*/, 37];
1247
- case 37: return [2 /*return*/, true];
1248
- case 38: return [3 /*break*/, 40];
1249
- case 39:
1698
+ case 39: return [3 /*break*/, 41];
1699
+ case 40:
1250
1700
  err_3 = _k.sent();
1251
- err_3.message = "Error in Report Builder Cron Job - Report Builder Build Tree: ".concat(err_3.message);
1252
- throw err_3;
1253
- case 40: return [2 /*return*/, true];
1701
+ console.log('Error writing excel export', err_3);
1702
+ return [3 /*break*/, 41];
1703
+ case 41: return [2 /*return*/, true];
1704
+ case 42: return [3 /*break*/, 44];
1705
+ case 43:
1706
+ err_4 = _k.sent();
1707
+ err_4.message = "Error in Report Builder Cron Job - Report Builder Build Tree: ".concat(err_4.message);
1708
+ throw err_4;
1709
+ case 44: return [2 /*return*/, true];
1254
1710
  }
1255
1711
  });
1256
1712
  });
@@ -1329,6 +1785,7 @@ function modifyDataTypeField(report, result, field, index) {
1329
1785
  }
1330
1786
  function tabGroupExcelRecursive(report, ws, currentRow, level, result, fields) {
1331
1787
  var row = ws.getRow(currentRow);
1788
+ var fieldCount = fields.length;
1332
1789
  if (level < report.groups_row.length) {
1333
1790
  row.getCell(2).fill = {
1334
1791
  fgColor: { argb: report.groups_row[level - 1].fill_color ? report.groups_row[level - 1].fill_color.replace('#', '') : 'ffffff' },
@@ -1343,7 +1800,7 @@ function tabGroupExcelRecursive(report, ws, currentRow, level, result, fields) {
1343
1800
  };
1344
1801
  var currentGroup = report.groups_row[level - 1];
1345
1802
  row.getCell(2).value = currentGroup.columnName + ': ' + (result._id[currentGroup.id] || '');
1346
- ws.mergeCells(row.getCell(2).$col$row + ':' + row.getCell(report.fields_selected.filter(function (a) { return a.show; }).length + 1).$col$row);
1803
+ ws.mergeCells(row.getCell(2).$col$row + ':' + row.getCell(fieldCount + 1).$col$row);
1347
1804
  row.getCell(2).border = {
1348
1805
  top: { style: 'thick' },
1349
1806
  left: { style: 'thick' },
@@ -1373,7 +1830,7 @@ function tabGroupExcelRecursive(report, ws, currentRow, level, result, fields) {
1373
1830
  left: { style: 'thick' }
1374
1831
  };
1375
1832
  }
1376
- else if (fieldIndex === report.fields_selected.filter(function (a) { return a.show; }).length - 1) {
1833
+ else if (fieldIndex === fieldCount - 1) {
1377
1834
  row.getCell(fieldIndex + 2).border = {
1378
1835
  right: { style: 'thick' }
1379
1836
  };
@@ -1407,7 +1864,7 @@ function tabGroupExcelRecursive(report, ws, currentRow, level, result, fields) {
1407
1864
  bottom: { style: 'thick' }
1408
1865
  };
1409
1866
  }
1410
- else if (fieldIndex === report.fields_selected.filter(function (a) { return a.show; }).length - 1) {
1867
+ else if (fieldIndex === fieldCount - 1) {
1411
1868
  row.getCell(fieldIndex + 2).border = {
1412
1869
  top: { style: 'thin' },
1413
1870
  bottom: { style: 'thick' },
@@ -1447,7 +1904,7 @@ function tabGroupExcelRecursive(report, ws, currentRow, level, result, fields) {
1447
1904
  };
1448
1905
  var finalGroup = report.groups_row[level - 1];
1449
1906
  row.getCell(2).value = finalGroup.columnName + ': ' + (result._id[finalGroup.id] || '');
1450
- ws.mergeCells(row.getCell(2).$col$row + ':' + row.getCell(report.fields_selected.filter(function (a) { return a.show; }).length + 1).$col$row);
1907
+ ws.mergeCells(row.getCell(2).$col$row + ':' + row.getCell(fieldCount + 1).$col$row);
1451
1908
  row.getCell(2).border = {
1452
1909
  top: { style: 'thick' },
1453
1910
  left: { style: 'thick' },
@@ -1474,22 +1931,29 @@ function tabGroupExcelRecursive(report, ws, currentRow, level, result, fields) {
1474
1931
  left: { style: 'thick' }
1475
1932
  };
1476
1933
  }
1477
- else if (fieldIndex === report.fields_selected.filter(function (a) { return a.show; }).length - 1) {
1934
+ else if (fieldIndex === fieldCount - 1) {
1478
1935
  row.getCell(fieldIndex + 2).border = {
1479
1936
  right: { style: 'thick' }
1480
1937
  };
1481
1938
  }
1482
1939
  });
1483
1940
  // Data
1484
- result['f_0'].forEach(function (res, resIndex) {
1941
+ getMaxRows(result).forEach(function (res, resIndex) {
1485
1942
  currentRow += 1;
1486
1943
  row = ws.getRow(currentRow);
1487
1944
  fields.forEach(function (field, fieldIndex) {
1488
- if (field.fieldType === 'Number' && typeof (result[field.id][resIndex]) === 'string' && result[field.id][resIndex]) {
1489
- row.getCell(fieldIndex + 2).value = parseFloat(result[field.id][resIndex].replace(new RegExp(/\,/g), '').replace(new RegExp(/\$/g), ''));
1945
+ var value = null;
1946
+ if (Array.isArray(result[field.id])) {
1947
+ value = result[field.id][resIndex] !== undefined ? result[field.id][resIndex] : result[field.id][result[field.id].length - 1];
1948
+ }
1949
+ else {
1950
+ value = result[field.id];
1951
+ }
1952
+ if (field.fieldType === 'Number' && typeof (value) === 'string' && value) {
1953
+ row.getCell(fieldIndex + 2).value = parseFloat(value.replace(new RegExp(/\,/g), '').replace(new RegExp(/\$/g), ''));
1490
1954
  }
1491
1955
  else {
1492
- row.getCell(fieldIndex + 2).value = result[field.id][resIndex];
1956
+ row.getCell(fieldIndex + 2).value = value;
1493
1957
  }
1494
1958
  if (field.leafFormatType === 'Currency') {
1495
1959
  row.getCell(fieldIndex + 2).numFmt = '"$"#,##0.00';
@@ -1506,7 +1970,7 @@ function tabGroupExcelRecursive(report, ws, currentRow, level, result, fields) {
1506
1970
  left: { style: 'thick' }
1507
1971
  };
1508
1972
  }
1509
- else if (fieldIndex === report.fields_selected.filter(function (a) { return a.show; }).length - 1) {
1973
+ else if (fieldIndex === fieldCount - 1) {
1510
1974
  row.getCell(fieldIndex + 2).border = {
1511
1975
  right: { style: 'thick' }
1512
1976
  };
@@ -1539,7 +2003,7 @@ function tabGroupExcelRecursive(report, ws, currentRow, level, result, fields) {
1539
2003
  bottom: { style: 'thick' }
1540
2004
  };
1541
2005
  }
1542
- else if (fieldIndex === report.fields_selected.filter(function (a) { return a.show; }).length - 1) {
2006
+ else if (fieldIndex === fieldCount - 1) {
1543
2007
  row.getCell(fieldIndex + 2).border = {
1544
2008
  top: { style: 'thin' },
1545
2009
  bottom: { style: 'thick' },
@@ -1587,14 +2051,16 @@ function tabGroupExcelWidthRecursive(report, level, result, cols, fields) {
1587
2051
  }
1588
2052
  else {
1589
2053
  var res = result[field.id];
1590
- if (res) {
1591
- length = res.length + 3;
2054
+ var length_1 = 10;
2055
+ if (res !== null && res !== undefined) {
2056
+ var resStr = (typeof res === 'string') ? res : "".concat(res);
2057
+ length_1 = resStr.length + 3;
1592
2058
  }
1593
2059
  if (!cols[fieldIndex]) {
1594
2060
  cols[fieldIndex] = Math.max(10, field.columnName.length);
1595
2061
  }
1596
- if (length > cols[fieldIndex]) {
1597
- cols[fieldIndex] = length;
2062
+ if (length_1 > cols[fieldIndex]) {
2063
+ cols[fieldIndex] = length_1;
1598
2064
  }
1599
2065
  }
1600
2066
  });