Class: LlmCostTracker::Dashboard::ProviderBreakdown

Inherits:
Object
  • Object
show all
Defined in:
app/services/llm_cost_tracker/dashboard/provider_breakdown.rb

Overview

Aggregates cost and call counts per provider for a given scope. Sorted by total cost descending; providers with zero cost fall to the bottom but are still returned so users can see calls without pricing.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope:) ⇒ ProviderBreakdown

Returns a new instance of ProviderBreakdown.



15
16
17
# File 'app/services/llm_cost_tracker/dashboard/provider_breakdown.rb', line 15

def initialize(scope:)
  @scope = scope
end

Class Method Details

.call(scope: LlmCostTracker::LlmApiCall.all) ⇒ Object



11
12
13
# File 'app/services/llm_cost_tracker/dashboard/provider_breakdown.rb', line 11

def self.call(scope: LlmCostTracker::LlmApiCall.all)
  new(scope: scope).rows
end

Instance Method Details

#rowsObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/services/llm_cost_tracker/dashboard/provider_breakdown.rb', line 19

def rows
  grouped = scope
            .group(:provider)
            .select("provider, COUNT(*) AS calls_count, COALESCE(SUM(total_cost), 0) AS total_cost_sum")
            .order(Arel.sql("total_cost_sum DESC, calls_count DESC"))
            .to_a

  total_cost = grouped.sum { |row| row.total_cost_sum.to_f }

  grouped.map do |row|
    cost = row.total_cost_sum.to_f
    ProviderRow.new(
      provider: row.provider,
      calls: row.calls_count.to_i,
      total_cost: cost,
      share_percent: total_cost.positive? ? (cost / total_cost) * 100.0 : 0.0
    )
  end
end