dawarich/app/services/maps/hexagon_request_handler.rb

63 lines
1.5 KiB
Ruby
Raw Normal View History

2025-09-16 14:41:53 -04:00
# frozen_string_literal: true
module Maps
class HexagonRequestHandler
2025-09-18 16:23:47 -04:00
def initialize(params:, user: nil, stat: nil, start_date: nil, end_date: nil)
2025-09-16 14:41:53 -04:00
@params = params
@user = user
2025-09-18 16:23:47 -04:00
@stat = stat
@start_date = start_date
@end_date = end_date
2025-09-16 14:41:53 -04:00
end
def call
2025-09-18 12:29:46 -04:00
# For authenticated users, we need to find the matching stat
2025-09-18 16:23:47 -04:00
stat ||= find_matching_stat
2025-09-18 12:29:46 -04:00
if stat
2025-09-18 16:23:47 -04:00
cached_result = Maps::HexagonCenterManager.new(stat:, user:).call
2025-09-16 14:41:53 -04:00
return cached_result[:data] if cached_result&.dig(:success)
end
2025-09-18 12:29:46 -04:00
# No pre-calculated data available - return empty feature collection
Rails.logger.debug 'No pre-calculated hexagon centers available'
empty_feature_collection
2025-09-16 14:41:53 -04:00
end
private
2025-09-18 16:23:47 -04:00
attr_reader :params, :user, :stat, :start_date, :end_date
2025-09-16 14:41:53 -04:00
2025-09-18 16:23:47 -04:00
def find_matching_stat
return unless user && start_date
2025-09-16 19:55:42 -04:00
2025-09-18 12:29:46 -04:00
# Parse the date to extract year and month
2025-09-18 16:23:47 -04:00
if start_date.is_a?(String)
date = Date.parse(start_date)
elsif start_date.is_a?(Time)
date = start_date.to_date
2025-09-18 12:29:46 -04:00
else
return
end
2025-09-16 19:55:42 -04:00
2025-09-18 12:29:46 -04:00
# Find the stat for this user, year, and month
2025-09-18 16:23:47 -04:00
user.stats.find_by(year: date.year, month: date.month)
2025-09-18 12:29:46 -04:00
rescue Date::Error
nil
2025-09-16 14:41:53 -04:00
end
2025-09-16 19:55:42 -04:00
def empty_feature_collection
{
2025-09-18 12:29:46 -04:00
'type' => 'FeatureCollection',
'features' => [],
'metadata' => {
'hexagon_count' => 0,
'total_points' => 0,
'source' => 'pre_calculated'
2025-09-16 19:55:42 -04:00
}
}
end
2025-09-16 14:41:53 -04:00
end
2025-09-16 19:55:42 -04:00
end