Skip to content

A platform for community discussion. Free, open, simple.

FIX: ensure usage report is timezone aware to prevent gaps (#33913)

Keegan Georgefeebe6993a3f
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_usage_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_usage_controller.rb
index ea57cd4a37d..c4ac9dfeb64 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_usage_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_usage_controller.rb
@@ -15,16 +15,33 @@ module DiscourseAi
private
def create_report
+ user_timezone = params[:timezone] || Time.zone.name
+ start_date = parse_date_in_timezone(params[:start_date], user_timezone) || 30.days.ago
+ end_date = parse_date_in_timezone(params[:end_date], user_timezone) || Time.current
+
report =
DiscourseAi::Completions::Report.new(
- start_date: params[:start_date]&.to_date || 30.days.ago,
- end_date: params[:end_date]&.to_date || Time.current,
+ start_date: start_date,
+ end_date: end_date,
+ timezone: user_timezone,
)
report = report.filter_by_feature(params[:feature]) if params[:feature].present?
report = report.filter_by_model(params[:model]) if params[:model].present?
report
end
+
+ def parse_date_in_timezone(date_string, timezone)
+ return nil unless date_string
+
+ # Parse date string in user's timezone
+ Time.zone = timezone
+ Time.zone.parse(date_string)
+ rescue StandardError
+ nil
+ ensure
+ Time.zone = nil # Reset to default
+ end
end
end
end
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs
index 0aaac6b2fc2..0b5869ace52 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs
@@ -25,6 +25,7 @@ import ComboBox from "select-kit/components/combo-box";
export default class AiUsage extends Component {
@service store;
+ @service currentUser;
@tracked startDate = moment().subtract(30, "days").toDate();
@tracked endDate = new Date();
@@ -48,6 +49,8 @@ export default class AiUsage extends Component {
data: {
start_date: moment(this.startDate).format("YYYY-MM-DD"),
end_date: moment(this.endDate).format("YYYY-MM-DD"),
+ timezone:
+ this.currentUser?.user_option?.timezone || moment.tz.guess(),
feature: this.selectedFeature,
model: this.selectedModel,
},
diff --git a/plugins/discourse-ai/lib/completions/report.rb b/plugins/discourse-ai/lib/completions/report.rb
index e90ca12e989..46f0c573837 100644
--- a/plugins/discourse-ai/lib/completions/report.rb
+++ b/plugins/discourse-ai/lib/completions/report.rb
@@ -5,11 +5,16 @@ module DiscourseAi
UNKNOWN_FEATURE = "unknown"
USER_LIMIT = 50
- attr_reader :start_date, :end_date, :base_query
+ attr_reader :start_date, :end_date, :base_query, :timezone
- def initialize(start_date: 30.days.ago, end_date: Time.current)
+ def initialize(start_date: 30.days.ago, end_date: Time.current, timezone: Time.zone.name)
+ @timezone = timezone
+
+ Time.zone = timezone # Set the timezone for parsing dates in the user's timezone
@start_date = start_date.beginning_of_day
@end_date = end_date.end_of_day
+ Time.zone = nil # Reset to default timezone
+
@base_query = AiApiAuditLog.where(created_at: @start_date..@end_date)
end
@@ -100,16 +105,23 @@ module DiscourseAi
def tokens_by_period(period = nil)
period = guess_period(period)
- base_query
- .group("DATE_TRUNC('#{period}', created_at)")
- .order("DATE_TRUNC('#{period}', created_at)")
- .select(
- "DATE_TRUNC('#{period}', created_at) as period",
- "SUM(COALESCE(request_tokens + response_tokens, 0)) as total_tokens",
- "SUM(COALESCE(cached_tokens,0)) as total_cached_tokens",
- "SUM(COALESCE(request_tokens,0)) as total_request_tokens",
- "SUM(COALESCE(response_tokens,0)) as total_response_tokens",
- )
+ results =
+ base_query
+ .group("DATE_TRUNC('#{period}', created_at)")
+ .order("DATE_TRUNC('#{period}', created_at)")
+ .select(
+ "DATE_TRUNC('#{period}', created_at) as period",
+ "SUM(COALESCE(request_tokens + response_tokens, 0)) as total_tokens",
+ "SUM(COALESCE(cached_tokens,0)) as total_cached_tokens",
+ "SUM(COALESCE(request_tokens,0)) as total_request_tokens",
+ "SUM(COALESCE(response_tokens,0)) as total_response_tokens",
+ )
+
+ # Convert periods to user's timezone
+ results.map do |row|
+ row.period = row.period.in_time_zone(timezone)
+ row
+ end
end
def user_breakdown
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb
index a1902a419a4..01981a64fff 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb
@@ -154,6 +154,46 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do
expect(data_by_hour.first[1]["total_tokens"]).to eq(150)
end
end
+
+ context "with different timezones" do
+ before { freeze_time Time.parse("2024-07-28 00:30:00 UTC") }
+
+ let(:base_time) { Time.parse("2024-07-28 00:30:00 UTC") } # 8:30 AM Singapore
+ let(:singapore_tz) { "Asia/Singapore" }
+
+ let!(:log_sg1) do
+ AiApiAuditLog.create!(
+ provider_id: 1,
+ feature_name: "summarize",
+ language_model: "gpt-4",
+ request_tokens: 1000,
+ response_tokens: 50,
+ created_at: base_time,
+ )
+ end
+
+ let!(:log_sg2) do
+ AiApiAuditLog.create!(
+ provider_id: 1,
+ feature_name: "summarize",
+ language_model: "gpt-4",
+ request_tokens: 1000,
+ response_tokens: 50,
+ created_at: base_time - 1.hour,
+ )
+ end
+
+ it "shows correct data across timezone boundaries" do
+ report =
+ DiscourseAi::Completions::Report.new(
+ start_date: base_time.in_time_zone(singapore_tz).beginning_of_day,
+ end_date: base_time.in_time_zone(singapore_tz).end_of_day,
+ timezone: singapore_tz,
+ )
+
+ expect(report.tokens_by_period(:hour).count).to eq(2)
+ end
+ end
end
context "when not admin" do