dawarich/app/services/maps/hexagon_request_handler.rb

73 lines
1.7 KiB
Ruby
Raw Normal View History

2025-09-16 14:41:53 -04:00
# frozen_string_literal: true
module Maps
class HexagonRequestHandler
def initialize(params:, user: nil)
2025-09-16 14:41:53 -04:00
@params = params
@user = user
2025-09-16 14:41:53 -04:00
end
def call
context = resolve_context
2025-09-18 12:29:46 -04:00
# For authenticated users, we need to find the matching stat
stat = context[:stat] || find_matching_stat(context)
# Use pre-calculated hexagon centers
if stat
2025-09-16 14:41:53 -04:00
cached_result = Maps::HexagonCenterManager.call(
2025-09-18 12:29:46 -04:00
stat: stat,
2025-09-16 14:41:53 -04:00
target_user: context[:target_user]
)
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
attr_reader :params, :user
2025-09-16 14:41:53 -04:00
def resolve_context
Maps::HexagonContextResolver.call(
params: params,
user: user
2025-09-16 14:41:53 -04:00
)
end
2025-09-18 12:29:46 -04:00
def find_matching_stat(context)
return unless context[:target_user] && context[: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
if context[:start_date].is_a?(String)
date = Date.parse(context[:start_date])
elsif context[:start_date].is_a?(Time)
date = context[:start_date].to_date
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
context[:target_user].stats.find_by(year: date.year, month: date.month)
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