You are here

function commerce_reports_views_query_alter in Commerce Reporting 8

Same name and namespace in other branches
  1. 7.4 includes/views/commerce_reports.views.inc \commerce_reports_views_query_alter()
  2. 7.3 includes/views/commerce_reports.views.inc \commerce_reports_views_query_alter()

Implements hook_views_query_alter().

When using aggregation, Views will apply the same grouping function to all additional fields. That means performing a SUM or AVG on a price field will cause SUM/AVG to run on the currency code column, which is a string. This causes a price field's data to be calculated together even though there may be different currency codes.

@link https://www.drupal.org/project/drupal/issues/2975149

File

./commerce_reports.module, line 30

Code

function commerce_reports_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

  // Only act on report entity views.
  $base_entity_type = $view
    ->getBaseEntityType();
  if (!$base_entity_type || $base_entity_type
    ->id() != 'commerce_order_report') {
    return;
  }

  // Only act on SQL queries (do not act on Search API queries, for example.)
  if (!$query instanceof Sql) {
    return;
  }
  foreach ($view->field as $field_plugin) {

    // If a field has an aggregation function, the display changes it to be
    // a numeric field handler. We want to stop these fields from applying the
    // same aggregate function to their additional fields (langcode, delta,
    // currency code, etc.)
    if ($field_plugin instanceof NumericField) {
      $aliases = $field_plugin->aliases;

      // The current field is in the alias array, remove it so that we preserve
      // the desired aggregation function.
      unset($aliases[$field_plugin->realField]);

      // Remove the aggregation function from all additional fields.
      foreach ($aliases as $alias) {
        unset($query->fields[$alias]['function']);
      }
    }
  }
}