Class: SpreeCmCommissioner::Transit::RouteStopCollection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/spree_cm_commissioner/transit/route_stop_collection.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stops = []) ⇒ RouteStopCollection

Returns a new instance of RouteStopCollection.



7
8
9
10
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 7

def initialize(stops = [])
  @stops = stops
  @errors = []
end

Instance Attribute Details

#stopsObject (readonly)

Returns the value of attribute stops.



5
6
7
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 5

def stops
  @stops
end

Class Method Details

.from_hash(array) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 12

def self.from_hash(array)
  # Handle nil, empty array, or string "[]" when loaded from database
  parsed_array = case array
                 when nil
                   []
                 when String
                   JSON.parse(array)
                 else
                   array
                 end

  stops = Array(parsed_array).each_with_index.map do |raw, index|
    hash = raw.to_h.symbolize_keys
    RouteStop.from_hash(hash.merge(sequence: index))
  end

  new(stops)
end

Instance Method Details

#[](index) ⇒ Object



39
40
41
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 39

def [](index)
  @stops[index]
end

#by_locationObject



67
68
69
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 67

def by_location
  @stops.group_by(&:location_id)
end

#by_location_with_dataObject

Fetches vendor places and groups route stops by their location object Returns: { location_obj => [route_stop_a, route_stop_b], location_obj_2 => […] } Example: If you have stops for branches in “Bangkok” and “Chiang Mai”,

this returns all stops grouped by their location object


75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 75

def by_location_with_data
  return {} if @stops.empty?

  # Extract unique vendor_place_ids from all stops
  vendor_place_ids = @stops.map(&:vendor_place_id).compact.uniq
  return {} if vendor_place_ids.empty?

  # Single query: fetch all vendor places with their locations
  # index_by(:id) creates a hash for O(1) lookup: { vendor_place_id => vendor_place_obj }
  vendor_places = SpreeCmCommissioner::VendorPlace.where(id: vendor_place_ids).includes(:location).index_by(&:id)

  grouped = {}
  @stops.each do |stop|
    # Set the vendor_place object on the stop for later use
    stop.vendor_place = vendor_places[stop.vendor_place_id]

    # Get the location from the vendor_place (e.g., "Bangkok" location)
    location = stop.vendor_place&.location
    next if location.nil?

    # Group stops by location object
    grouped[location] ||= []
    grouped[location] << stop
  end

  grouped
end

#each(&block) ⇒ Object



35
36
37
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 35

def each(&block)
  @stops.each(&block)
end

#empty?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 55

def empty?
  @stops.empty?
end

#errorsObject

rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 156

def errors # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
  @errors = []

  # Check each stop is valid
  @stops.each_with_index do |stop, index|
    next if stop.valid?

    stop.errors.each do |error|
      @errors << "Stop #{index}: #{error}"
    end
  end

  # Check for duplicate vendor_place_ids, but allow same location at start/end (circular routes)
  vendor_place_ids = @stops.map(&:vendor_place_id)
  duplicates = vendor_place_ids.tally.select { |_, count| count > 1 }.keys
  duplicates.each do |dup_id|
    # Allow same vendor_place only if it's at first and last stop
    is_first = @stops.first&.vendor_place_id == dup_id && @stops.first.branch?
    is_last = @stops.last&.vendor_place_id == dup_id && @stops.last.branch?
    count_in_stops = vendor_place_ids.count(dup_id)

    # Valid if: appears exactly twice AND is first and last stop
    is_valid = is_first && is_last && count_in_stops == 2

    unless is_valid
      @errors << "vendor_place_id #{dup_id} appears more than once (is_first: #{is_first}, is_last: #{is_last}, count: #{count_in_stops})"
    end
  end

  @errors
end

#firstObject



43
44
45
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 43

def first
  @stops.first
end

#group_by_sequenceObject

Groups route stops by their location in sequence order Returns an array of hashes where each hash contains:

- location: the VendorPlace representing the location
- stops: array of route stops at that location, sorted by sequence

Example usage: @stops.group_by_sequence

location_object_1 => [stop1, stop2, stop3],
location_object_2 => [stop4, stop5]

Stop 0: Location A Stop 1: Location A Stop 2: Location B Stop 3: Location A ← Same location again (For case when the bus has the same origin/destination)



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 116

def group_by_sequence
  return [] if @stops.blank?

  by_location = by_location_with_data || {}

  # location_id => location_vendor_place (the "location" vendor_place in the hash key)
  location_by_id = by_location.keys.index_by(&:id)

  ordered_stops =
    by_location.values
               .flatten
               .compact
               .sort_by { |s| s.sequence.to_i }

  grouped_stops = []
  current_location_id = nil
  current_group = nil

  ordered_stops.each do |stop|
    stop_location_id = stop.location_id

    if stop_location_id != current_location_id
      current_location_id = stop_location_id
      current_group = {
        location: location_by_id[stop_location_id],
        stops: []
      }
      grouped_stops << current_group
    end

    current_group[:stops] << stop
  end

  grouped_stops
end

#lastObject



47
48
49
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 47

def last
  @stops.last
end

#lengthObject



51
52
53
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 51

def length
  @stops.length
end

#multi_leg?Boolean

Returns:

  • (Boolean)


59
60
61
62
63
64
65
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 59

def multi_leg?
  # Count only actual branches (not break stops)
  # Multi-leg requires at least 3 branch points (origin + boarding/drop-off branches + destination)
  # This allows for circular routes where the same location can be both origin and destination,
  # as long as there are at least 3 branch points in total.
  @stops.count(&:branch?) >= 3
end

#to_hObject



31
32
33
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 31

def to_h
  @stops.map(&:to_h)
end

#valid?Boolean

Returns:

  • (Boolean)


152
153
154
# File 'lib/spree_cm_commissioner/transit/route_stop_collection.rb', line 152

def valid?
  errors.empty?
end