Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fix stock ledger edge cases from code review

Łukasz Adamczyka7b045dd644b
diff --git a/docs/plans/6.0-inventory-operations.md b/docs/plans/6.0-inventory-operations.md
index ef820b8d43..f11eb08757 100644
--- a/docs/plans/6.0-inventory-operations.md
+++ b/docs/plans/6.0-inventory-operations.md
@@ -89,8 +89,8 @@ These additions live in `6.0-typed-stock-movements.md`; this plan only consumes
- `in_transit` / `partially_received` → receive screen: per-item `quantity_received` input with running totals, optional `discrepancy_reason` per item, "Receive" submit (writes destination `received` movements for the deltas).
- `received` / `cancelled` → read-only summary + activity log.
- **Purchase Order detail** mirrors transfer detail. `draft` → editable line items + costs. `ordered` → frozen line items, "Receive" enabled. Same partial-receive screen.
-- **Variant Inventory tab (on Product detail) gains a History panel.** Reads `GET /api/v3/admin/stock_movements?q[stock_item_variant_id_eq]=…` (the typed-movements admin endpoint), renders `date · location · qty before → after · kind · cause` with the cause linking to the underlying entity (Transfer T-…, PO PO-…, RMA RA-…, Order #…, "Manual adjustment").
-- **Stock Location detail page (settings) gains an Activity tab.** Same data shape, scoped via `q[stock_item_stock_location_id_eq]`. Useful for warehouse reconciliation.
+- **Variant Inventory tab (on Product detail) gains a History panel.** Reads `GET /api/v3/admin/stock_movements?q[stock_level_variant_id_eq]=…` (the typed-movements admin endpoint), renders `date · location · qty before → after · kind · cause` with the cause linking to the underlying entity (Transfer T-…, PO PO-…, RMA RA-…, Order #…, "Manual adjustment").
+- **Stock Location detail page (settings) gains an Activity tab.** Same data shape, scoped via `q[stock_level_stock_location_id_eq]`. Useful for warehouse reconciliation.
- **No standalone "Stock Movements" page.** Movements are always read in the context of a variant or a location. The legacy admin's firehose list is gone.
## Design Details
diff --git a/docs/plans/6.0-typed-stock-movements.md b/docs/plans/6.0-typed-stock-movements.md
index ea6f76d425..dc9960ec8d 100644
--- a/docs/plans/6.0-typed-stock-movements.md
+++ b/docs/plans/6.0-typed-stock-movements.md
@@ -126,19 +126,26 @@ class Spree::StockMovement < Spree.base_class
private
- # The single place count_on_hand and allocated_count change.
+ # The single place count_on_hand and allocated_count change. A correction
+ # applies even to a variant that stopped tracking inventory — that is how
+ # turning tracking off writes its stock away.
def apply_to_stock_level
- return unless stock_level.should_track_inventory?
+ return unless adjusted? || stock_level.should_track_inventory?
case kind
when 'received', 'adjusted' then stock_level.adjust_count_on_hand(quantity)
when 'allocated' then stock_level.adjust_allocated_count(quantity.abs)
- when 'released' then stock_level.adjust_allocated_count(-quantity.abs)
- when 'shipped'
- stock_level.adjust_count_on_hand(-quantity.abs)
- stock_level.adjust_allocated_count(-quantity.abs)
+ when 'released' then stock_level.release_allocated_count(quantity.abs)
+ when 'shipped' then apply_departure
end
end
+
+ # A forced dispatch is the only write allowed below zero, and retiring the
+ # promise keys off the cause: only a dispatch has one to retire.
+ def apply_departure
+ stock_level.adjust_count_on_hand(-quantity.abs, force: force.present?)
+ stock_level.release_allocated_count(quantity.abs) if fulfillment_id.present?
+ end
end
```
@@ -250,8 +257,10 @@ def restock(variant, quantity, cause = nil, persist: true)
move(variant, quantity, kind: 'received', cause: cause, persist: persist)
end
-def unstock(variant, quantity, cause = nil, persist: true)
- move(variant, quantity, kind: 'shipped', cause: cause, persist: persist)
+# `force` is an instruction about this one write, threaded from
+# Fulfillments::Fulfill and never persisted on the row.
+def unstock(variant, quantity, cause = nil, persist: true, force: false)
+ move(variant, quantity, kind: 'shipped', cause: cause, persist: persist, force: force)
end
# Promises against placed orders. The cause is the fulfillment, never the
@@ -272,7 +281,7 @@ end
private
-def move(variant, quantity, kind:, cause: nil, reason: nil, persist: true)
+def move(variant, quantity, kind:, cause: nil, reason: nil, persist: true, force: false)
stock_level = stock_level_or_create(variant)
attributes = { quantity: quantity, kind: kind, reason: reason, **cause_attributes(cause) }
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 2bbb6d8700..f7dca66079 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -658,6 +658,7 @@ export interface ProductVariantInput {
options?: VariantOptionPair[]
/** Per-currency prices. Upserted by currency. */
prices?: VariantPrice[]
+ /** Stock per location. Upserted by location; omitted locations are removed. */
stock_levels?: VariantStockLevel[]
}
@@ -819,9 +820,18 @@ export interface VariantPrice {
compare_at_amount?: string | number | null
}
+/** Stock for one variant at one location. */
export interface VariantStockLevel {
+ /** Prefixed id of the location holding the stock, e.g. `sloc_1234567890`. */
stock_location_id: string
+ /**
+ * Units physically at the location, not units available to sell — stock
+ * promised to placed orders is still counted here until it ships. Sent as
+ * the count the shelf should end at; the API records the difference as an
+ * adjustment in the stock history.
+ */
count_on_hand: number
+ /** Whether this location sells the variant beyond what it holds. */
backorderable?: boolean
}
@@ -851,6 +861,7 @@ export interface VariantCreateParams {
options: [VariantOptionPair, ...VariantOptionPair[]]
/** Per-currency prices. Upserted by currency. */
prices?: VariantPrice[]
+ /** Stock per location. Upserted by location; omitted locations are removed. */
stock_levels?: VariantStockLevel[]
}
@@ -876,6 +887,7 @@ export interface VariantUpdateParams {
options?: VariantOptionPair[]
/** Per-currency prices. Upserted by currency. */
prices?: VariantPrice[]
+ /** Stock per location. Upserted by location; omitted locations are removed. */
stock_levels?: VariantStockLevel[]
}
@@ -1106,8 +1118,16 @@ export interface StockLocationUpdateParams {
pickup_instructions?: string | null
}
+/** Corrects one stock level. */
export interface StockLevelUpdateParams {
+ /**
+ * The count the shelf should end at. The API records the difference as an
+ * `adjusted` movement rather than writing the column, so the correction
+ * appears in the stock history with everything else. Must be a whole number
+ * of zero or more.
+ */
count_on_hand?: number
+ /** Whether this location sells the variant beyond what it holds. */
backorderable?: boolean
/** Labels the correction in the stock history. Defaults to "Manual adjustment". */
reason?: string
diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
index f0f0cf8a89..e735e23793 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb
@@ -19,6 +19,11 @@ module Spree
new_count = attributes.delete('count_on_hand')
reason = attributes.delete('reason').presence || Spree::StockMovement.default_adjustment_reason
+ unless new_count.nil?
+ new_count = parse_count(new_count)
+ return render_validation_error(count_on_hand_errors) if new_count.nil?
+ end
+
ActiveRecord::Base.transaction do
@resource.update!(attributes) if attributes.any?
adjust_count_on_hand(new_count, reason) unless new_count.nil?
@@ -34,12 +39,29 @@ module Spree
# The movement carries the delta, not the new count — it records what
# changed, and the column follows from it.
def adjust_count_on_hand(new_count, reason)
- delta = new_count.to_i - @resource.count_on_hand
+ delta = new_count - @resource.count_on_hand
return if delta.zero?
@resource.stock_location.adjust(@resource.variant, delta, reason: reason)
end
+ # Strictly, because `to_i` reads anything unparseable as zero — and a
+ # zero here is not a no-op but an instruction to write the whole shelf
+ # off. A typo must be refused, never obeyed.
+ #
+ # @return [Integer, nil] nil when the value is not a whole number
+ def parse_count(value)
+ return value if value.is_a?(Integer)
+
+ Integer(value.to_s.strip, exception: false)
+ end
+
+ def count_on_hand_errors
+ Spree::StockLevel.new.errors.tap do |errors|
+ errors.add(:count_on_hand, :not_an_integer)
+ end
+ end
+
def model_class
Spree::StockLevel
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_controller_spec.rb
index 836ac5ab95..6ca531edec 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_levels_controller_spec.rb
@@ -51,6 +51,19 @@ RSpec.describe Spree::Api::V3::Admin::StockLevelsController, type: :controller d
expect(movement.quantity).to eq(42 - count_before)
end
+ # `to_i` reads anything unparseable as zero, and a zero here is not a
+ # no-op — it is an instruction to write the whole shelf off.
+ it 'refuses a count that is not a whole number instead of zeroing the shelf' do
+ count_before = stock_level.count_on_hand
+
+ expect {
+ patch :update, params: { id: stock_level.prefixed_id, count_on_hand: 'invalid' }, as: :json
+ }.not_to change { stock_level.reload.count_on_hand }.from(count_before)
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(stock_level.stock_movements.adjusted).to be_empty
+ end
+
it 'stores a client-supplied reason on the movement' do
patch :update, params: { id: stock_level.prefixed_id, count_on_hand: 42, reason: 'Damaged in transit' }, as: :json
diff --git a/spree/api/spec/integration/spree/api/v3/admin/stock_movements_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/stock_movements_spec.rb
index 42525ab9bb..05f98917f9 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/stock_movements_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/stock_movements_spec.rb
@@ -47,8 +47,8 @@ RSpec.describe 'Admin Stock Movements API', type: :request, swagger_doc: 'api-re
parameter name: :limit, in: :query, type: :integer, required: false, description: 'Number of records per page'
parameter name: :'q[kind_eq]', in: :query, type: :string, required: false,
description: "Filter by kind ('received', 'allocated', 'shipped', 'released', 'adjusted')"
- parameter name: :'q[stock_level_id_eq]', in: :query, type: :integer, required: false,
- description: 'Filter by stock level'
+ parameter name: :'q[stock_level_id_eq]', in: :query, type: :string, required: false,
+ description: 'Filter by stock level, e.g. sl_1234567890'
parameter name: :fields, in: :query, type: :string, required: false,
description: 'Comma-separated list of fields to include. id is always included.'
diff --git a/spree/core/app/models/spree/order_inventory.rb b/spree/core/app/models/spree/order_inventory.rb
index fbb0171467..4e7dd1c534 100644
--- a/spree/core/app/models/spree/order_inventory.rb
+++ b/spree/core/app/models/spree/order_inventory.rb
@@ -143,17 +143,23 @@ module Spree
inventory_unit.save! if inventory_unit.persisted?
end
- shipment.destroy if shipment.fulfillment_items.sum(:quantity).zero?
-
# Removing units from a placed order withdraws their promise. On-hand
# and backordered units go back the same way now — nothing physical
# moved either way.
+ #
+ # Before the fulfillment is destroyed, never after: a destroyed record
+ # reports no allocation (`allocated_quantities` reads nothing for a
+ # record that is not persisted), so releasing afterwards would withdraw
+ # zero and strand the promise on the level with nothing left to release
+ # it.
if order.completed? && removed_quantity.positive? && variant.should_track_inventory?
# Only this fulfillment's own promise can be withdrawn.
released = [removed_quantity, shipment.allocated_quantities[variant.id].to_i].min
shipment.stock_location.release(variant, released, shipment) if released.positive?
end
+ shipment.destroy if shipment.fulfillment_items.sum(:quantity).zero?
+
removed_quantity
end
end
diff --git a/spree/core/app/models/spree/stock_level.rb b/spree/core/app/models/spree/stock_level.rb
index f712677057..11be6196bf 100644
--- a/spree/core/app/models/spree/stock_level.rb
+++ b/spree/core/app/models/spree/stock_level.rb
@@ -157,6 +157,12 @@ module Spree
units.each do |unit|
break unless number.positive?
+ # What this unit takes of the arriving stock — the whole unit, or the
+ # part of it the arrival covers. Read before the split, because the
+ # split leaves `unit.quantity` holding the *remainder*, and subtracting
+ # that would let the next unit be filled from stock already spoken for.
+ filled = [unit.quantity, number].min
+
if unit.quantity > number
# if required quantity is greater than available
# split off and fulfill that
@@ -165,7 +171,7 @@ module Spree
else
unit.fill_backorder
end
- number -= unit.quantity
+ number -= filled
end
end
diff --git a/spree/core/app/models/spree/stock_movement.rb b/spree/core/app/models/spree/stock_movement.rb
index a68e605a1a..46e569cdcb 100644
--- a/spree/core/app/models/spree/stock_movement.rb
+++ b/spree/core/app/models/spree/stock_movement.rb
@@ -49,6 +49,12 @@ module Spree
less_than_or_equal_to: QUANTITY_LIMITS[:max],
only_integer: true
}, allow_nil: true
+ # The three order-driven kinds carry their direction in the kind, so they
+ # are written positive and read through `abs`. Accepting a negative would
+ # store a row whose sign contradicts the change it caused — the ledger
+ # would say one thing and the shelf another.
+ validates :quantity, numericality: { greater_than: 0 }, allow_nil: true,
+ if: -> { allocated? || released? || shipped? }
validates :reason, presence: true, if: :adjusted?
scope :recent, -> { order(created_at: :desc) }
diff --git a/spree/core/app/models/spree/stock_transfer.rb b/spree/core/app/models/spree/stock_transfer.rb
index eff822cd3a..98b1a5f440 100644
--- a/spree/core/app/models/spree/stock_transfer.rb
+++ b/spree/core/app/models/spree/stock_transfer.rb
@@ -49,6 +49,15 @@ module Spree
return false
end
+ # Before the availability check, which a negative quantity would sail
+ # through — every count is greater than a negative number. The move would
+ # then write a negative in both directions and take stock off the source
+ # *and* the destination.
+ unless positive_quantities?(variants)
+ errors.add(:base, Spree.t('stock_transfer.errors.invalid_quantity'))
+ return false
+ end
+
unless variants_available_in_source_location?(source_location, variants)
errors.add(:base, Spree.t('stock_transfer.errors.variants_unavailable'))
return false
@@ -94,6 +103,10 @@ module Spree
# Each variant needs enough available stock for the quantity being moved,
# not merely some. Checking only for a positive balance let a transfer take
# more than the shelf held and leave it negative.
+ def positive_quantities?(variants)
+ variants.all? { |_variant, quantity| quantity.to_i.positive? }
+ end
+
def variants_available_in_source_location?(source_location, variants)
return true if source_location.nil?
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index 00250badc9..8aa777b91b 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -629,6 +629,10 @@ module Spree
stock_levels_params.each do |stock_data|
stock_data = stock_data.to_h.with_indifferent_access
location = Spree::StockLocation.find_by_param(stock_data[:stock_location_id])
+ # A stale or foreign location id is skipped rather than raising, which
+ # is what #stock_levels_attributes= already does for the same payload.
+ next if location.nil?
+
location_ids_in_payload << location.id
set_stock(stock_data[:count_on_hand], stock_data[:backorderable], location)
end
diff --git a/spree/core/app/services/spree/products/duplicator.rb b/spree/core/app/services/spree/products/duplicator.rb
index 38ac03b64c..3078de4284 100644
--- a/spree/core/app/services/spree/products/duplicator.rb
+++ b/spree/core/app/services/spree/products/duplicator.rb
@@ -66,6 +66,10 @@ module Spree
stock_levels.map do |stock_level|
new_stock_level = stock_level.dup
new_stock_level.count_on_hand = 0
+ # A promise belongs to the order that made it, never to a copy of the
+ # product it was made against. Carried over, the duplicate would open
+ # holding stock for someone else's order and read as negative.
+ new_stock_level.allocated_count = 0
new_stock_level
end
end
diff --git a/spree/core/app/workflows/spree/fulfillments/fulfill.rb b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
index a930b880e1..1dd8bb626f 100644
--- a/spree/core/app/workflows/spree/fulfillments/fulfill.rb
+++ b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
@@ -189,8 +189,11 @@ module Spree
# A canceled fulfillment gets its promise back on the way out (see
# #reallocate_if_resuming_from_canceled), so what it is about to take
- # is its whole manifest rather than the nothing it holds right now.
- allocated = @source.canceled? ? held : @source.allocated_quantities
+ # is its whole manifest rather than the nothing it holds right now —
+ # minus the variants that keep no stock, which the writes skip and the
+ # check must skip too, or it would refuse a dispatch over a shelf that
+ # was never kept for them.
+ allocated = @source.canceled? ? tracked_only(held) : @source.allocated_quantities
return {} if allocated.empty?
wanted =
@@ -208,6 +211,18 @@ module Spree
end
end
+ # @param quantities [Hash{Integer => Integer}]
+ # @return [Hash{Integer => Integer}]
+ def tracked_only(quantities)
+ return quantities if quantities.empty?
+
+ tracked = Spree::Variant.with_deleted.where(id: quantities.keys).select do |variant|
+ variant.should_track_inventory?
+ end.map(&:id)
+
+ quantities.slice(*tracked)
+ end
+
# Each requested quantity has to exist in *this* fulfillment. Without
# this the split would silently pull units out of a sibling fulfillment,
# shipping goods the merchant did not select.
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index ee57f82145..f938524b9d 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1602,6 +1602,7 @@ en:
stock_movements: Stock Movements
stock_transfer:
errors:
+ invalid_quantity: Every variant must move a quantity above zero
must_have_variant: You must add at least one variant
same_location: cannot be the same as the destination location
variants_unavailable: Some variants are not available on %{stock}
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 6cafe02828..5b979c29b2 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -135,6 +135,21 @@ module Spree
Spree::Deprecation.warn('Spree.queues.taxons is deprecated and will be removed in Spree 6.1. Use Spree.queues.categories instead.') if defined?(Spree::Deprecation)
categories
end
+
+ # @deprecated Renamed with the stock level rename in 6.0; removed in 6.1.
+ #
+ # The writer matters as much as the reader here: this is an OpenStruct, so
+ # an existing initializer assigning the old name would quietly define a
+ # field nobody reads and its jobs would fall back to the default queue.
+ queues.define_singleton_method(:stock_location_stock_items) do
+ Spree::Deprecation.warn('Spree.queues.stock_location_stock_items is deprecated and will be removed in Spree 6.1. Use Spree.queues.stock_location_stock_levels instead.') if defined?(Spree::Deprecation)
+ stock_location_stock_levels
+ end
+
+ queues.define_singleton_method(:stock_location_stock_items=) do |value|
+ Spree::Deprecation.warn('Spree.queues.stock_location_stock_items= is deprecated and will be removed in Spree 6.1. Use Spree.queues.stock_location_stock_levels= instead.') if defined?(Spree::Deprecation)
+ self.stock_location_stock_levels = value
+ end
end
end
diff --git a/spree/core/spec/models/spree/order_inventory_spec.rb b/spree/core/spec/models/spree/order_inventory_spec.rb
index 87e5ad1734..8c642b36b9 100644
--- a/spree/core/spec/models/spree/order_inventory_spec.rb
+++ b/spree/core/spec/models/spree/order_inventory_spec.rb
@@ -250,6 +250,25 @@ describe Spree::OrderInventory, type: :model do
expect(stock_level.reload.allocated_count).to eq(allocated_before - removed)
end
end
+
+ # Draining a fulfillment destroys it, and a destroyed fulfillment reports
+ # no allocation — so releasing after the destroy withdraws nothing and
+ # strands the promise on the level with nothing left to release it.
+ context 'when every unit is removed, so the fulfillment is destroyed' do
+ before { order.touch :completed_at }
+
+ it 'withdraws the promise before the fulfillment goes' do
+ stock_level = shipment.stock_location.stock_level(variant)
+ held = shipment.fulfillment_items.sum(&:quantity)
+ shipment.stock_location.allocate(variant, held, shipment)
+ allocated_before = stock_level.reload.allocated_count
+
+ subject.send(:remove_from_shipment, shipment, held)
+
+ expect(shipment).to be_destroyed
+ expect(stock_level.reload.allocated_count).to eq(allocated_before - held)
+ end
+ end
end
end
diff --git a/spree/core/spec/models/spree/stock_level_spec.rb b/spree/core/spec/models/spree/stock_level_spec.rb
index bdb4783b4d..ac8cd55445 100644
--- a/spree/core/spec/models/spree/stock_level_spec.rb
+++ b/spree/core/spec/models/spree/stock_level_spec.rb
@@ -445,6 +445,32 @@ describe Spree::StockLevel, type: :model do
end
end
+ describe 'filling backorders on restock' do
+ # Splitting leaves `unit.quantity` holding the remainder, so subtracting it
+ # instead of what was filled leaves budget over — and the next unit is then
+ # filled from stock that has already been spoken for.
+ it 'fills only as many units as arrived, across several backordered units' do
+ order = create(:order_ready_to_ship, line_items_count: 1)
+ fulfillment = order.fulfillments.first
+ variant = fulfillment.manifest.first.variant
+ line_item = fulfillment.fulfillment_items.first.line_item
+
+ fulfillment.fulfillment_items.first.update_columns(quantity: 7, status: 'backordered')
+ fulfillment.fulfillment_items.create!(
+ variant: variant, quantity: 4, status: 'backordered',
+ order: order, line_item: line_item
+ )
+
+ level = fulfillment.stock_location.stock_level_or_create(variant)
+ level.update_columns(count_on_hand: 0, allocated_count: 0)
+
+ level.send(:process_backorders, 5)
+
+ filled = fulfillment.fulfillment_items.reload.select(&:on_hand?).sum(&:quantity)
+ expect(filled).to eq(5)
+ end
+ end
+
describe 'allocation counters' do
subject { create(:stock_level, adjust_count_on_hand: false) }
diff --git a/spree/core/spec/models/spree/stock_movement_spec.rb b/spree/core/spec/models/spree/stock_movement_spec.rb
index 9d19f366e6..0eb7a53621 100644
--- a/spree/core/spec/models/spree/stock_movement_spec.rb
+++ b/spree/core/spec/models/spree/stock_movement_spec.rb
@@ -28,6 +28,27 @@ describe Spree::StockMovement, type: :model do
end
end
+ describe 'quantity sign' do
+ let(:stock_level) { create(:stock_level, count_on_hand: 10, backorderable: false) }
+
+ # The kind carries the direction and the effect is read through `abs`, so a
+ # negative row would say one thing while the shelf did another.
+ %w[allocated released shipped].each do |kind|
+ it "refuses a negative quantity for #{kind}" do
+ movement = build(:stock_movement, kind: kind, quantity: -2, stock_level: stock_level)
+
+ expect(movement).not_to be_valid
+ expect(movement.errors[:quantity]).to be_present
+ end
+ end
+
+ it 'still allows a negative adjusted quantity, which writes stock off' do
+ movement = build(:stock_movement, kind: 'adjusted', quantity: -2, reason: 'Shrinkage', stock_level: stock_level)
+
+ expect(movement).to be_valid
+ end
+ end
+
describe 'Constants' do
describe 'KINDS' do
it 'names every movement kind' do
diff --git a/spree/core/spec/models/spree/stock_transfer_spec.rb b/spree/core/spec/models/spree/stock_transfer_spec.rb
index b949c17d9a..47697c6a5e 100644
--- a/spree/core/spec/models/spree/stock_transfer_spec.rb
+++ b/spree/core/spec/models/spree/stock_transfer_spec.rb
@@ -115,6 +115,36 @@ module Spree
end
end
+ describe 'quantity guards' do
+ let(:source) { create(:stock_location_with_items) }
+ let(:destination) { create(:stock_location) }
+ let(:variant) { source.stock_levels.first.variant }
+
+ # A negative quantity sails through the availability check — every count
+ # is greater than a negative number — and then takes stock off the source
+ # *and* the destination.
+ it 'refuses a negative transfer quantity' do
+ transfer = described_class.new
+
+ expect(transfer.transfer(source, destination, { variant => -5 })).to be false
+ expect(transfer.errors[:base]).to be_present
+ end
+
+ it 'refuses a zero transfer quantity' do
+ transfer = described_class.new
+
+ expect(transfer.transfer(source, destination, { variant => 0 })).to be false
+ end
+
+ # A receive has no source, so the availability check never runs and only
+ # this guard stands between a typo and stock disappearing.
+ it 'refuses a negative receive quantity' do
+ transfer = described_class.new
+
+ expect(transfer.receive(destination, { variant => -5 })).to be false
+ end
+ end
+
describe '#receive' do
subject { stock_transfer.receive(destination_location, { variant => 5 }) }
diff --git a/spree/core/spec/models/spree/variant_spec.rb b/spree/core/spec/models/spree/variant_spec.rb
index f1da10ea10..676199713b 100644
--- a/spree/core/spec/models/spree/variant_spec.rb
+++ b/spree/core/spec/models/spree/variant_spec.rb
@@ -1586,8 +1586,17 @@ describe Spree::Variant, type: :model do
expect(si.count_on_hand).to eq(99)
end
end
- end
+
+ # #stock_levels_attributes= already skips an id that does not resolve, so
+ # the two write paths must agree rather than one raising a 500.
+ it 'skips a stock location id that does not resolve' do
+ variant = create(:variant)
+ expect {
+ variant.stock_levels = [{ stock_location_id: 'sloc_DoesNotExist', count_on_hand: 4 }]
+ }.not_to raise_error
+ end
+ end
describe '#options=' do
it 'sets option values via set_option_value' do
product = create(:product)
diff --git a/spree/core/spec/services/spree/products/duplicator_spec.rb b/spree/core/spec/services/spree/products/duplicator_spec.rb
index 5a97735c4e..49f92efc87 100644
--- a/spree/core/spec/services/spree/products/duplicator_spec.rb
+++ b/spree/core/spec/services/spree/products/duplicator_spec.rb
@@ -39,6 +39,23 @@ RSpec.describe Spree::Products::Duplicator do
Timecop.return
end
+ describe 'stock level duplication' do
+ # A promise belongs to the order that made it. Copied onto the duplicate,
+ # it would open holding stock for somebody else's order.
+ it 'starts the copy with no stock and no promise' do
+ original = product.variants_including_master.first
+ level = original.stock_levels.first
+ level.update_columns(count_on_hand: 7, allocated_count: 3)
+
+ new_product = subject.value
+
+ new_product.variants_including_master.flat_map(&:stock_levels).each do |copy|
+ expect(copy.count_on_hand).to eq(0)
+ expect(copy.allocated_count).to eq(0)
+ end
+ end
+ end
+
describe 'image duplication' do
it 'clones images by default' do
expect { duplicate }.to change { Spree::Image.count }.by(1)
diff --git a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
index 59287bfca4..ecb6edc8cc 100644
--- a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
+++ b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
@@ -162,6 +162,21 @@ module Spree
describe 'fulfilling a canceled fulfillment' do
before { fulfillment.update!(status: 'canceled') }
+ # A variant that keeps no stock is skipped by every write, so the
+ # shelf-cover check has to skip it too — otherwise a canceled dispatch of
+ # untracked goods is refused over a level nobody maintains.
+ it 'dispatches when the goods are untracked and no shelf is kept for them' do
+ fulfillment.manifest.each do |item|
+ item.variant.update!(track_inventory: false)
+ fulfillment.stock_location.stock_level(item.variant)&.update_columns(count_on_hand: 0)
+ end
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result).to be_success
+ expect(fulfillment.reload).to be_fulfilled
+ end
+
it 're-promises the units and then ships them' do
stock_the_shelf(fulfillment)
variant = fulfillment.fulfillment_items.first.variant