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
Split order products into shipments by stock location (#10541)
Szymon Iwacz642d79f52b1c
diff --git a/api/app/controllers/spree/api/v1/shipments_controller.rb b/api/app/controllers/spree/api/v1/shipments_controller.rbindex e0f202dce6..aafbc4035f 100644--- a/api/app/controllers/spree/api/v1/shipments_controller.rb+++ b/api/app/controllers/spree/api/v1/shipments_controller.rb@@ -92,12 +92,17 @@ module Spree@stock_location = Spree::StockLocation.find(params[:stock_location_id])unless @quantity > 0- unprocessable_entity("#{Spree.t(:shipment_transfer_errors_occured, scope: 'api')} \n #{Spree.t(:negative_quantity, scope: 'api')}")+ unprocessable_entity("#{Spree.t(:shipment_transfer_errors_occurred, scope: 'api')} \n #{Spree.t(:negative_quantity, scope: 'api')}")returnend- @original_shipment.transfer_to_location(@variant, @quantity, @stock_location)- render json: { success: true, message: Spree.t(:shipment_transfer_success) }, status: 201+ transfer = @original_shipment.transfer_to_location(@variant, @quantity, @stock_location)+ if transfer.valid?+ transfer.run!+ render json: { message: Spree.t(:shipment_transfer_success) }, status: 201+ else+ render json: { message: transfer.errors.full_messages.to_sentence }, status: 422+ endenddef transfer_to_shipment@@ -113,10 +118,15 @@ module Spreeendif error- unprocessable_entity("#{Spree.t(:shipment_transfer_errors_occured, scope: 'api')} \n#{error}")+ unprocessable_entity("#{Spree.t(:shipment_transfer_errors_occurred, scope: 'api')} \n#{error}")else- @original_shipment.transfer_to_shipment(@variant, @quantity, @target_shipment)- render json: { success: true, message: Spree.t(:shipment_transfer_success) }, status: 201+ transfer = @original_shipment.transfer_to_shipment(@variant, @quantity, @target_shipment)+ if transfer.valid?+ transfer.run!+ render json: { message: Spree.t(:shipment_transfer_success) }, status: 201+ else+ render json: { message: transfer.errors.full_messages }, status: 422+ endendenddiff --git a/api/config/locales/en.yml b/api/config/locales/en.ymlindex 1f91afccf1..8eb565361d 100644--- a/api/config/locales/en.yml+++ b/api/config/locales/en.yml@@ -26,7 +26,7 @@ en:cannot_ready: "Cannot ready shipment."stock_location_required: "A stock_location_id parameter must be provided in order to retrieve stock movements."invalid_taxonomy_id: "Invalid taxonomy id."- shipment_transfer_errors_occured: "Following errors occured while attempting this action:"+ shipment_transfer_errors_occurred: "Following errors occured while attempting this action:"negative_quantity: "quantity is negative"wrong_shipment_target: "target shipment is the same as original shipment"diff --git a/api/spec/controllers/spree/api/v1/shipments_controller_spec.rb b/api/spec/controllers/spree/api/v1/shipments_controller_spec.rbindex 6e0cf2d49f..5d291c4636 100644--- a/api/spec/controllers/spree/api/v1/shipments_controller_spec.rb+++ b/api/spec/controllers/spree/api/v1/shipments_controller_spec.rb@@ -81,7 +81,7 @@ describe Spree::Api::V1::ShipmentsController, type: :controller doit 'displays wrong target and negative quantity errors' doapi_post :transfer_to_shipment, params- expect(json_response['exception']).to eq("#{Spree.t(:shipment_transfer_errors_occured, scope: 'api')} \n#{Spree.t(:negative_quantity, scope: 'api')}, \n#{Spree.t(:wrong_shipment_target, scope: 'api')}")+ expect(json_response['exception']).to eq("#{Spree.t(:shipment_transfer_errors_occurred, scope: 'api')} \n#{Spree.t(:negative_quantity, scope: 'api')}, \n#{Spree.t(:wrong_shipment_target, scope: 'api')}")endend@@ -92,7 +92,7 @@ describe Spree::Api::V1::ShipmentsController, type: :controller doit 'displays negative quantity error' doapi_post :transfer_to_shipment, params- expect(json_response['exception']).to eq("#{Spree.t(:shipment_transfer_errors_occured, scope: 'api')} \n#{Spree.t(:negative_quantity, scope: 'api')}")+ expect(json_response['exception']).to eq("#{Spree.t(:shipment_transfer_errors_occurred, scope: 'api')} \n#{Spree.t(:negative_quantity, scope: 'api')}")endend@@ -103,7 +103,7 @@ describe Spree::Api::V1::ShipmentsController, type: :controller doit 'displays wrong target error' doapi_post :transfer_to_shipment, params- expect(json_response['exception']).to eq("#{Spree.t(:shipment_transfer_errors_occured, scope: 'api')} \n#{Spree.t(:wrong_shipment_target, scope: 'api')}")+ expect(json_response['exception']).to eq("#{Spree.t(:shipment_transfer_errors_occurred, scope: 'api')} \n#{Spree.t(:wrong_shipment_target, scope: 'api')}")endendenddiff --git a/backend/app/assets/javascripts/spree/backend/shipments.js b/backend/app/assets/javascripts/spree/backend/shipments.jsindex 5fe8491cbb..eb00b6af81 100644--- a/backend/app/assets/javascripts/spree/backend/shipments.js+++ b/backend/app/assets/javascripts/spree/backend/shipments.js@@ -289,43 +289,34 @@ function completeItemSplit(event) {var newShipment = selectedShipment.data('new-shipment')// eslint-disable-next-line eqeqeqif (stockLocationId != 'new_shipment') {+ var path, additionalDataif (newShipment !== undefined) {- // TRANSFER TO A NEW LOCATION- $.ajax({- type: 'POST',- async: false,- url: Spree.url(Spree.routes.shipments_api + '/transfer_to_location'),- data: {- original_shipment_number: originalShipmentNumber,- variant_id: variantId,- quantity: quantity,- stock_location_id: stockLocationId,- token: Spree.api_key- }- }).fail(function (msg) {- alert(msg.responseJSON.message || msg.responseJSON.exception)- }).done(function (msg) {- window.location.reload()- })+ // transfer to a new location data+ path = '/transfer_to_location'+ additionalData = { stock_location_id: stockLocationId }} else {- // TRANSFER TO AN EXISTING SHIPMENT- $.ajax({- type: 'POST',- async: false,- url: Spree.url(Spree.routes.shipments_api + '/transfer_to_shipment'),- data: {- original_shipment_number: originalShipmentNumber,- target_shipment_number: targetShipmentNumber,- variant_id: variantId,- quantity: quantity,- token: Spree.api_key- }- }).fail(function (msg) {- alert(msg.responseJSON.message || msg.responseJSON.exception)- }).done(function (msg) {- window.location.reload()- })+ // transfer to an existing shipment data+ path = '/transfer_to_shipment'+ additionalData = { target_shipment_number: targetShipmentNumber }}++ var data = {+ original_shipment_number: originalShipmentNumber,+ variant_id: variantId,+ quantity: quantity,+ token: Spree.api_key+ }++ $.ajax({+ type: 'POST',+ async: false,+ url: Spree.url(Spree.routes.shipments_api + path),+ data: $.extend(data, additionalData)+ }).fail(function (msg) {+ alert(msg.responseJSON.message || msg.responseJSON.exception)+ }).done(function (msg) {+ window.location.reload()+ })}}diff --git a/backend/spec/features/admin/orders/order_details_spec.rb b/backend/spec/features/admin/orders/order_details_spec.rbindex 6aa4e76981..ff2fa4cb26 100644--- a/backend/spec/features/admin/orders/order_details_spec.rb+++ b/backend/spec/features/admin/orders/order_details_spec.rb@@ -362,7 +362,9 @@ describe 'Order Details', type: :feature, js: true dofill_in 'item_quantity', with: 2click_icon :save- expect(page).not_to have_css('tr.stock-item-split')+ alert_text = page.driver.browser.switch_to.alert.text+ expect(alert_text).to eq('Desired shipment has not enough stock in desired stock location')+ accept_alert { order.reload }expect(order.shipments.count).to eq(1)expect(order.shipments.first.inventory_units_for(product.master).sum(&:quantity)).to eq(2)@@ -514,8 +516,9 @@ describe 'Order Details', type: :feature, js: true dofill_in 'item_quantity', with: 200click_icon :save- expect(page).not_to have_css('tr.stock-item-split')- order.reload+ alert_text = page.driver.browser.switch_to.alert.text+ expect(alert_text).to eq('Desired shipment has not enough stock in desired stock location')+ accept_alert { order.reload }expect(order.shipments.count).to eq(2)expect(order.shipments.first.inventory_units_for(product.master).sum(&:quantity)).to eq(1)diff --git a/backend/spec/features/admin/orders/shipments_spec.rb b/backend/spec/features/admin/orders/shipments_spec.rbindex dbc5ef4258..707f4ee3fd 100644--- a/backend/spec/features/admin/orders/shipments_spec.rb+++ b/backend/spec/features/admin/orders/shipments_spec.rb@@ -30,7 +30,7 @@ describe 'Shipments', type: :feature doit 'can ship a completed order' doclick_on 'Ship'- expect(page).to have_content("shipped package")+ expect(page).to have_content('shipped package')expect(order.reload.shipment_state).to eq('shipped')endend@@ -47,13 +47,16 @@ describe 'Shipments', type: :feature doit 'can move a variant to a new and to an existing shipment' doexpect(order.shipments.count).to eq(1)+ # Non existing shipmentwithin_row(1) { click_icon :split }select2 'LA', css: '.stock-item-split', search: true, match: :first- click_icon :'save-split'+ click_icon :save+ wait_for_ajaxexpect(page).to have_css('#order-form-wrapper div', id: /^shipment_\d$/).exactly(2).timesexpect(page).to have_css("#shipment_#{order.shipments.first.id}")+ # Existing shipmentwithin_row(2) { click_icon :split }select2 "LA(#{order.reload.shipments.last.number})", css: '.stock-item-split', search: true, match: :firstclick_icon :savediff --git a/core/app/models/spree/fulfilment_changer.rb b/core/app/models/spree/fulfilment_changer.rbindex da43b559e1..8cfc768194 100644--- a/core/app/models/spree/fulfilment_changer.rb+++ b/core/app/models/spree/fulfilment_changer.rb@@ -36,7 +36,7 @@ module Spreeprivateattr_reader :variant, :quantity, :current_stock_location, :desired_stock_location,- :current_shipment, :desired_shipment, :available_quantity+ :current_shipment, :desired_shipment, :available_quantitydef handle_stockActiveRecord::Base.transaction do@@ -45,13 +45,64 @@ module Spreedesired_stock_location.unstock(variant, unstock_quantity, desired_shipment)end- update_current_shipment_inventory_units(new_on_hand_quantity, :on_hand)- update_current_shipment_inventory_units(quantity - new_on_hand_quantity, :backordered)+ move_inventory_units_between_shipments+ end+ end++ def move_inventory_units_between_shipments+ update_desired_shipment_inventory_units+ update_current_shipment_inventory_units+ end++ def current_shipment_units+ @current_shipment_units ||= current_shipment.inventory_units.on_hand_or_backordered.where(variant_id: variant.id)+ end++ def update_desired_shipment_inventory_units+ on_hand_unit = get_desired_shipment_inventory_unit(:on_hand)+ on_hand_unit.update(quantity: on_hand_unit.quantity + new_on_hand_quantity)++ new_backorder_quantity = current_on_hand_quantity - new_on_hand_quantity+ if new_backorder_quantity > 0+ backordered_unit = get_desired_shipment_inventory_unit(:backordered)+ backordered_unit.update(quantity: backordered_unit.quantity + new_backorder_quantity)+ end+ end++ def update_current_shipment_inventory_units+ reduced_quantity = current_on_hand_quantity++ # Reduce quantities from all backordered units first in case there is more than one.+ backorder_units = current_shipment_units.backordered+ reduced_quantity = reduce_units_quantities(reduced_quantity, backorder_units) if backorder_units.any?++ # Reduce quantities from all on_hand units in case there is more than one.+ if reduced_quantity > 0+ on_hand_units = current_shipment_units.on_hand+ reduce_units_quantities(reduced_quantity, on_hand_units) if on_hand_units.any?+ end+ end++ def reduce_units_quantities(reduced_quantity, units)+ units.each do |unit|+ unit.quantity > reduced_quantity ? unit.update(quantity: unit.quantity - reduced_quantity) : unit.destroy!+ reduced_quantity -= unit.quantity+ end+ reduced_quantity+ end++ def get_desired_shipment_inventory_unit(state)+ desired_shipment.inventory_units.find_or_create_by(state: state) do |unit|+ current_shipment_unit = current_shipment_units.first+ unit.variant_id = current_shipment_unit.variant_id+ unit.order_id = current_shipment_unit.order_id+ unit.line_item_id = current_shipment_unit.line_item_id+ unit.quantity = 0endenddef after_process_shipments- if current_shipment.inventory_units.length.zero?+ if current_shipment.inventory_units.sum(:quantity).zero?current_shipment.destroy!elsecurrent_shipment.refresh_rates@@ -64,7 +115,7 @@ module Spreeenddef new_on_hand_quantity- [available_quantity, quantity].min+ [available_quantity, current_on_hand_quantity].minenddef unstock_quantity@@ -72,16 +123,7 @@ module Spreeenddef current_on_hand_quantity- [current_shipment.inventory_units.on_hand_or_backordered.size, quantity].min- end-- def update_current_shipment_inventory_units(quantity, state)- current_shipment.- inventory_units.- where(variant: variant).- order(state: :asc).- limit(quantity).- update_all(shipment_id: desired_shipment.id, state: state)+ [current_shipment.inventory_units.on_hand_or_backordered.sum(:quantity), quantity].minenddef reload_shipment_inventory_units@@ -105,7 +147,7 @@ module Spreedef enough_stock_at_desired_locationreturn if Spree::Stock::Quantifier.new(variant, desired_stock_location).can_supply?(quantity)- errors.add(:desired_shipment, :not_enough_stock_at_desired_location)+ errors.add(:desired_shipment, :has_not_enough_stock_at_desired_location)enddef desired_shipment_different_from_currentdiff --git a/core/app/models/spree/shipment.rb b/core/app/models/spree/shipment.rbindex fb69b2ab15..9976045137 100644--- a/core/app/models/spree/shipment.rb+++ b/core/app/models/spree/shipment.rb@@ -362,7 +362,7 @@ module Spreedesired_shipment: shipment_to_transfer_to,variant: variant,quantity: quantity- ).run!+ )endprivatediff --git a/core/config/locales/en.yml b/core/config/locales/en.ymlindex eec83f463a..48788da6cf 100644--- a/core/config/locales/en.yml+++ b/core/config/locales/en.yml@@ -6,7 +6,7 @@ en:attributes:desired_shipment:can_not_transfer_within_same_shipment: can not be same as current shipment- not_enough_stock_at_desired_location: not enough stock in desired stock location+ has_not_enough_stock_at_desired_location: has not enough stock in desired stock locationcurrent_shipment:has_already_been_shipped: has already been shippedcan_not_have_backordered_inventory_units: has backordered inventory unitsdiff --git a/core/lib/spree/testing_support/factories/shipment_factory.rb b/core/lib/spree/testing_support/factories/shipment_factory.rbindex 8279d58a20..8d20df9715 100644--- a/core/lib/spree/testing_support/factories/shipment_factory.rb+++ b/core/lib/spree/testing_support/factories/shipment_factory.rb@@ -8,15 +8,13 @@ FactoryBot.define doafter(:create) do |shipment, _evalulator|shipment.add_shipping_method(create(:shipping_method), true)-- shipment.order.line_items.each do |line_item|- line_item.quantity.times do- shipment.inventory_units.create(- order_id: shipment.order_id,- variant_id: line_item.variant_id,- line_item_id: line_item.id- )- end+ shipment.order.line_items.map do |line_item|+ shipment.inventory_units.create(+ order_id: shipment.order_id,+ variant_id: line_item.variant_id,+ line_item_id: line_item.id,+ quantity: line_item.quantity+ )endendenddiff --git a/core/spec/models/spree/fulfilment_changer_spec.rb b/core/spec/models/spree/fulfilment_changer_spec.rbindex 70e72d8c32..796a983000 100644--- a/core/spec/models/spree/fulfilment_changer_spec.rb+++ b/core/spec/models/spree/fulfilment_changer_spec.rb@@ -39,15 +39,15 @@ describe Spree::FulfilmentChanger doendcontext 'when the current shipment has enough inventory units' do- let(:current_shipment_inventory_unit_count) { 2 }+ let(:current_shipment_inventory_unit_count) { 3 }let(:quantity) { 1 }it 'adds the desired inventory units to the desired shipment' do- expect { subject }.to change { desired_shipment.inventory_units.length }.by(quantity)+ expect { subject }.to change { desired_shipment.inventory_units.sum(:quantity) }.by(quantity)endit 'removes the desired inventory units from the current shipment' do- expect { subject }.to change { current_shipment.inventory_units.length }.by(-quantity)+ expect { subject }.to change { current_shipment.inventory_units.sum(:quantity) }.by(-quantity)endit 'recalculates shipping costs for the current shipment' do@@ -123,8 +123,8 @@ describe Spree::FulfilmentChanger doit 'creates a shipment with the correct number of on hand and backordered units' dosubject- expect(desired_shipment.inventory_units.on_hand.count).to eq(5)- expect(desired_shipment.inventory_units.backordered.count).to eq(2)+ expect(desired_shipment.inventory_units.on_hand.sum(:quantity)).to eq(5)+ expect(desired_shipment.inventory_units.backordered.sum(:quantity)).to eq(2)endcontext 'when the desired stock location already has a backordered units' do@@ -140,20 +140,58 @@ describe Spree::FulfilmentChanger doit 'creates a shipment with the correct number of on hand and backordered units' dosubject- expect(desired_shipment.inventory_units.on_hand.count).to eq(0)- expect(desired_shipment.inventory_units.backordered.count).to eq(7)+ expect(desired_shipment.inventory_units.on_hand.sum(:quantity)).to eq(0)+ expect(desired_shipment.inventory_units.backordered.sum(:quantity)).to eq(7)endendcontext 'when the original shipment has on hand and backordered units' dobefore do- current_shipment.inventory_units.limit(6).update_all(state: :backordered)+ expect_any_instance_of(described_class).to receive(:handle_stock_counts?).at_least(:once).and_return(false)+ backordered_unit = current_shipment.inventory_units.on_hand.first.dup+ backordered_unit.update(state: :backordered, quantity: 5)end- it 'removes the backordered items first' do+ it 'removes the backordered item first' do+ expect(current_shipment.inventory_units.backordered.sum(:quantity)).to eq(5)subject- expect(current_shipment.inventory_units.backordered.count).to eq(0)- expect(current_shipment.inventory_units.on_hand.count).to eq(3)+ expect(current_shipment.inventory_units.backordered).not_to be_present+ expect(current_shipment.inventory_units.on_hand.sum(:quantity)).to eq(8)+ end++ context 'more than one backordered unit' do+ before do+ current_shipment.inventory_units.on_hand.first.update!(quantity: 1)+ new_unit = current_shipment.inventory_units.on_hand.first.dup+ new_unit.update!(quantity: 5)+ end++ it 'reduces the backordered items first' do+ expect(current_shipment.inventory_units.on_hand.count).to eq(2)+ expect(current_shipment.inventory_units.on_hand.sum(:quantity)).to eq(6)+ expect(current_shipment.inventory_units.backordered.count).to eq(1)+ expect(current_shipment.inventory_units.backordered.sum(:quantity)).to eq(5)+ subject+ expect(current_shipment.inventory_units.backordered).not_to be_present+ expect(current_shipment.inventory_units.on_hand.count).to eq(1)+ expect(current_shipment.inventory_units.on_hand.sum(:quantity)).to eq(4)+ end+ end++ context 'more than one on_hand unit' do+ before do+ backordered_unit = current_shipment.inventory_units.backordered.first.dup+ backordered_unit.update!(quantity: 4)+ end++ it 'reduces the backordered items first' do+ expect(current_shipment.inventory_units.backordered.count).to eq(2)+ expect(current_shipment.inventory_units.backordered.sum(:quantity)).to eq(9)+ subject+ expect(current_shipment.inventory_units.backordered.count).to eq(1)+ expect(current_shipment.inventory_units.backordered.sum(:quantity)).to eq(2)+ expect(current_shipment.inventory_units.on_hand.sum(:quantity)).to eq(10)+ endendend@@ -177,8 +215,8 @@ describe Spree::FulfilmentChanger doit 'creates a shipment with the correct number of on hand and backordered units' dosubject- expect(desired_shipment.inventory_units.on_hand.count).to eq(5)- expect(desired_shipment.inventory_units.backordered.count).to eq(2)+ expect(desired_shipment.inventory_units.on_hand.sum(:quantity)).to eq(5)+ expect(desired_shipment.inventory_units.backordered.sum(:quantity)).to eq(2)endendend@@ -192,7 +230,7 @@ describe Spree::FulfilmentChanger doit 'has an activemodel error hash' dosubject- expect(shipment_splitter.errors.messages).to eq(desired_shipment: ['not enough stock in desired stock location'])+ expect(shipment_splitter.errors.messages).to eq(desired_shipment: ['has not enough stock in desired stock location'])endendend@@ -260,12 +298,25 @@ describe Spree::FulfilmentChanger doendend+ context 'when the current shipment has not enough inventory units' do+ let(:current_shipment_inventory_unit_count) { 3 }+ let(:quantity) { 5 }++ it 'adds the desired inventory units to the desired shipment' do+ expect { subject }.to change { desired_shipment.inventory_units.sum(:quantity) }.by(current_shipment_inventory_unit_count)+ end++ it 'removes the desired inventory units from the current shipment' do+ expect { subject }.to change { current_shipment.inventory_units.sum(:quantity) }.by(-current_shipment_inventory_unit_count)+ end+ end+context 'when the current shipment is emptied out by the transfer' dolet(:current_shipment_inventory_unit_count) { 30 }let(:quantity) { 30 }it 'adds the desired inventory units to the desired shipment' do- expect { subject }.to change { desired_shipment.inventory_units.length }.by(quantity)+ expect { subject }.to change { desired_shipment.inventory_units.sum(:quantity) }.by(quantity)endit 'removes the current shipment' dodiff --git a/core/spec/models/spree/shipment_spec.rb b/core/spec/models/spree/shipment_spec.rbindex bb84cfadc1..b04c6c02fe 100644--- a/core/spec/models/spree/shipment_spec.rb+++ b/core/spec/models/spree/shipment_spec.rb@@ -767,13 +767,13 @@ describe Spree::Shipment, type: :model doit 'creates new shipment for same order' doshipment = order.shipments.first- expect { shipment.transfer_to_location(variant, 1, stock_location) }.+ expect { shipment.transfer_to_location(variant, 1, stock_location).run! }.to change { order.reload.shipments.size }.from(1).to(2)endit 'sets the given stock location for new shipment' doshipment = order.shipments.first- shipment.transfer_to_location(variant, 1, stock_location)+ shipment.transfer_to_location(variant, 1, stock_location).run!new_shipment = order.reload.shipments.last