Class: Spree::StockReservations::Reserve

Inherits:
Object
  • Object
show all
Includes:
Spree::ServiceModule::Base
Defined in:
app/services/spree/stock_reservations/reserve.rb

Instance Method Summary collapse

Methods included from Spree::ServiceModule::Base

prepended

Instance Method Details

#call(order:) ⇒ Object



6
7
8
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'app/services/spree/stock_reservations/reserve.rb', line 6

def call(order:)
  return success(order) unless Spree::Config[:stock_reservations_enabled]

  expires_at = Time.current + Spree::StockReservation.ttl_for(order)

  ApplicationRecord.transaction do
    targets = build_targets(order)
    break if targets.empty?

    # Pessimistic lock + fresh read of count_on_hand. The lock serializes
    # concurrent checkouts and we use the locked rows below so we never
    # check stock against a stale association cache.
    locked_stock_items = Spree::StockItem
      .where(id: targets.map { |_, si| si.id })
      .lock
      .index_by(&:id)

    held = held_by_others(locked_stock_items.keys, order.id)
    existing = existing_reservations_for(targets)

    this_order_used = Hash.new(0)

    targets.each do |line_item, stock_item|
      stock_item = locked_stock_items.fetch(stock_item.id)
      available = stock_item.count_on_hand - held.fetch(stock_item.id, 0) - this_order_used[stock_item.id]

      if available < line_item.quantity
        raise InsufficientStockError.new(
          line_item,
          Spree.t(
            :insufficient_stock_for_reservation,
            default: '%{item} has only %{available} available',
            item: line_item.variant.name,
            available: [available, 0].max
          )
        )
      end

      this_order_used[stock_item.id] += line_item.quantity

      reservation = existing[[stock_item.id, line_item.id]] ||
                    Spree::StockReservation.new(stock_item: stock_item, line_item: line_item)
      reservation.order = order
      reservation.quantity = line_item.quantity
      reservation.expires_at = expires_at
      reservation.save!
    end
  end

  success(order)
rescue InsufficientStockError => e
  failure(e.line_item, e.message)
end