Search ext: Ensure all non-grouped columns are aggregated if using GROUP BY
authorColeman Watts <coleman@civicrm.org>
Fri, 18 Sep 2020 15:27:20 +0000 (11:27 -0400)
committerColeman Watts <coleman@civicrm.org>
Fri, 18 Sep 2020 18:42:11 +0000 (14:42 -0400)
ext/search/ang/search/crmSearch.component.js

index 703cd364d7743c1848490895a46ca385a1a935b0..5eaaee5ababb199f1894377a02c94cf093956f3b 100644 (file)
@@ -9,6 +9,9 @@
     controller: function($scope, $element, $timeout, crmApi4, dialogService, searchMeta, formatForSelect2) {
       var ts = $scope.ts = CRM.ts(),
         ctrl = this;
+
+      this.DEFAULT_AGGREGATE_FN = 'GROUP_CONCAT';
+
       this.selectedRows = [];
       this.limit = CRM.cache.get('searchPageSize', 30);
       this.page = 1;
         if (!ctrl.params.groupBy[idx]) {
           ctrl.clearParam('groupBy', idx);
         }
+        // Remove aggregate functions when no grouping
+        if (!ctrl.params.groupBy.length) {
+          _.each(ctrl.params.select, function(col, pos) {
+            if (_.contains(col, '(')) {
+              var info = searchMeta.parseExpr(col);
+              if (info.fn.category === 'aggregate') {
+                ctrl.params.select[pos] = info.path + info.suffix;
+              }
+            }
+          });
+        }
       };
 
       /**
         $('.crm-search-results', $element).css('height', '');
       }
 
+      // Ensure all non-grouped columns are aggregated if using GROUP BY
+      function aggregateGroupByColumns() {
+        if (ctrl.params.groupBy.length) {
+          _.each(ctrl.params.select, function(col, pos) {
+            if (!_.contains(col, '(') && ctrl.canAggregate(col)) {
+              ctrl.params.select[pos] = ctrl.DEFAULT_AGGREGATE_FN + '(' + col + ')';
+            }
+          });
+        }
+      }
+
       // Debounced callback for loadResults
       function _loadResultsCallback() {
         // Multiply limit to read 2 pages at once & save ajax requests
 
       function loadResults() {
         $scope.loading = true;
+        aggregateGroupByColumns();
         _loadResults();
       }