Class: Spree::StockLevel

Inherits:
Object
  • Object
show all
Includes:
HasCustomFields, HasExternalReferences, Metadata, CustomEvents
Defined in:
app/models/spree/stock_level.rb,
app/models/spree/stock_level/custom_events.rb

Defined Under Namespace

Modules: CustomEvents

Constant Summary collapse

STOCK_STATUS_SCOPES =

What the Inventory page's stock-status filter can ask for. Each names a scope above; STOCK_STATUS_SCOPES is the allowlist that keeps a request from naming any other method.

%w[in_stock low_stock out_of_stock low_stock_overall out_of_stock_overall
with_incoming with_reserved].freeze

Constants included from CustomEvents

CustomEvents::LEGACY_EVENT_PREFIX, CustomEvents::LEGACY_EVENT_SUFFIXES

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CustomEvents

included, #publish_event

Methods included from HasExternalReferences

#assign_external_references, #external_id_for, #set_external_id

Methods included from Metadata

#private_metadata, #private_metadata=

Class Method Details

.purchasable_arel ⇒ Arel::Nodes::Node

What a customer could still buy from this shelf, as an Arel expression: the same subtraction #purchasable_count makes in Ruby. A list filters on it, so it cannot be a Ruby method. Built through Arel rather than interpolated into a string so the column names are quoted by the adapter and nothing here can carry a fragment.

Returns:

  • (Arel::Nodes::Node)


55
56
57
# File 'app/models/spree/stock_level.rb', line 55

def self.purchasable_arel
  arel_table[:count_on_hand] - arel_table[:allocated_count] - arel_table[:reserved_count]
end

.variant_ids_by_total_purchasable {|total| ... } ⇒ ActiveRecord::Relation

Ids of tracked variants whose purchasable units across every active location satisfy the condition the block builds. Unscoped, so the sum covers all locations even when the caller has narrowed the list to one.

Yield Parameters:

  • total (Arel::Nodes::Node) —

    the summed purchasable units

Returns:

  • (ActiveRecord::Relation) —

    a variant_id subquery



98
99
100
101
102
103
104
105
# File 'app/models/spree/stock_level.rb', line 98

def self.variant_ids_by_total_purchasable
  levels = unscoped.where(deleted_at: nil)
  levels.joins(:stock_location).merge(Spree::StockLocation.active).
    joins(:variant).where(spree_variants: { track_inventory: true, deleted_at: nil }).
    group(:variant_id).
    having(yield(Arel::Nodes::Sum.new([purchasable_arel]))).
    select(:variant_id)
end

Instance Method Details

#adjust_allocated_count(value) ⇒ void

This method returns an undefined value.

Promised units go up and down atomically: two fulfillments allocating the same level concurrently must not read each other's value first, and neither counter update needs the delta that count_on_hand's locked path exists for.

Touched afterwards because the counter write is a bare SQL update: it runs no callbacks, so without this a placement taking the last unit would leave the variant's cache keys and the search index claiming it is still for sale, and would publish no stock_level.updated. Under the old model the same change went through save, and this is what restores it.

Parameters:

  • value (Integer) —

    signed change



189
190
191
192
# File 'app/models/spree/stock_level.rb', line 189

def adjust_allocated_count(value)
  value.negative? ? decrement!(:allocated_count, value.abs) : increment!(:allocated_count, value)
  touch
end

#adjust_count_on_hand(value, force: false) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Physical stock changes through movements only — call a Spree::StockLocation verb rather than this, so the change leaves an audit row. Keeps the locked read-modify-write that #process_backorders needs the delta for.

Parameters:

  • force (Boolean) (defaults to: false) —

    let the write leave the shelf below zero. Only a forced dispatch asks for this: the merchant has decided the parcel left whatever the ledger claims.



146
147
148
149
150
# File 'app/models/spree/stock_level.rb', line 146

def adjust_count_on_hand(value, force: false)
  with_lock do
    set_count_on_hand(count_on_hand + value, force: force)
  end
end

#adjust_incoming_count(value) ⇒ void

