active_reporting icon indicating copy to clipboard operation
active_reporting copied to clipboard

Support for multiple aggregations like sum and count together

Open kkrb opened this issue 7 years ago • 1 comments

Hi, At first, excellent work on this gem especially around the multidimensional reporting. I am currently working on a use case for which i need to provide both sum and count values for a vendor for different months which the current gem does not support. Could you please advise on a work around for this? Thanks in advance for your support.

kkrb avatar Jul 03 '18 08:07 kkrb

We have a bunch of aggregates that we need for the same time period. We generate an ActiveReport::Metric for each aggregate using the same filters/dimensions, and then generate a report for each and merge them together by matching the data they all share, such as the created_at key or whatever dimension. Some probably-non-working code to give you an idea:

# Assume `metrics` is an array of ActiveReporting::Metric objects.
metrics.each_with_object([]) do |metric, merged_report|
  metric_key = metric.name.to_s # This is the key that will reference the aggregate result
  report = ActiveReporting::Report.new(metric).run # Get reporting data for the metric
  # Handle first case where merged_report is empty
  merged_report.push(*report) && next if merged_report.empty?
  
  # We have to find where in `merged_report` to put the results in `report`.
  report.each do |row|
    recipient_row = merged_report.find do |potential_recipient_row|
      next if potential_recipient_row[metric_key] # this row has already has a value for this report
      # Do a comparison after stripping all the keys that would differ between any report we
      # could have generated from the `metrics` object. If everything in these rows is the
      # same, then that is the row we want to place our data.
      (potential_recipient_row.keys - metrics.map(&:name).map(&:to_s)).all? do |key|
        row[key] == potential_recipient_row[key]
      end
    end
    recipient_row[metric_key] = row[metric_key] # Now just assign the data to the recipient row
  end
end

niborg avatar Jul 12 '18 16:07 niborg