Skip to content

Commit

Permalink
Refactor: move charging logic from cb to rate
Browse files Browse the repository at this point in the history
  • Loading branch information
isimluk committed Nov 18, 2016
1 parent 631a8ca commit d714d67
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 26 deletions.
27 changes: 3 additions & 24 deletions app/models/chargeback.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,35 +141,14 @@ def calculate_costs(metric_rollup_records, rates, hours_in_interval)

rates.each do |rate|
rate.chargeback_rate_details.each do |r|
if !chargeback_fields_present && r.fixed?
cost = 0
else
metric_value, cost = r.metric_and_cost_by(metric_rollup_records, hours_in_interval)
r.charge(relevant_fields, chargeback_fields_present, metric_rollup_records, hours_in_interval).each do |field, value|
next unless self.class.attribute_names.include?(field)
self[field] = (self[field] || 0) + value
end

accumulate_metrics_and_costs_per_rate(r, metric_value, cost)
end
end
end

def accumulate_metrics_and_costs_per_rate(rate, metric, cost)
col_hash = {}

defined_column_for_report = (relevant_fields & [rate.metric_keys[0], rate.cost_keys[0]]).present?

if defined_column_for_report
rate.metric_keys.each { |col| col_hash[col] = metric }
rate.cost_keys.each { |col| col_hash[col] = cost }
end

col_hash.each do |k, val|
next unless self.class.attribute_names.include?(k)
self[k] ||= 0
self[k] += val
end
end
private :accumulate_metrics_and_costs_per_rate

def self.report_cb_model(model)
model.gsub(/^Chargeback/, "")
end
Expand Down
19 changes: 17 additions & 2 deletions app/models/chargeback_rate_detail.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,21 @@ class ChargebackRateDetail < ApplicationRecord

attr_accessor :hours_in_interval

def charge(relevant_fields, chargeback_fields_present, metric_rollup_records, hours_in_interval)
if !chargeback_fields_present && fixed?
cost = 0
else
metric_value, cost = metric_and_cost_by(metric_rollup_records, hours_in_interval)
end

result = {}
if (relevant_fields & [metric_keys[0], cost_keys[0]]).present?
metric_keys.each { |field| result[field] = metric_value }
cost_keys.each { |field| result[field] = cost }
end
result
end

def max_of_metric_from(metric_rollup_records)
metric_rollup_records.map(&metric.to_sym).max
end
Expand Down Expand Up @@ -210,6 +225,8 @@ def contiguous_tiers?
!error
end

private

def metric_keys
["#{rate_name}_metric", # metric value (e.g. Storage [Used|Allocated|Fixed])
"#{group}_metric"] # total of metric's group (e.g. Storage Total)
Expand All @@ -227,8 +244,6 @@ def metric_and_cost_by(metric_rollup_records, hours_in_interval)
[metric_value, hourly_cost(metric_value) * hours_in_interval]
end

private

def first_tier?(tier,tiers)
tier == tiers.first
end
Expand Down

0 comments on commit d714d67

Please sign in to comment.