Skip to content

Commit

Permalink
fix: Handle invalid metric in ReportsController (chatwoot#8086)
Browse files Browse the repository at this point in the history
Co-authored-by: Pranav Raj S <[email protected]>

Fixes CW-2643
  • Loading branch information
vishnu-narayanan authored Oct 12, 2023
1 parent 9e173fc commit 415bb23
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
15 changes: 14 additions & 1 deletion app/builders/v2/report_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ def initialize(account, params)
end

def timeseries
send(params[:metric])
return send(params[:metric]) if metric_valid?

Rails.logger.error "ReportBuilder: Invalid metric - #{params[:metric]}"
{}
end

# For backward compatible with old report
Expand Down Expand Up @@ -53,6 +56,16 @@ def conversation_metrics

private

def metric_valid?
%w[conversations_count
incoming_messages_count
outgoing_messages_count
avg_first_response_time
avg_resolution_time reply_time
resolutions_count
reply_time].include?(params[:metric])
end

def inbox
@inbox ||= account.inboxes.find(params[:id])
end
Expand Down
28 changes: 28 additions & 0 deletions spec/builders/v2/report_builder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,34 @@
builder = described_class.new(account, params)
expect { builder.timeseries }.to raise_error(ArgumentError)
end

it 'logs error when metric is nil' do
params = {
metric: nil, # Set metric to nil to test this case
type: :account,
since: (Time.zone.today - 3.days).to_time.to_i.to_s,
until: Time.zone.today.end_of_day.to_time.to_i.to_s
}

builder = described_class.new(account, params)

expect(Rails.logger).to receive(:error).with('ReportBuilder: Invalid metric - ')
builder.timeseries
end

it 'calls the appropriate metric method for a valid metric' do
params = {
metric: 'not_conversation_count', # Provide a invalid metric
type: :account,
since: (Time.zone.today - 3.days).to_time.to_i.to_s,
until: Time.zone.today.end_of_day.to_time.to_i.to_s
}

builder = described_class.new(account, params)
expect(Rails.logger).to receive(:error).with('ReportBuilder: Invalid metric - not_conversation_count')

builder.timeseries
end
end

context 'when report type is label' do
Expand Down

0 comments on commit 415bb23

Please sign in to comment.