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.

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.rb
index 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')}")
return
end
- @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
+ end
end
def transfer_to_shipment
@@ -113,10 +118,15 @@ module Spree
end
if 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
+ end
end
end
diff --git a/api/config/locales/en.yml b/api/config/locales/en.yml
index 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.rb
index 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 do
it 'displays wrong target and negative quantity errors' do
api_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')}")
end
end
@@ -92,7 +92,7 @@ describe Spree::Api::V1::ShipmentsController, type: :controller do
it 'displays negative quantity error' do
api_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')}")
end
end
@@ -103,7 +103,7 @@ describe Spree::Api::V1::ShipmentsController, type: :controller do
it 'displays wrong target error' do
api_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')}")
end
end
end
diff --git a/backend/app/assets/javascripts/spree/backend/shipments.js b/backend/app/assets/javascripts/spree/backend/shipments.js
index 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 eqeqeq
if (stockLocationId != 'new_shipment') {
+ var path, additionalData
if (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.rb
index 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 do
fill_in 'item_quantity', with: 2
click_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 do
fill_in 'item_quantity', with: 200
click_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.rb
index 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 do
it 'can ship a completed order' do
click_on 'Ship'
- expect(page).to have_content("shipped package")
+ expect(page).to have_content('shipped package')
expect(order.reload.shipment_state).to eq('shipped')
end
end
@@ -47,13 +47,16 @@ describe 'Shipments', type: :feature do
it 'can move a variant to a new and to an existing shipment' do
expect(order.shipments.count).to eq(1)
+ # Non existing shipment
within_row(1) { click_icon :split }
select2 'LA', css: '.stock-item-split', search: true, match: :first
- click_icon :'save-split'
+ click_icon :save
+ wait_for_ajax
expect(page).to have_css('#order-form-wrapper div', id: /^shipment_\d$/).exactly(2).times
expect(page).to have_css("#shipment_#{order.shipments.first.id}")
+ # Existing shipment
within_row(2) { click_icon :split }
select2 "LA(#{order.reload.shipments.last.number})", css: '.stock-item-split', search: true, match: :first
click_icon :save
diff --git a/core/app/models/spree/fulfilment_changer.rb b/core/app/models/spree/fulfilment_changer.rb
index da43b559e1..8cfc768194 100644
--- a/core/app/models/spree/fulfilment_changer.rb
+++ b/core/app/models/spree/fulfilment_changer.rb
@@ -36,7 +36,7 @@ module Spree
private
attr_reader :variant, :quantity, :current_stock_location, :desired_stock_location,
- :current_shipment, :desired_shipment, :available_quantity
+ :current_shipment, :desired_shipment, :available_quantity
def handle_stock
ActiveRecord::Base.transaction do
@@ -45,13 +45,64 @@ module Spree
desired_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 = 0
end
end
def after_process_shipments
- if current_shipment.inventory_units.length.zero?
+ if current_shipment.inventory_units.sum(:quantity).zero?
current_shipment.destroy!
else
current_shipment.refresh_rates
@@ -64,7 +115,7 @@ module Spree
end
def new_on_hand_quantity
- [available_quantity, quantity].min
+ [available_quantity, current_on_hand_quantity].min
end
def unstock_quantity
@@ -72,16 +123,7 @@ module Spree
end
def 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].min
end
def reload_shipment_inventory_units
@@ -105,7 +147,7 @@ module Spree
def enough_stock_at_desired_location
return 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)
end
def desired_shipment_different_from_current
diff --git a/core/app/models/spree/shipment.rb b/core/app/models/spree/shipment.rb
index fb69b2ab15..9976045137 100644
--- a/core/app/models/spree/shipment.rb
+++ b/core/app/models/spree/shipment.rb
@@ -362,7 +362,7 @@ module Spree
desired_shipment: shipment_to_transfer_to,
variant: variant,
quantity: quantity
- ).run!
+ )
end
private
diff --git a/core/config/locales/en.yml b/core/config/locales/en.yml
index 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 location
current_shipment:
has_already_been_shipped: has already been shipped
can_not_have_backordered_inventory_units: has backordered inventory units
diff --git a/core/lib/spree/testing_support/factories/shipment_factory.rb b/core/lib/spree/testing_support/factories/shipment_factory.rb
index 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 do
after(: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
+ )
end
end
end
diff --git a/core/spec/models/spree/fulfilment_changer_spec.rb b/core/spec/models/spree/fulfilment_changer_spec.rb
index 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 do
end
context '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)
end
it '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)
end
it 'recalculates shipping costs for the current shipment' do
@@ -123,8 +123,8 @@ describe Spree::FulfilmentChanger do
it 'creates a shipment with the correct number of on hand and backordered units' do
subject
- 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)
end
context 'when the desired stock location already has a backordered units' do
@@ -140,20 +140,58 @@ describe Spree::FulfilmentChanger do
it 'creates a shipment with the correct number of on hand and backordered units' do
subject
- 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)
end
end
context 'when the original shipment has on hand and backordered units' do
before 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)
+ end
end
end
@@ -177,8 +215,8 @@ describe Spree::FulfilmentChanger do
it 'creates a shipment with the correct number of on hand and backordered units' do
subject
- 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)
end
end
end
@@ -192,7 +230,7 @@ describe Spree::FulfilmentChanger do
it 'has an activemodel error hash' do
subject
- 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'])
end
end
end
@@ -260,12 +298,25 @@ describe Spree::FulfilmentChanger do
end
end
+ 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' do
let(: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)
end
it 'removes the current shipment' do
diff --git a/core/spec/models/spree/shipment_spec.rb b/core/spec/models/spree/shipment_spec.rb
index 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 do
it 'creates new shipment for same order' do
shipment = 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)
end
it 'sets the given stock location for new shipment' do
shipment = 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