This method returns an undefined value.

Units on their way here on an open purchase order or an in-flight transfer. Written only by the workflows that move those documents in and out of that state and by the receipt recorder that lands the units.

Parameters:

  • value (Integer) —

    signed change



254
255
256
# File 'app/models/spree/stock_level.rb', line 254

def adjust_incoming_count(value)
  adjust_clamped_counter(:incoming_count, value)
end

#adjust_reserved_count(value) ⇒ void

This method returns an undefined value.

Units held by checkouts in progress. The counter follows the reservation rows: each row adds itself on create, moves the figure on a quantity change and gives it back on destroy, and Spree::StockReservation.withdraw does the same for a batch delete. Nothing else writes it; the spree:stock:recount_levels task repairs drift, but another writer is the bug.

Parameters:

  • value (Integer) —

    signed change



244
245
246
# File 'app/models/spree/stock_level.rb', line 244

def adjust_reserved_count(value)
  adjust_clamped_counter(:reserved_count, value)
end

#available? ⇒ Boolean

Tells whether it's available to be included in a shipment

Returns:

  • (Boolean)


172
173
174
# File 'app/models/spree/stock_level.rb', line 172

def available?
  in_stock? || backorderable?
end

#available_count ⇒ Integer

Physical stock minus allocated units at this stock level. Distinct from Spree::Stock::Quantifier#available_stock, which sums this across all stock levels belonging to a variant.

Returns:

  • (Integer)


221
222
223
# File 'app/models/spree/stock_level.rb', line 221

def available_count
  count_on_hand - allocated_count
end

#backordered_inventory_units ⇒ Object



133
134
135
# File 'app/models/spree/stock_level.rb', line 133

def backordered_inventory_units
  Spree::FulfillmentItem.backordered_for_stock_level(self)
end

#in_stock? ⇒ Boolean

Units that are physically here and not already promised to a placed order — what a customer can still buy from this level.

Returns:

  • (Boolean)


167
168
169
# File 'app/models/spree/stock_level.rb', line 167

def in_stock?
  available_count.positive?
end

#purchasable_count ⇒ Integer

Units a customer could still buy from this shelf: what is here, minus what placed orders have taken, minus what checkouts in progress are holding. The figure the Inventory page calls Available, and the Ruby twin of purchasable_arel, which the in_stock scopes filter on.

Returns:

  • (Integer)


231
232
233
# File 'app/models/spree/stock_level.rb', line 231

def purchasable_count
  available_count - reserved_count
end

#reduce_count_on_hand_to_zero ⇒ Object



258
259
260
# File 'app/models/spree/stock_level.rb', line 258

def reduce_count_on_hand_to_zero
  set_count_on_hand(0) if count_on_hand > 0
end

#release_allocated_count(units) ⇒ void

This method returns an undefined value.

Withdraws up to units of promise. Only a promise that exists can be withdrawn — stock that leaves without ever having been allocated (a stock transfer, or a fulfillment created before typed movements) must not drive the counter below zero, which would make the level look more available than it is.

Locked, unlike its counterpart #adjust_allocated_count: the cap is read from the same counter the write then moves, so two concurrent releases reading before either writes would both pass a cap that only covered one of them.

Parameters:

  • units (Integer)


207
208
209
210
211
212
213
214
# File 'app/models/spree/stock_level.rb', line 207

def release_allocated_count(units)
  with_lock do
    withdrawn = [units.abs, allocated_count].min
    next if withdrawn.zero?

    adjust_allocated_count(-withdrawn)
  end
end

#set_count_on_hand(value, force: false) ⇒ Object

Parameters:



153
154
155
156
157
158
159
160
161
162
163
# File 'app/models/spree/stock_level.rb', line 153

def set_count_on_hand(value, force: false)
  @forced_count_on_hand = force
  self.count_on_hand = value
  process_backorders(count_on_hand - count_on_hand_was)

  save!
ensure
  # Scoped to this write: the exemption must not outlive the call that
  # asked for it.
  @forced_count_on_hand = false
end