Class: Admin::AiUsageLogsController

Inherits:
CrmController
  • Object
show all
Defined in:
app/controllers/admin/ai_usage_logs_controller.rb

Instance Method Summary collapse

Instance Method Details

#indexObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'app/controllers/admin/ai_usage_logs_controller.rb', line 6

def index
  @period     = params[:period].presence&.to_i || 30
  @feature    = params[:feature].presence
  @provider   = params[:provider].presence
  @user_id    = params[:user_id].presence&.to_i

  @since      = @period.days.ago

  @features   = AiUsageLog.distinct.pluck(:feature).compact.sort
  @users      = Account.joins(:party)
                       .where(id: AiUsageLog.where.not(account_id: nil).select(:account_id).distinct)
                       .pluck('parties.full_name', 'accounts.id')
                       .sort_by(&:first)

  base = AiUsageLog.where('created_at >= ?', @since)
  base = base.where(feature: @feature)   if @feature.present?
  base = base.where(provider: @provider)  if @provider.present?
  base = base.where(account_id: @user_id) if @user_id.present?

  # Summary cards
  @total_logs          = base.count
  @total_input_tokens  = base.sum(:input_tokens).to_i
  @total_output_tokens = base.sum(:output_tokens).to_i
  @total_cost_usd      = base.where.not(cost_microdollars: nil).sum(:cost_microdollars).to_f /
                         AiUsageLog::MICRODOLLARS_PER_DOLLAR

  # Rollup by feature (for the period)
  @by_feature = AiUsageLog
                .where('created_at >= ?', @since)
                .group(:feature)
                .pluck(
                  :feature,
                  Arel.sql('COUNT(*) AS calls'),
                  Arel.sql('COALESCE(SUM(input_tokens), 0)'),
                  Arel.sql('COALESCE(SUM(output_tokens), 0)'),
                  Arel.sql('COALESCE(SUM(cost_microdollars), 0)'),
                  Arel.sql('SUM(CASE WHEN cost_microdollars IS NULL THEN 1 ELSE 0 END)')
                )
                .map do |feature, calls, input_t, output_t, cost_micro, null_count|
                  {
                    feature:       feature,
                    calls:         calls,
                    input_tokens:  input_t,
                    output_tokens: output_t,
                    cost_usd:      cost_micro.to_f / AiUsageLog::MICRODOLLARS_PER_DOLLAR,
                    null_cost_count: null_count.to_i
                  }
                end
                .sort_by { |r| -r[:cost_usd] }

  # Rollup by provider + model
  @by_model = AiUsageLog
              .where('created_at >= ?', @since)
              .group(:provider, :model_id)
              .pluck(
                :provider,
                :model_id,
                Arel.sql('COUNT(*) AS calls'),
                Arel.sql('COALESCE(SUM(input_tokens), 0)'),
                Arel.sql('COALESCE(SUM(output_tokens), 0)'),
                Arel.sql('COALESCE(SUM(cost_microdollars), 0)'),
                Arel.sql('SUM(CASE WHEN cost_microdollars IS NULL THEN 1 ELSE 0 END)')
              )
              .map do |provider, model_id, calls, input_t, output_t, cost_micro, null_count|
                {
                  provider:      provider,
                  model_id:      model_id,
                  calls:         calls,
                  input_tokens:  input_t,
                  output_tokens: output_t,
                  cost_usd:      cost_micro.to_f / AiUsageLog::MICRODOLLARS_PER_DOLLAR,
                  null_cost_count: null_count.to_i
                }
              end
              .sort_by { |r| -r[:cost_usd] }

  # Rollup by user (from ai_usage_logs)
  @by_user = AiUsageLog
             .where('ai_usage_logs.created_at >= ?', @since)
             .joins('LEFT JOIN accounts ON accounts.id = ai_usage_logs.account_id')
             .joins('LEFT JOIN parties ON parties.id = accounts.party_id')
             .group(:account_id, 'accounts.login', 'parties.full_name')
             .pluck(
               :account_id,
               Arel.sql('accounts.login'),
               Arel.sql('parties.full_name'),
               Arel.sql('COUNT(*) AS calls'),
               Arel.sql('COALESCE(SUM(input_tokens), 0)'),
               Arel.sql('COALESCE(SUM(output_tokens), 0)'),
               Arel.sql('COALESCE(SUM(cost_microdollars), 0)')
             )
             .map do |, , full_name, calls, input_t, output_t, cost_micro|
               {
                 account_id:    ,
                 name:          full_name.presence || .presence || 'System / Automated',
                 calls:         calls,
                 input_tokens:  input_t,
                 output_tokens: output_t,
                 cost_usd:      cost_micro.to_f / AiUsageLog::MICRODOLLARS_PER_DOLLAR
               }
             end
             .sort_by { |r| -r[:cost_usd] }

  # Sunny Chat usage by user (from assistant_conversations — authoritative source)
  @chat_by_user = AssistantConversation
                  .where('assistant_conversations.created_at >= ?', @since)
                  .joins('JOIN parties ON parties.id = assistant_conversations.user_id')
                  .joins('LEFT JOIN accounts ON accounts.party_id = assistant_conversations.user_id')
                  .group('assistant_conversations.user_id', 'parties.full_name', 'accounts.login')
                  .pluck(
                    Arel.sql('assistant_conversations.user_id'),
                    Arel.sql('parties.full_name'),
                    Arel.sql('accounts.login'),
                    Arel.sql('COUNT(DISTINCT assistant_conversations.id)'),
                    Arel.sql("COALESCE(SUM((metadata->>'total_input_tokens')::int), 0)"),
                    Arel.sql("COALESCE(SUM((metadata->>'total_output_tokens')::int), 0)"),
                    Arel.sql("COALESCE(SUM((metadata->>'total_cost_cents')::float), 0)")
                  )
                  .map do |user_id, full_name, , convos, input_t, output_t, cost|
                    {
                      user_id:       user_id,
                      name:          full_name.presence || .presence || "User ##{user_id}",
                      conversations: convos,
                      input_tokens:  input_t,
                      output_tokens: output_t,
                      cost_usd:      cost
                    }
                  end
                  .sort_by { |r| -r[:cost_usd] }

  # Daily spend for sparkline
  @daily_cost = AiUsageLog
                .where('created_at >= ?', @since)
                .group(Arel.sql("DATE(created_at AT TIME ZONE 'America/Chicago')"))
                .sum(:cost_microdollars)
                .transform_values { |v| v.to_f / AiUsageLog::MICRODOLLARS_PER_DOLLAR }
                .sort.to_h

  # Recent log entries with eager-loaded associations for display
  @logs = base.includes(account: :party)
              .order(created_at: :desc)
              .limit(100)

  # Pre-load conversation titles for entries linked to AssistantConversation
  conv_ids = @logs.select { |l| l.subject_type == 'AssistantConversation' }.map(&:subject_id).compact.uniq
  @conversation_titles = conv_ids.any? ? AssistantConversation.where(id: conv_ids).pluck(:id, :title, :user_id).to_h { |id, title, uid| [id, { title: title, user_id: uid }] } : {}

  # Also extract conversation_ids from metadata (embedding entries store it there)
  meta_conv_ids = @logs.filter_map { |l| l.['conversation_id'] }.uniq - conv_ids
  if meta_conv_ids.any?
    AssistantConversation.where(id: meta_conv_ids).pluck(:id, :title, :user_id).each do |id, title, uid|
      @conversation_titles[id] = { title: title, user_id: uid }
    end
  end
end