t27duck / active_reporting

OLAP-like DSL for ActiveRecord-based reporting
MIT License
136 stars 19 forks source link

Add aggregate expression FactModel feature #13

Closed niborg closed 1 year ago

niborg commented 6 years ago

We needed more granular control over the aggregate function results, as our data was not perfectly modeled to get what we wanted. So we added the aggregate_expression declaration to the fact model API, which allowed us to mix in some SQL when needed. Works like so:

# Assume a `Case` model. Has an expected_recovery column for what might be obtained,
# expected_hours for how many hours expected to be worked, and a `type` column that
# can be "pro bono" (free), "contingency" (take 30% of expected_recovery),  or "hourly"
# (expected hours times $300).
#
class CaseFactModel < ActiveReporting::FactModel
  aggregate_expression(
    :expected_money_agg_exp,
    "CASE WHEN type = 'pro bono' THEN 0 " \
    "WHEN type = 'contingency' THEN expected_recovery * 0.3 " \
    "WHEN type = 'hourly' THEN expected_hours * 300 END"
  )
end

metric = ActiveReporting::Metric.new(
  :my_metric,
  fact_model: CaseFactModel,
  aggregate: { sum: :expected_money_agg_exp }
)

Of course, Metric still works as it previous did as well. We have been using this feature in our production app with no issues.

Hope you think this is something that would be constructive to your delightful gem! As always, open to any feedback.

niborg commented 6 years ago

Seems to not be working on Travis with Rails 4.2 & Postgres. I can't replicate locally, will try to figure it out when I have a moment.

andresgutgon commented 6 years ago

What's the status of this PR? @t27duck do you see it ok?

andresgutgon commented 6 years ago

image

@niborg did you tried to do a new commit? Maybe was a Travis issue. I saw the same in another PR I did in this project

t27duck commented 6 years ago

@andresgutgon - I already tried re-running CI on this branch. It has something to do with Rails 4.2

niborg commented 6 years ago

Haven't had the time to figure out the issue yet, unfortunately.

niborg commented 1 year ago

Closing as I think the passage of time indicates this is not relevant to anyone anymore :)