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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Merge branch 'main' into feature/v-3530
Łukasz Adamczyk1f2d330f1f63
diff --cc packages/admin-sdk/src/types/generated/index.tsindex 24457eb9cb,769e1e160a..218f7d7658--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@@ -1,4 -1,4 +1,4 @@@- // Typelizer digest dc73404812d261d8e6ba124e0a473047-// Typelizer digest aea9cb4109ae251400c490dd03ab40de++// Typelizer digest a8cb8ffe4383aa5294d51223946bdf4a//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'@@@ -82,12 -82,10 +82,11 @@@ export type { default as Role } from '.export type { default as Seller } from './Seller'export type { default as SetupTask } from './SetupTask'export type { default as State } from './State'-export type { default as StockItem } from './StockItem'+export type { default as StockLevel } from './StockLevel'export type { default as StockLocation } from './StockLocation'+export type { default as StockMovement } from './StockMovement'export type { default as StockReservation } from './StockReservation'export type { default as StockTransfer } from './StockTransfer'- export type { default as StoreCreditCategory } from './StoreCreditCategory'export type { default as StoreCredit } from './StoreCredit'export type { default as Store } from './Store'export type { default as TaxCategory } from './TaxCategory'diff --cc packages/dashboard/src/schemas/product.tsindex 5017f87063,5d5004f11d..e86e0484cf--- a/packages/dashboard/src/schemas/product.ts+++ b/packages/dashboard/src/schemas/product.ts@@@ -1,7 -1,8 +1,8 @@@import { requiredMessage } from '@spree/dashboard-ui'import { z } from 'zod/v4'+ import { isSupportedVideoUrl } from '../lib/video-url'-export const stockItemFormSchema = z.object({+export const stockLevelFormSchema = z.object({id: z.string().optional(),stock_location_id: z.string(),stock_location_name: z.string().optional(),diff --cc spree/api/app/controllers/concerns/spree/api/v3/admin/product_listing.rbindex 64ba1e260a,2a768907f3..3f75c82830--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/product_listing.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/product_listing.rb@@@ -33,9 -33,9 +33,9 @@@ module Spre:tax_category,:product_type,{ product_publications: :channel },- { primary_media: [attachment_attachment: :blob] },+ { primary_media: [attachment_attachment: :blob, poster_attachment: :blob] },- { default_variant: [:prices, { stock_items: [:stock_location, :active_stock_reservations] }] },- { variants: [:prices, { stock_items: [:stock_location, :active_stock_reservations] }] }+ { default_variant: [:prices, { stock_levels: [:stock_location, :active_stock_reservations] }] },+ { variants: [:prices, { stock_levels: [:stock_location, :active_stock_reservations] }] }]endenddiff --cc spree/api/app/controllers/spree/api/v3/admin/variants_controller.rbindex 8409ec5ee7,b9d09819c1..e1fb8a2269--- a/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/variants_controller.rb@@@ -21,9 -21,9 +21,9 @@@ module Spredef scope_includes[- :prices, stock_items: :stock_location,+ :prices, stock_levels: :stock_location,option_values: :option_type,- primary_media: [attachment_attachment: :blob]+ primary_media: [attachment_attachment: :blob, poster_attachment: :blob]]endenddiff --cc spree/api/app/controllers/spree/api/v3/store/products_controller.rbindex 299c84ff37,be2befa487..defcf5b1e4--- a/spree/api/app/controllers/spree/api/v3/store/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/products_controller.rb@@@ -43,9 -43,9 +43,9 @@@ module Spre:seller,{product_publications: [],- primary_media: [attachment_attachment: :blob],+ primary_media: [attachment_attachment: :blob, poster_attachment: :blob],- default_variant: [:prices, stock_items: [:stock_location, :active_stock_reservations]],- variants: [:prices, :seller, stock_items: [:stock_location, :active_stock_reservations]]+ default_variant: [:prices, stock_levels: [:stock_location, :active_stock_reservations]],+ variants: [:prices, :seller, stock_levels: [:stock_location, :active_stock_reservations]]}]enddiff --cc spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rbindex c4c945861c,d535356526..a26a7707f0--- a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb@@@ -981,13 -981,13 +981,13 @@@ RSpec.describe Spree::Api::V3::Store::Cendit 'releases stock reservations on successful completion' do- create(:payment, cart: order, amount: order.reload.total)+ create(:payment, cart: order, amount: order.reload.total).tap(&:create_payment_profile)line_item = order.line_items.first- line_item.variant.stock_items.first.update!(backorderable: false)- line_item.variant.stock_items.first.set_count_on_hand(20)+ line_item.variant.stock_levels.first.update!(backorderable: false)+ line_item.variant.stock_levels.first.set_count_on_hand(20)create(:stock_reservation,- stock_item: line_item.variant.stock_items.first,+ stock_level: line_item.variant.stock_levels.first,line_item: line_item,cart: order,order: nil,diff --cc spree/core/app/models/spree/stock_level.rbindex f72e0cdcfe,0000000000..3e407dc747mode 100644,000000..100644--- a/spree/core/app/models/spree/stock_level.rb+++ b/spree/core/app/models/spree/stock_level.rb@@@ -1,197 -1,0 +1,185 @@@+module Spree+ class StockLevel < Spree.base_class+ has_prefix_id :sl++ acts_as_paranoid++ include Spree::HasCustomFields+ include Spree::Metadata+ # Dual-emits the pre-rename `stock_item.*` names for one release.+ include Spree::StockLevel::CustomEvents++ publishes_lifecycle_events++ with_options inverse_of: :stock_levels do+ belongs_to :stock_location, class_name: 'Spree::StockLocation'+ belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'+ end+ has_many :stock_movements, inverse_of: :stock_level+ has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :stock_level, dependent: :destroy+ has_many :active_stock_reservations, -> { active }, class_name: 'Spree::StockReservation', inverse_of: :stock_level++ validates :stock_location, :variant, presence: true+ validates :variant_id, uniqueness: { scope: :stock_location_id }, unless: :deleted_at++ validates :count_on_hand, numericality: {+ greater_than_or_equal_to: 0,+ less_than_or_equal_to: 2**31 - 1,+ only_integer: true+ }, if: :verify_count_on_hand?++ delegate :weight, :should_track_inventory?, to: :variant+ delegate :name, to: :variant, prefix: true+ delegate :product, to: :variant+- after_save :conditional_variant_touch, if: :saved_changes?++ after_save(if: :saved_changes?) { variant.touch }+ after_touch { variant.touch }+ after_destroy { variant.touch }++ self.whitelisted_ransackable_attributes = %w[count_on_hand allocated_count stock_location_id variant_id]+ self.whitelisted_ransackable_associations = %w[variant stock_location]++ scope :with_active_stock_location, -> { joins(:stock_location).merge(Spree::StockLocation.active) }++ # Stock levels for products assigned to `store`, walking+ # `variant → product → store`.+ #+ # Used by the admin API as the base scope so the controller can filter+ # directly by stock_location/variant without inheriting+ # `Spree::Store#stock_levels`'s extra joins or the variant default+ # ordering.+ scope :for_store, ->(store) {+ joins(variant: :product).where(spree_products: { store_id: store.id })+ }++ def backordered_inventory_units+ Spree::InventoryUnit.backordered_for_stock_level(self)+ end++ # @api private+ # 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.+ #+ # @param force [Boolean] 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.+ def adjust_count_on_hand(value, force: false)+ with_lock do+ set_count_on_hand(count_on_hand + value, force: force)+ end+ end++ # @param force [Boolean] see {#adjust_count_on_hand}+ 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++ # Units that are physically here and not already promised to a placed+ # order — what a customer can still buy from this level.+ def in_stock?+ available_count.positive?+ end++ # Tells whether it's available to be included in a shipment+ def available?+ in_stock? || backorderable?+ end++ # 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.+ #+ # @param value [Integer] signed change+ # @return [void]+ def adjust_allocated_count(value)+ value.negative? ? decrement!(:allocated_count, value.abs) : increment!(:allocated_count, value)+ end++ # 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.+ #+ # @param units [Integer]+ # @return [void]+ def release_allocated_count(units)+ with_lock do+ withdrawn = [units.abs, allocated_count].min+ next if withdrawn.zero?++ adjust_allocated_count(-withdrawn)+ end+ end++ # 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.+ #+ # @return [Integer]+ def available_count+ count_on_hand - allocated_count+ end++ def reduce_count_on_hand_to_zero+ set_count_on_hand(0) if count_on_hand > 0+ end++ private++ # A shelf can only be driven below zero by a write that asked to, and then+ # it means Spree never saw those goods arrive — a receiving gap that heals+ # itself when the missing `received` movement lands. Every other writer, a+ # correction above all, is stopped: a hand-typed count below zero is a+ # typo, not a fact.+ def verify_count_on_hand?+ count_on_hand_changed? && count_on_hand.negative? &&+ count_on_hand < count_on_hand_was && !@forced_count_on_hand+ end++ # Process backorders based on amount of stock received+ # If stock was -20 and is now -15 (increase of 5 units), then we can process atmost 5 inventory orders.+ # If stock was -20 but then was -25 (decrease of 5 units), do nothing.+ def process_backorders(number)+ return unless number.positive?++ units = backordered_inventory_units.first(number) # We can process atmost n backorders++ 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+ split = unit.split_inventory!(number)+ split.fill_backorder+ else+ unit.fill_backorder+ end+ number -= filled+ end+ end-- def conditional_variant_touch- variant.touch if !Spree::Config.binary_inventory_cache || stock_changed?- end-- def stock_changed?- # the variant_id changes from nil when a new stock location is added- (- saved_change_to_count_on_hand? &&- saved_change_to_count_on_hand.any?(&:zero?)- ) || saved_change_to_variant_id?- end+ end+enddiff --cc spree/core/spec/models/spree/stock_level_spec.rbindex 0deb528f39,0000000000..f328e8c768mode 100644,000000..100644--- a/spree/core/spec/models/spree/stock_level_spec.rb+++ b/spree/core/spec/models/spree/stock_level_spec.rb@@@ -1,592 -1,0 +1,570 @@@+require 'spec_helper'++describe Spree::StockLevel, type: :model do+ subject { stock_location.stock_levels.order(:id).first }++ let(:stock_location) { create(:stock_location_with_items) }++ it_behaves_like 'metadata'+ it_behaves_like 'lifecycle events'++ # The rename would otherwise silently unsubscribe every webhook endpoint a+ # merchant had pointed at stock_item.*. Both names ship for one release.+ describe 'legacy stock_item events', events: true do+ let!(:stock_level) { create(:stock_level) }++ before do+ Spree::Events.reset!+ allow(Spree::Events).to receive(:enabled?).and_return(true)+ end++ after { Spree::Events.reset! }++ # One subscription set per example: calling this twice would count every+ # event twice over.+ def names_published+ received = []+ %w[stock_level stock_item].each do |prefix|+ %w[created updated deleted].each do |suffix|+ Spree::Events.subscribe("#{prefix}.#{suffix}", async: false) { |event| received << event.name }+ end+ end+ Spree::Events.activate!+ yield+ received+ end++ # Creating a level propagates more of them across the store's locations,+ # so what matters is that the two names come out in step.+ it 'publishes created under both names' do+ names = names_published { create(:stock_level) }++ expect(names).to include('stock_level.created', 'stock_item.created')+ expect(names.count('stock_item.created')).to eq(names.count('stock_level.created'))+ end++ it 'publishes updated under both names' do+ names = names_published { stock_level.update!(backorderable: !stock_level.backorderable) }++ expect(names).to contain_exactly('stock_level.updated', 'stock_item.updated')+ end++ it 'publishes deleted under both names' do+ names = names_published { stock_level.destroy! }++ expect(names).to contain_exactly('stock_level.deleted', 'stock_item.deleted')+ end++ it 'carries the same payload on both' do+ payloads = {}+ %w[stock_level.created stock_item.created].each do |name|+ Spree::Events.subscribe(name, async: false) { |event| payloads[name] = event.payload }+ end+ Spree::Events.activate!++ create(:stock_level)++ expect(payloads['stock_item.created']).to eq(payloads['stock_level.created'])+ end++ # The legacy twin follows whatever the real name did, so the touch-only+ # guard in Publishable is not defeated by publishing around it.+ it 'stays silent on a touch-only save' do+ names = names_published { stock_level.touch }++ expect(names).to be_empty+ end++ it 'leaves events this model does not own alone' do+ received = []+ Spree::Events.subscribe('stock_item.custom', async: false) { |event| received << event.name }+ Spree::Events.activate!++ stock_level.publish_event('stock_level.custom')++ expect(received).to be_empty+ end+ end++ it 'maintains the count on hand for a variant' do+ expect(subject.count_on_hand).to eq 10+ end++ it "can return the stock item's variant's name" do+ expect(subject.variant_name).to eq(subject.variant.name)+ end++ context 'available to be included in shipment' do+ context 'has stock' do+ it { expect(subject).to be_available }+ end++ context 'backorderable' do+ before { subject.backorderable = true }++ it { expect(subject).to be_available }+ end++ context 'no stock and not backorderable' do+ before do+ subject.backorderable = false+ allow(subject).to receive_messages(count_on_hand: 0)+ end++ it { expect(subject).not_to be_available }+ end+ end++ describe 'reduce_count_on_hand_to_zero' do+ context 'when count_on_hand > 0' do+ before do+ subject.update_column('count_on_hand', 4)+ subject.reduce_count_on_hand_to_zero+ end++ it { expect(subject.count_on_hand).to eq(0) }+ end++ context 'when count_on_hand > 0' do+ before do+ subject.update_column('count_on_hand', -4)+ @count_on_hand = subject.count_on_hand+ subject.reduce_count_on_hand_to_zero+ end++ it { expect(subject.count_on_hand).to eq(@count_on_hand) }+ end+ end++ context 'adjust count_on_hand' do+ let!(:current_on_hand) { subject.count_on_hand }++ it 'is updated pessimistically' do+ copy = Spree::StockLevel.find(subject.id)++ subject.adjust_count_on_hand(5)+ expect(subject.count_on_hand).to eq(current_on_hand + 5)++ expect(copy.count_on_hand).to eq(current_on_hand)+ copy.adjust_count_on_hand(5)+ expect(copy.count_on_hand).to eq(current_on_hand + 10)+ end++ context 'item out of stock (by five items)' do+ context 'when stock received is insufficient to fulfill backorders' do+ let(:inventory_unit) { double('InventoryUnit') }+ let(:inventory_unit_2) { double('InventoryUnit2') }+ let(:split_inventory_unit) { double('SplitInventoryUnit') }++ before do+ allow(subject).to receive_messages(backordered_inventory_units: [inventory_unit, inventory_unit_2])+ allow(split_inventory_unit).to receive_messages(quantity: 3)+ allow(inventory_unit).to receive_messages(quantity: 4, split_inventory!: split_inventory_unit)+ allow(inventory_unit_2).to receive_messages(quantity: 1)+ subject.update_column(:count_on_hand, -5)+ end++ it 'splits inventory to fulfill partial backorder' do+ expect(inventory_unit_2).not_to receive(:split_inventory!)++ expect(split_inventory_unit).to receive(:fill_backorder)+ expect(inventory_unit).not_to receive(:fill_backorder)+ expect(inventory_unit_2).not_to receive(:fill_backorder)++ subject.adjust_count_on_hand(3)+ expect(subject.count_on_hand).to eq(-2)+ end+ end+ end++ context 'item out of stock (by two items)' do+ let(:inventory_unit) { double('InventoryUnit') }+ let(:inventory_unit_2) { double('InventoryUnit2') }++ before do+ allow(subject).to receive_messages(backordered_inventory_units: [inventory_unit, inventory_unit_2])+ allow(inventory_unit).to receive_messages(quantity: 1)+ allow(inventory_unit_2).to receive_messages(quantity: 1)+ subject.update_column(:count_on_hand, -2)+ end++ # Regression test for #3755+ it 'processes existing backorders, even with negative stock' do+ expect(inventory_unit).to receive(:fill_backorder)+ expect(inventory_unit_2).not_to receive(:fill_backorder)+ subject.adjust_count_on_hand(1)+ expect(subject.count_on_hand).to eq(-1)+ end++ # Test for #3755. Only a dispatch may drive the shelf further below zero+ # now, so this says so at the call.+ it 'does not process backorders when stock is adjusted negatively' do+ expect(inventory_unit).not_to receive(:fill_backorder)+ expect(inventory_unit_2).not_to receive(:fill_backorder)+ subject.adjust_count_on_hand(-1, force: true)+ expect(subject.count_on_hand).to eq(-3)+ end++ context 'adds new items' do+ before { allow(subject).to receive_messages(backordered_inventory_units: [inventory_unit, inventory_unit_2]) }++ it 'fills existing backorders' do+ expect(inventory_unit).to receive(:fill_backorder)+ expect(inventory_unit_2).to receive(:fill_backorder)++ subject.adjust_count_on_hand(3)+ expect(subject.count_on_hand).to eq(1)+ end+ end+ end+ end++ context 'set count_on_hand' do+ let!(:current_on_hand) { subject.count_on_hand }++ it 'is updated pessimistically' do+ copy = Spree::StockLevel.find(subject.id)++ subject.set_count_on_hand(5)+ expect(subject.count_on_hand).to eq(5)++ expect(copy.count_on_hand).to eq(current_on_hand)+ copy.set_count_on_hand(10)+ expect(copy.count_on_hand).to eq(current_on_hand)+ end++ context 'item out of stock (by two items)' do+ let(:inventory_unit) { double('InventoryUnit') }+ let(:inventory_unit_2) { double('InventoryUnit2') }++ before { subject.set_count_on_hand(-2, force: true) }++ it "doesn't process backorders" do+ expect(subject).not_to receive(:backordered_inventory_units)+ end++ context 'adds new items' do+ before do+ allow(subject).to receive_messages(backordered_inventory_units: [inventory_unit, inventory_unit_2])+ allow(inventory_unit).to receive_messages(quantity: 1)+ allow(inventory_unit_2).to receive_messages(quantity: 1)+ end++ it 'fills existing backorders' do+ expect(inventory_unit).to receive(:fill_backorder)+ expect(inventory_unit_2).to receive(:fill_backorder)++ subject.set_count_on_hand(1)+ expect(subject.count_on_hand).to eq(1)+ end+ end+ end+ end++ context 'with stock movements' do+ before { Spree::StockMovement.create(stock_level: subject, quantity: 1, kind: 'received') }++ it 'doesnt raise ReadOnlyRecord error' do+ expect { subject.destroy }.not_to raise_error+ end+ end++ context 'destroyed' do+ before { subject.destroy }++ it 'recreates stock item just fine' do+ expect do+ stock_location.stock_levels.create!(variant: subject.variant)+ end.not_to raise_error+ end++ it 'doesnt allow recreating more than one stock item at once' do+ stock_location.stock_levels.create!(variant: subject.variant)++ expect do+ stock_location.stock_levels.create!(variant: subject.variant)+ end.to raise_error(StandardError)+ end+ end++ describe '#after_save' do+ before do+ subject.variant.update_column(:updated_at, 1.day.ago)+ end+- context 'binary_inventory_cache is set to false (default)' do- context 'in_stock? changes' do- it 'touches its variant' do- expect do- subject.adjust_count_on_hand(subject.count_on_hand * -1)- end.to change { subject.variant.reload.updated_at }- end- end-- context 'in_stock? does not change' do- it 'touches its variant' do- expect do- subject.adjust_count_on_hand((subject.count_on_hand * -1) + 1)- end.to change { subject.variant.reload.updated_at }- end++ context 'in_stock? changes' do++ it 'touches its variant' do++ expect do++ subject.adjust_count_on_hand(subject.count_on_hand * -1)++ end.to change { subject.variant.reload.updated_at }+ end+ end+- context 'binary_inventory_cache is set to true' do- before { Spree::Config.binary_inventory_cache = true }-- context 'in_stock? changes' do- it 'touches its variant' do- expect do- subject.adjust_count_on_hand(subject.count_on_hand * -1)- end.to change { subject.variant.reload.updated_at }- end- end-- context 'in_stock? does not change' do- it 'does not touch its variant' do- expect do- subject.adjust_count_on_hand((subject.count_on_hand * -1) + 1)- end.not_to change { subject.variant.reload.updated_at }- end++ context 'in_stock? does not change' do++ it 'touches its variant' do++ expect do++ subject.adjust_count_on_hand((subject.count_on_hand * -1) + 1)++ end.to change { subject.variant.reload.updated_at }+ end++ end+- context 'when a new stock location is added' do- it 'touches its variant' do- expect do- perform_enqueued_jobs { create(:stock_location, propagate_all_variants: true) }- end.to change { subject.variant.reload.updated_at }- end++ context 'when a new stock location is added' do++ it 'touches its variant' do++ expect do++ perform_enqueued_jobs { create(:stock_location, propagate_all_variants: true) }++ end.to change { subject.variant.reload.updated_at }+ end+ end+ end++ describe '#after_touch' do+ it 'touches its variant' do+ Timecop.scale(1000) do+ expect do+ subject.touch+ end.to change { subject.variant.updated_at }+ end+ end+ end++ # Regression test for #4651+ context 'variant' do+ it 'can be found even if the variant is deleted' do+ subject.variant.destroy+ expect(subject.reload.variant).not_to be_nil+ end+ end++ describe 'validations' do+ describe 'count_on_hand' do+ # How far below zero a level may go is decided by the movement kind+ # applying the change, not by the variant's backorder settings — an+ # oversell lives in allocated_count now, not in a negative shelf.+ shared_examples_for 'valid count_on_hand' do+ before { subject.save }++ it 'has no errors on count_on_hand' do+ expect(subject.errors[:count_on_hand]).to be_empty+ end+ end++ shared_examples_for 'not valid count_on_hand' do+ before { subject.save }++ it 'has an error on count_on_hand' do+ expect(subject.errors[:count_on_hand]).to include 'must be greater than or equal to 0'+ end+ end++ context 'when count_on_hand did not change' do+ it_behaves_like 'valid count_on_hand'+ end++ context 'when count_on_hand stays at or above zero' do+ before do+ subject.update_column(:count_on_hand, 3)+ subject.count_on_hand = 1+ end++ it_behaves_like 'valid count_on_hand'+ end++ context 'when count_on_hand rises while still negative' do+ before do+ subject.update_column(:count_on_hand, -3)+ subject.count_on_hand = -1+ end++ it_behaves_like 'valid count_on_hand'+ end++ context 'when count_on_hand is driven below zero' do+ before do+ subject.update_column(:count_on_hand, 3)+ subject.count_on_hand = -3+ end++ it_behaves_like 'not valid count_on_hand'++ context 'and the variant is backorderable' do+ before { subject.backorderable = true }++ it_behaves_like 'not valid count_on_hand'+ end++ context 'and the variant is a pre-order' do+ before { allow(subject.variant).to receive(:preorder?).and_return(true) }++ it_behaves_like 'not valid count_on_hand'+ end++ context 'and a dispatch is what is writing it' do+ it 'is let through' do+ subject.update_column(:count_on_hand, 3)++ subject.set_count_on_hand(-3, force: true)++ expect(subject.reload.count_on_hand).to eq(-3)+ end++ # The exemption belongs to the write that asked for it, not to the+ # record — the next save must be policed again.+ it 'does not outlive the call that asked for it' do+ subject.update_column(:count_on_hand, 3)+ subject.set_count_on_hand(-3, force: true)++ subject.count_on_hand = -4+ subject.save++ expect(subject.errors[:count_on_hand]).to include 'must be greater than or equal to 0'+ end+ end+ end+ 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) }++ describe '#adjust_allocated_count' do+ it 'moves the promise in both directions' do+ subject.adjust_allocated_count(4)+ expect(subject.reload.allocated_count).to eq(4)++ subject.adjust_allocated_count(-3)+ expect(subject.reload.allocated_count).to eq(1)+ end+ end++ describe '#release_allocated_count' do+ it 'withdraws only what was promised' do+ subject.adjust_allocated_count(2)++ subject.release_allocated_count(5)++ expect(subject.reload.allocated_count).to eq(0)+ end++ # The cap is read from the counter the write then moves, so it only holds+ # if both happen as one step. Needs a database with real parallel+ # connections and row locking, and needs to run outside the test+ # transaction — a transaction never blocks on its own FOR UPDATE, so+ # threads sharing one connection interleave freely and prove nothing.+ context 'released concurrently', if: ENV['DB'] == 'postgres' do+ self.use_transactional_tests = false++ let!(:concurrent_level) { create(:stock_level, adjust_count_on_hand: false) }++ after do+ location = concurrent_level.stock_location+ product = concurrent_level.variant.product+ Spree::StockMovement.where(stock_level_id: concurrent_level.id).delete_all+ location.really_destroy!+ product.really_destroy!+ end++ it 'never withdraws more promise than the level holds' do+ concurrent_level.adjust_allocated_count(5)++ 4.times.map do+ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ Spree::StockLevel.find(concurrent_level.id).release_allocated_count(5)+ end+ end+ end.each(&:join)++ expect(concurrent_level.reload.allocated_count).to eq(0)+ end+ end+ end++ describe '#available_count' do+ it 'is the shelf minus the promise' do+ subject.update_columns(count_on_hand: 10, allocated_count: 4)++ expect(subject.available_count).to eq(6)+ end+ end++ describe '#in_stock?' do+ it 'is false once every unit is promised' do+ subject.update_columns(count_on_hand: 2, allocated_count: 2)++ expect(subject).not_to be_in_stock+ end++ it 'is true while unpromised units remain' do+ subject.update_columns(count_on_hand: 2, allocated_count: 1)++ expect(subject).to be_in_stock+ end+ end+ end++ describe 'scopes' do+ context '.with_active_stock_location' do+ let(:stock_levels_with_active_location) { Spree::StockLevel.with_active_stock_location }++ context 'when stock location is active' do+ before { stock_location.update_column(:active, true) }++ it { expect(stock_levels_with_active_location).to include(subject) }+ end++ context 'when stock location is inactive' do+ before { stock_location.update_column(:active, false) }++ it { expect(stock_levels_with_active_location).not_to include(subject) }+ end+ end++ describe '.for_store' do+ let(:store) { @default_store }+ let(:other_store) { create(:store) }+ let(:product_in_store) { create(:product, store: store) }+ let(:product_in_other_store) { create(:product, store: other_store) }++ let!(:in_store_item) do+ create(:stock_level, variant: product_in_store.default_variant, stock_location: stock_location)+ end+ let!(:other_store_item) do+ create(:stock_level, variant: product_in_other_store.default_variant, stock_location: stock_location)+ end++ it 'returns stock items for variants of products owned by the store' do+ expect(described_class.for_store(store)).to include(in_store_item)+ end++ it 'excludes stock items for products owned by another store' do+ expect(described_class.for_store(store)).not_to include(other_store_item)+ end+ end+ end+enddiff --cc spree/core/spec/services/spree/products/duplicator_spec.rbindex 49f92efc87,202ffbcd54..3f292f990d--- a/spree/core/spec/services/spree/products/duplicator_spec.rb+++ b/spree/core/spec/services/spree/products/duplicator_spec.rb@@@ -39,26 -39,9 +39,26 @@@ RSpec.describe Spree::Products::DuplicaTimecop.returnend+ 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' doit 'clones images by default' do- expect { duplicate }.to change { Spree::Image.count }.by(1)+ expect { duplicate }.to change { Spree::Media.count }.by(1)endcontext 'when excluding images from cloning' do