Class: SpreeCmCommissioner::Cart::AddGuest

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

Instance Method Summary collapse

Instance Method Details

#call(order:, line_item:) ⇒ 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
# File 'app/services/spree_cm_commissioner/cart/add_guest.rb', line 6

def call(order:, line_item:)
  # Release holds BEFORE mutating, using the quantities the hold was placed against
  # (Release reads live line items). Only release when this guest will actually bump
  # the quantity. Guard on success and abort if it fails.
  if should_increase_quantity?(line_item)
    release = order.release_order_holds(reason: :cart_changed)
    return release unless release.success?
  end

  # Lock the line item (SELECT ... FOR UPDATE) so concurrent guest add/remove
  # on the same line item are serialized. with_lock reloads the record inside
  # the lock, so quantity/guests reflect the latest committed state before we
  # read-modify-write them. Without this, two simultaneous requests would
  # clobber each other's quantity update.
  line_item.with_lock do
    create_blank_guest(line_item)
    increase_quantity(line_item) if should_increase_quantity?(line_item)
    recalculate_cart(order, line_item)
  end

  success(order: order, line_item: line_item)
rescue ActiveRecord::RecordInvalid => e
  # Convert ONLY the out-of-stock failures into a failure result. The stock validator tags
  # its error with one of two types (see AvailabilityValidatorDecorator): the ordinary
  # :selected_quantity_not_available, or :stock_reserved when the only stock left is
  # withheld for a private sale. BOTH must be listed — nothing upstream rescues
  # RecordInvalid, so a missing type is an uncaught 500 rather than a 422.
  # The raise rolls back the lock transaction (so the blank guest is not persisted);
  # returning it as a failure lets the caller render the availability message.
  #
  # Anything else a different line item validation, or an invalid order/shipment
  # raised by recalculate_cart is re-raised so genuine backend errors are not
  # masked behind an empty quantity error.
  stock_error = %i[selected_quantity_not_available stock_reserved].any? do |kind|
    e.record.errors.of_kind?(:quantity, kind)
  end

  raise unless e.record == line_item && stock_error

  failure(e.record)
end