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
Fixed: Create shipments in Admin Orders API (#13983)
Damian Legawiec61ee4307de74
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rbindex 26c8a7ec19..caa6984eb6 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb@@ -144,6 +144,52 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller doendend+ context 'with items and shipping address (one-shot draft order)' do+ let(:country) { @default_country }+ let(:state) { country.states.first || create(:state, country: country) }+ let!(:zone) { create(:zone) }+ let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }+ let!(:shipping_method) do+ create(:shipping_method, zones: [zone]).tap do |sm|+ sm.calculator.preferred_amount = 5+ sm.calculator.save+ end+ end+ let!(:stock_location) { Spree::StockLocation.first || create(:stock_location, country: country, state: state) }++ let(:product) { create(:product_in_stock, stores: [store]) }+ let(:variant) { product.default_variant }++ let(:create_params) do+ {+ email: '[email protected]',+ items: [{ variant_id: variant.prefixed_id, quantity: 2 }],+ shipping_address: {+ firstname: 'Jane', lastname: 'Doe',+ address1: '350 Fifth Avenue', city: 'New York',+ zipcode: '10118', phone: '555-555-0199',+ country_id: country.id, state_id: state.id+ }+ }+ end++ it 'creates fulfillments and returns delivery_total in the response' do+ subject++ expect(response).to have_http_status(:created)+ created = Spree::Order.find_by_prefix_id(json_response['id'])++ expect(created.shipments).not_to be_empty+ expect(created.shipments.first.shipping_rates).not_to be_empty+ expect(created.shipments.first.selected_shipping_rate).to be_present+ expect(created.shipment_total).to eq(5)+ expect(created.total).to eq(created.item_total + created.shipment_total + created.adjustment_total)++ expect(json_response['delivery_total']).to eq('5.0')+ expect(json_response['total']).to eq(created.total.to_s)+ end+ end+context 'with use_customer_default_address' dolet(:address) { create(:address) }let(:customer) { create(:user, bill_address: address, ship_address: address) }@@ -265,6 +311,74 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller doexpect(order.reload.tag_list).to contain_exactly('VIP')endend++ context 'adding items to a draft order with a shipping address' do+ let(:country) { @default_country }+ let(:state) { country.states.first || create(:state, country: country) }+ let!(:zone) { create(:zone) }+ let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }+ let!(:shipping_method) do+ create(:shipping_method, zones: [zone]).tap do |sm|+ sm.calculator.preferred_amount = 5+ sm.calculator.save+ end+ end+ let!(:stock_location) { Spree::StockLocation.first || create(:stock_location, country: country, state: state) }++ let(:product) { create(:product_in_stock, stores: [store]) }+ let(:variant) { product.default_variant }+ let(:ship_address) { create(:address, country: country, state: state) }+ let!(:order) { create(:order, store: store, state: 'cart', ship_address: ship_address) }++ it 'creates fulfillments and rolls delivery_total into the response' do+ patch :update, params: {+ id: order.prefixed_id,+ items: [{ variant_id: variant.prefixed_id, quantity: 2 }]+ }, as: :json++ expect(response).to have_http_status(:ok)++ order.reload+ expect(order.line_items.find_by(variant: variant).quantity).to eq(2)+ expect(order.shipments).not_to be_empty+ expect(order.shipments.first.shipping_rates).not_to be_empty+ expect(order.shipments.first.selected_shipping_rate).to be_present+ expect(order.shipment_total).to eq(5)++ expect(json_response['delivery_total']).to eq('5.0')+ expect(json_response['total']).to eq(order.total.to_s)+ end++ context 'when the order already has shipments' do+ before do+ # Seed initial shipments via the same Update path so they reflect+ # real Stock::Coordinator output.+ patch :update, params: {+ id: order.prefixed_id,+ items: [{ variant_id: variant.prefixed_id, quantity: 1 }]+ }, as: :json+ order.reload+ end++ it 'rebuilds shipments when items change (old shipment IDs are gone)' do+ old_shipment_ids = order.shipments.map(&:id)+ expect(old_shipment_ids).not_to be_empty++ patch :update, params: {+ id: order.prefixed_id,+ items: [{ variant_id: variant.prefixed_id, quantity: 4 }]+ }, as: :json++ expect(response).to have_http_status(:ok)++ order.reload+ new_shipment_ids = order.shipments.map(&:id)+ expect(new_shipment_ids).not_to be_empty+ expect(new_shipment_ids & old_shipment_ids).to be_empty+ expect(order.shipments.first.inventory_units.sum(:quantity)).to eq(4)+ end+ end+ endenddescribe 'DELETE #destroy' dodiff --git a/spree/core/app/services/spree/orders/build_shipments.rb b/spree/core/app/services/spree/orders/build_shipments.rbnew file mode 100644index 0000000000..fdbaeeddec--- /dev/null+++ b/spree/core/app/services/spree/orders/build_shipments.rb@@ -0,0 +1,29 @@+module Spree+ module Orders+ # Shared shipment-building step for admin order Create / Update.+ #+ # Rebuilds shipments from scratch (Stock::Coordinator), then layers in+ # tax, costs, and free-shipping promotions so totals reflect delivery+ # before payment is requested. Without this, draft orders would expose+ # delivery_total: 0.0 until completion is attempted — which is too late.+ #+ # No-op when the order has no shipping address, no line items, or does+ # not require delivery (digital orders, etc.).+ class BuildShipments+ prepend Spree::ServiceModule::Base++ def call(order:)+ return success(order) unless order.ship_address_id.present?+ return success(order) unless order.line_items.any?+ return success(order) unless order.delivery_required?++ order.create_proposed_shipments+ order.create_shipment_tax_charge!+ order.set_shipments_cost+ order.apply_free_shipping_promotions++ success(order)+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/orders/create.rb b/spree/core/app/services/spree/orders/create.rbindex 8996f02a1f..308b78c3fe 100644--- a/spree/core/app/services/spree/orders/create.rb+++ b/spree/core/app/services/spree/orders/create.rb@@ -33,7 +33,9 @@ module Spreeorder.save!add_items(order) if @params[:items].present?+ build_shipments(order)apply_coupon(order) if @params[:coupon_code].present?+ order.update_with_updater!endsuccess(order.reload)@@ -99,6 +101,11 @@ module Spreeraise ActiveRecord::RecordInvalid, order if result.failure?end+ def build_shipments(order)+ result = Spree::Orders::BuildShipments.call(order: order)+ raise ActiveRecord::RecordInvalid, order if result.failure?+ end+def apply_coupon(order)order.coupon_code = @params[:coupon_code]handler = Spree::PromotionHandler::Coupon.new(order).applydiff --git a/spree/core/app/services/spree/orders/update.rb b/spree/core/app/services/spree/orders/update.rbindex c91c4a01d0..770b406261 100644--- a/spree/core/app/services/spree/orders/update.rb+++ b/spree/core/app/services/spree/orders/update.rb@@ -15,11 +15,19 @@ module Spreeitems_param = @params.delete(:items)ApplicationRecord.transaction do+ ship_address_id_before = @order.ship_address_id+if @order.update(@params)process_items(items_param) if items_paramelsereturn failure(@order, @order.errors.full_messages.to_sentence)end++ if items_param || @order.ship_address_id != ship_address_id_before+ build_shipments+ end++ @order.update_with_updater!endsuccess(@order.reload)@@ -33,6 +41,11 @@ module Spreeresult = Spree::Orders::UpsertItems.call(order: @order, items: items)raise ActiveRecord::RecordInvalid, @order if result.failure?end++ def build_shipments+ result = Spree::Orders::BuildShipments.call(order: @order)+ raise ActiveRecord::RecordInvalid, @order if result.failure?+ endendendenddiff --git a/spree/core/app/services/spree/orders/upsert_items.rb b/spree/core/app/services/spree/orders/upsert_items.rbindex f5630d223b..678f0d37f3 100644--- a/spree/core/app/services/spree/orders/upsert_items.rb+++ b/spree/core/app/services/spree/orders/upsert_items.rb@@ -8,7 +8,10 @@ module Spree# - If a line item for the variant already exists -> sets its quantity# - If no line item exists -> creates one with the given quantity#- # After all items are processed the order is recalculated once.+ # Order totals are NOT recalculated here. Callers (Spree::Orders::Create+ # and Spree::Orders::Update) are responsible for running shipment+ # rebuilding and a final `order.update_with_updater!` once their+ # full pipeline (items, shipments, coupons) has run.class UpsertItemsprepend Spree::ServiceModule::Base@@ -41,8 +44,6 @@ module Spreereturn failure(line_item) unless line_item.saveend-- order.update_with_updater!endsuccess(order)diff --git a/spree/core/spec/services/spree/orders/create_spec.rb b/spree/core/spec/services/spree/orders/create_spec.rbnew file mode 100644index 0000000000..997586733a--- /dev/null+++ b/spree/core/spec/services/spree/orders/create_spec.rb@@ -0,0 +1,204 @@+require 'spec_helper'++module Spree+ RSpec.describe Orders::Create do+ let(:store) { @default_store }+ let(:user) { create(:user) }++ # Real shipping setup so Stock::Coordinator actually produces shipments.+ let(:country) { @default_country }+ let(:state) { country.states.first || create(:state, country: country) }+ let!(:zone) { create(:zone) }+ let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }+ let!(:shipping_method) do+ create(:shipping_method, zones: [zone]).tap do |sm|+ sm.calculator.preferred_amount = 5+ sm.calculator.save+ end+ end+ let!(:stock_location) { Spree::StockLocation.first || create(:stock_location, country: country, state: state) }++ let(:product) { create(:product_in_stock, stores: [store]) }+ let(:variant) { product.default_variant }++ let(:address_attrs) do+ {+ firstname: 'Jane', lastname: 'Doe',+ address1: '350 Fifth Avenue', city: 'New York',+ zipcode: '10118', phone: '555-555-0199',+ country_id: country.id, state_id: state.id+ }+ end++ describe '#call' do+ subject { described_class.call(store: store, user: user, params: params) }++ context 'without a store' do+ it 'fails' do+ result = described_class.call(store: nil)+ expect(result).to be_failure+ expect(result.value).to eq(:store_is_required)+ end+ end++ context 'with minimal params (no items, no address)' do+ let(:params) { { email: '[email protected]' } }++ it 'creates a draft order with no shipments' do+ expect(subject).to be_success+ order = subject.value+ expect(order).to be_persisted+ expect(order.status).to eq('draft')+ expect(order.shipments).to be_empty+ expect(order.shipment_total).to eq(0)+ end+ end++ context 'with items but no shipping address' do+ let(:params) do+ {+ email: '[email protected]',+ items: [{ variant_id: variant.prefixed_id, quantity: 2 }]+ }+ end++ it 'does not build shipments — total reflects only items' do+ expect(subject).to be_success+ order = subject.value+ expect(order.line_items.count).to eq(1)+ expect(order.shipments).to be_empty+ expect(order.shipment_total).to eq(0)+ expect(order.total).to eq(order.item_total)+ end+ end++ context 'with shipping address but no items' do+ let(:params) do+ {+ email: '[email protected]',+ shipping_address: address_attrs+ }+ end++ it 'does not build shipments' do+ expect(subject).to be_success+ order = subject.value+ expect(order.ship_address).to be_present+ expect(order.shipments).to be_empty+ expect(order.shipment_total).to eq(0)+ end+ end++ context 'happy path: items + shipping address' do+ let(:params) do+ {+ email: '[email protected]',+ items: [{ variant_id: variant.prefixed_id, quantity: 2 }],+ shipping_address: address_attrs+ }+ end++ it 'creates shipments and rolls delivery cost into the order total' do+ expect(subject).to be_success+ order = subject.value++ expect(order.line_items.count).to eq(1)+ expect(order.shipments).not_to be_empty+ expect(order.shipments.first.shipping_rates).not_to be_empty+ expect(order.shipments.first.selected_shipping_rate).to be_present++ expect(order.shipment_total).to eq(5)+ expect(order.total).to eq(order.item_total + order.shipment_total + order.adjustment_total)+ end++ it 'persists the totals to the database' do+ subject+ order = subject.value.reload+ expect(order.shipment_total).to eq(5)+ expect(order.total).to eq(order.item_total + 5 + order.adjustment_total)+ end+ end++ context 'when delivery is not required' do+ let(:params) do+ {+ email: '[email protected]',+ items: [{ variant_id: variant.prefixed_id, quantity: 1 }],+ shipping_address: address_attrs+ }+ end++ before do+ allow_any_instance_of(Spree::Order).to receive(:delivery_required?).and_return(false)+ end++ it 'does not build shipments' do+ expect(subject).to be_success+ expect(subject.value.shipments).to be_empty+ expect(subject.value.shipment_total).to eq(0)+ end+ end++ context 'with a free-shipping coupon code' do+ let!(:promotion) do+ create(:free_shipping_promotion, code: 'SHIP10', stores: [store])+ end++ let(:params) do+ {+ email: '[email protected]',+ items: [{ variant_id: variant.prefixed_id, quantity: 1 }],+ shipping_address: address_attrs,+ coupon_code: 'SHIP10'+ }+ end++ it 'builds shipments first, then the free-shipping promo cancels the delivery cost' do+ expect(subject).to be_success+ order = subject.value++ # Shipments still exist, gross cost is still 5 (cost column on the shipment)+ expect(order.shipments.size).to eq(1)+ expect(order.shipment_total).to eq(5)++ # Promo created a -5 adjustment on the shipment+ shipment = order.shipments.first+ expect(shipment.adjustment_total).to eq(-5)+ expect(shipment.adjustments.promotion.size).to eq(1)+ expect(order.shipping_discount).to eq(5)++ # Promotion is associated with the order+ expect(order.promotions).to include(promotion)++ # Customer-visible total is item_total only — free shipping nets out+ expect(order.total).to eq(order.item_total)+ end+ end++ context 'with an automatic free-shipping promotion (no coupon code)' do+ let!(:promotion) do+ create(:free_shipping_promotion, kind: :automatic, stores: [store])+ end++ let(:params) do+ {+ email: '[email protected]',+ items: [{ variant_id: variant.prefixed_id, quantity: 1 }],+ shipping_address: address_attrs+ }+ end++ it 'applies the promotion during shipment building, even without a coupon code' do+ expect(subject).to be_success+ order = subject.value++ shipment = order.shipments.first+ expect(shipment).to be_present+ expect(shipment.adjustment_total).to eq(-5)+ expect(order.shipping_discount).to eq(5)+ expect(order.total).to eq(order.item_total)+ end+ end+ end+ end+enddiff --git a/spree/core/spec/services/spree/orders/update_spec.rb b/spree/core/spec/services/spree/orders/update_spec.rbindex cf1b45c337..a778920c3b 100644--- a/spree/core/spec/services/spree/orders/update_spec.rb+++ b/spree/core/spec/services/spree/orders/update_spec.rb@@ -2,15 +2,30 @@ require 'spec_helper'module SpreeRSpec.describe Orders::Update do- let(:store) { create(:store) }+ let(:store) { @default_store }let(:user) { create(:user) }- let(:order) { create(:order, user: user, store: store) }- let(:variant) { create(:variant) }+ let(:product) { create(:product_in_stock, stores: [store]) }+ let(:variant) { product.default_variant }- before do- variant.stock_items.first.update!(count_on_hand: 10)- store.products << variant.product unless store.products.include?(variant.product)+ # Real shipping setup so Stock::Coordinator can produce shipments+ # for the rebuild flows.+ let(:country) { @default_country }+ let(:state) { country.states.first || create(:state, country: country) }+ let(:other_country) { create(:country) }+ let(:other_state) { create(:state, country: other_country) }+ let!(:zone) { create(:zone) }+ let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }+ let!(:other_zone) { create(:zone) }+ let!(:other_zone_member) { create(:zone_member, zone: other_zone, zoneable: other_country) }+ let!(:shipping_method) do+ create(:shipping_method, zones: [zone, other_zone]).tap do |sm|+ sm.calculator.preferred_amount = 5+ sm.calculator.save+ endend+ let!(:stock_location) { Spree::StockLocation.first || create(:stock_location, country: country, state: state) }++ let(:order) { create(:order, user: user, store: store) }describe '#call' dosubject { described_class.call(order: order, params: params) }@@ -125,6 +140,130 @@ module Spreeexpect(order.line_items.find_by(variant: variant)).to be_presentendend++ describe 'shipment rebuild' do+ # Order seeded with a shipping address + line item + an initial shipment.+ let(:initial_address) { create(:address, country: country, state: state) }+ let(:order) do+ o = create(:order, user: user, store: store, ship_address: initial_address)+ described_class.call(order: o, params: { items: [{ variant_id: variant.prefixed_id, quantity: 1 }] })+ o.reload+ end++ it 'starts with shipments built from the seeded data' do+ expect(order.shipments).not_to be_empty+ expect(order.shipment_total).to eq(5)+ end++ context 'when items change' do+ let(:params) { { items: [{ variant_id: variant.prefixed_id, quantity: 3 }] } }++ it 'rebuilds shipments to reflect the new line item state' do+ old_shipment_ids = order.shipments.map(&:id)++ expect(subject).to be_success++ order.reload+ new_shipment_ids = order.shipments.map(&:id)++ expect(order.line_items.find_by(variant: variant).quantity).to eq(3)+ expect(new_shipment_ids).not_to be_empty+ expect(new_shipment_ids & old_shipment_ids).to be_empty+ expect(order.shipments.first.inventory_units.sum(:quantity)).to eq(3)+ expect(order.shipment_total).to eq(5)+ end+ end++ context 'when shipping address changes' do+ let(:new_address_attrs) do+ {+ firstname: 'Bob', lastname: 'Stone',+ address1: '99 New Street', city: 'Other City',+ zipcode: '99999', phone: '555-000-9999',+ country_id: other_country.id, state_id: other_state.id+ }+ end+ let(:params) { { ship_address_attributes: new_address_attrs } }++ it 'rebuilds shipments against the new address' do+ old_shipment_ids = order.shipments.map(&:id)++ expect(subject).to be_success++ order.reload+ expect(order.ship_address.country_id).to eq(other_country.id)+ expect(order.ship_address.address1).to eq('99 New Street')++ new_shipment_ids = order.shipments.map(&:id)+ expect(new_shipment_ids).not_to be_empty+ expect(new_shipment_ids & old_shipment_ids).to be_empty+ end+ end++ context 'when neither items nor shipping address change' do+ let(:params) { { customer_note: 'whatever' } }++ it 'does not rebuild shipments — same shipment IDs stay in place' do+ old_shipment_ids = order.shipments.map(&:id)++ expect(subject).to be_success++ order.reload+ expect(order.shipments.map(&:id)).to match_array(old_shipment_ids)+ expect(order.customer_note).to eq('whatever')+ end+ end+ end++ describe 'final totals refresh' do+ it 'persists totals after the pipeline runs' do+ described_class.call(order: order, params: { items: [{ variant_id: variant.prefixed_id, quantity: 2 }] })++ order.reload+ expect(order.line_items.first.quantity).to eq(2)+ expect(order.item_total).to eq(variant.price * 2)+ expect(order.total).to eq(order.item_total + order.shipment_total + order.adjustment_total)+ end+ end++ describe 'with an automatic free-shipping promotion' do+ let!(:promotion) { create(:free_shipping_promotion, kind: :automatic, stores: [store]) }+ let(:initial_address) { create(:address, country: country, state: state) }+ let(:order) { create(:order, user: user, store: store, ship_address: initial_address) }++ it 'applies the promo when items are added so delivery cost nets to zero' do+ described_class.call(order: order, params: { items: [{ variant_id: variant.prefixed_id, quantity: 1 }] })++ order.reload+ shipment = order.shipments.first+ expect(shipment).to be_present+ expect(shipment.adjustment_total).to eq(-5)+ expect(order.shipping_discount).to eq(5)+ expect(order.total).to eq(order.item_total)+ end++ it 're-applies the promo when shipping address changes' do+ # Seed: order with line item + shipments + promo applied+ described_class.call(order: order, params: { items: [{ variant_id: variant.prefixed_id, quantity: 1 }] })+ order.reload+ expect(order.shipping_discount).to eq(5)++ # Move to a different country — shipments rebuild, promo must re-apply+ described_class.call(order: order, params: {+ ship_address_attributes: {+ firstname: 'Bob', lastname: 'Stone',+ address1: '99 New Street', city: 'Other City',+ zipcode: '99999', phone: '555-000-9999',+ country_id: other_country.id, state_id: other_state.id+ }+ })++ order.reload+ expect(order.shipments.first.adjustment_total).to eq(-5)+ expect(order.shipping_discount).to eq(5)+ expect(order.total).to eq(order.item_total)+ end+ endendendenddiff --git a/spree/core/spec/services/spree/orders/upsert_items_spec.rb b/spree/core/spec/services/spree/orders/upsert_items_spec.rbindex 8abb82b129..17223ae49b 100644--- a/spree/core/spec/services/spree/orders/upsert_items_spec.rb+++ b/spree/core/spec/services/spree/orders/upsert_items_spec.rb@@ -216,22 +216,6 @@ module Spreeendend- context 'recalculates order totals' do- let(:items) do- [- { variant_id: variant.prefixed_id, quantity: 2 },- { variant_id: variant2.prefixed_id, quantity: 1 }- ]- end-- it 'updates order item_total' do- expect(subject).to be_success- order.reload- expected_total = (variant.price * 2) + variant2.price- expect(order.item_total).to eq(expected_total)- end- end-context 'rolls back on failure mid-batch' dolet(:items) do[