Class: SpreeCmCommissioner::Routes::Create

Inherits:
Object
  • Object
show all
Includes:
Spree::ServiceModule::Base
Defined in:
app/services/spree_cm_commissioner/routes/create.rb

Instance Method Summary collapse

Instance Method Details

#call(vendor:, route_params:, route_stops:) ⇒ Object

Parameters:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/services/spree_cm_commissioner/routes/create.rb', line 9

def call(vendor:, route_params:, route_stops:)
  # vendor_id, tenant_id, origin_place_id, destination_place_id are excluded and set automatically.
  attrs = ::Spree::PermittedAttributes.route_attributes
                                      .index_with { |attr_key| route_params[attr_key] }
                                      .except(:vendor_id, :tenant_id, :route_stops, :origin_place_id, :destination_place_id)
                                      .compact

  return failure(nil, 'Route stops are required') if route_stops.length < 2

  origin_place = find_place_for(route_stops, route_stops.first)
  destination_place = find_place_for(route_stops, route_stops.last)

  return failure(nil, 'Origin or destination place could not be determined') if origin_place.nil? || destination_place.nil?
  return failure(nil, 'Route with origin & destination already exists') if vendor.routes.exists?(
    origin_place_id: origin_place.id,
    destination_place_id: destination_place.id
  )

  attrs = attrs.merge(
    tenant_id: vendor.tenant_id,
    route_name: attrs[:route_name] || "#{origin_place.name} -> #{destination_place.name}",
    service_origin_id: vendor.service_origin_id,
    origin_place_id: origin_place.id,
    destination_place_id: destination_place.id,
    route_stops: route_stops
  )

  route = vendor.routes.new(attrs)
  if route.save
    success(route: route)
  else
    failure(route.errors)
  end
end

#find_place_for(route_stops, route_stop) ⇒ Object



44
45
46
47
48
49
# File 'app/services/spree_cm_commissioner/routes/create.rb', line 44

def find_place_for(route_stops, route_stop)
  return nil if route_stop.nil?

  @locations ||= SpreeCmCommissioner::VendorPlace.where(id: route_stops.map(&:location_id).uniq).includes(:place).index_by(&:id)
  @locations[route_stop.location_id]&.place
end