dawarich/app/services/visits/smart_detect.rb

43 lines
1.1 KiB
Ruby
Raw Permalink Normal View History

2025-03-05 14:04:26 -05:00
# frozen_string_literal: true
module Visits
# Coordinates the process of detecting and creating visits from tracked points
class SmartDetect
MINIMUM_VISIT_DURATION = 3.minutes
2025-03-05 14:04:26 -05:00
MAXIMUM_VISIT_GAP = 30.minutes
MINIMUM_POINTS_FOR_VISIT = 3
attr_reader :user, :start_at, :end_at, :points
def initialize(user, start_at:, end_at:)
@user = user
@start_at = start_at.to_i
@end_at = end_at.to_i
@points = user.points.not_visited
2025-03-05 14:04:26 -05:00
.order(timestamp: :asc)
.where(timestamp: start_at..end_at)
2025-03-02 15:24:57 -05:00
end
2025-03-03 14:11:21 -05:00
2025-03-05 14:04:26 -05:00
def call
return [] if points.empty?
2025-03-03 14:11:21 -05:00
2025-03-05 14:04:26 -05:00
potential_visits = Visits::Detector.new(points).detect_potential_visits
2025-03-09 11:29:16 -04:00
merged_visits = Visits::Merger.new(points).merge_visits(potential_visits)
grouped_visits = group_nearby_visits(merged_visits).flatten
2025-03-03 14:11:21 -05:00
2025-03-05 14:04:26 -05:00
Visits::Creator.new(user).create_visits(grouped_visits)
2025-03-02 15:24:57 -05:00
end
2025-03-05 14:04:26 -05:00
private
2025-03-05 14:04:26 -05:00
def group_nearby_visits(visits)
visits.group_by do |visit|
[
(visit[:center_lat] * 1000).round / 1000.0,
(visit[:center_lon] * 1000).round / 1000.0
]
end.values
end
2025-03-02 15:24:57 -05:00
end
end