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
Add shipment cancel, resume, and split actions to Admin API
Damian Legawiecd4e6b4fc08c8
diff --git a/packages/sdk/src/admin-client.ts b/packages/sdk/src/admin-client.tsindex e588962a49..7697a2d200 100644--- a/packages/sdk/src/admin-client.ts+++ b/packages/sdk/src/admin-client.ts@@ -34,6 +34,7 @@ import type {AdminProductCreateParams,AdminProductUpdateParams,AdminRefundCreateParams,+ AdminShipmentSplitParams,AdminShipmentUpdateParams,AdminTaxonCreateParams,AdminTaxonUpdateParams,@@ -58,6 +59,7 @@ export type {AdminProductCreateParams,AdminProductUpdateParams,AdminRefundCreateParams,+ AdminShipmentSplitParams,AdminShipmentUpdateParams,AdminTaxonCreateParams,AdminTaxonUpdateParams,@@ -337,6 +339,34 @@ export class AdminClient {): Promise<AdminShipment> =>this.request<AdminShipment>('PATCH', `/orders/${orderId}/shipments/${id}/ship`, options),+ /** Cancel a shipment */+ cancel: (+ orderId: string,+ id: string,+ options?: RequestOptions+ ): Promise<AdminShipment> =>+ this.request<AdminShipment>('PATCH', `/orders/${orderId}/shipments/${id}/cancel`, options),++ /** Resume a canceled shipment */+ resume: (+ orderId: string,+ id: string,+ options?: RequestOptions+ ): Promise<AdminShipment> =>+ this.request<AdminShipment>('PATCH', `/orders/${orderId}/shipments/${id}/resume`, options),++ /** Split a shipment - transfer items to a new shipment */+ split: (+ orderId: string,+ id: string,+ params: AdminShipmentSplitParams,+ options?: RequestOptions+ ): Promise<{ data: AdminShipment[] }> =>+ this.request<{ data: AdminShipment[] }>('PATCH', `/orders/${orderId}/shipments/${id}/split`, {+ ...options,+ body: params,+ }),+},/** Nested: orders/{id}/payments */diff --git a/packages/sdk/src/admin-params.ts b/packages/sdk/src/admin-params.tsindex d2e3e82a00..62eb4dcbba 100644--- a/packages/sdk/src/admin-params.ts+++ b/packages/sdk/src/admin-params.ts@@ -181,6 +181,12 @@ export interface AdminShipmentUpdateParams {stock_location_id?: string;}+export interface AdminShipmentSplitParams {+ variant_id: string;+ quantity: number;+ stock_location_id?: string;+}+export interface AdminPaymentCreateParams {payment_method_id: string;amount?: number;diff --git a/packages/sdk/tests/admin/shipments.test.ts b/packages/sdk/tests/admin/shipments.test.tsindex 4ce6a99504..21ed544227 100644--- a/packages/sdk/tests/admin/shipments.test.ts+++ b/packages/sdk/tests/admin/shipments.test.ts@@ -46,4 +46,34 @@ describe('admin / orders.shipments', () => {expect(result.shipped_at).toBeTruthy();});});++ describe('cancel', () => {+ it('cancels a shipment', async () => {+ const result = await client.admin.orders.shipments.cancel(orderId, 'ship_1');++ expect(result.state).toBe('canceled');+ });+ });++ describe('resume', () => {+ it('resumes a canceled shipment', async () => {+ const result = await client.admin.orders.shipments.resume(orderId, 'ship_1');++ expect(result.state).toBe('ready');+ });+ });++ describe('split', () => {+ it('splits a shipment to a new stock location', async () => {+ const result = await client.admin.orders.shipments.split(orderId, 'ship_1', {+ variant_id: 'var_1',+ quantity: 1,+ stock_location_id: 'sl_2',+ });++ expect(result.data).toHaveLength(2);+ expect(result.data[0].id).toBe('ship_1');+ expect(result.data[1].id).toBe('ship_2');+ });+ });});diff --git a/packages/sdk/tests/mocks/admin-handlers.ts b/packages/sdk/tests/mocks/admin-handlers.tsindex 8a5fb7fb9e..df661e90ca 100644--- a/packages/sdk/tests/mocks/admin-handlers.ts+++ b/packages/sdk/tests/mocks/admin-handlers.ts@@ -345,6 +345,21 @@ export const adminHandlers = [HttpResponse.json({ ...adminFixtures.shipment, state: 'shipped', shipped_at: '2026-03-06T14:00:00.000Z' })),+ http.patch(`${API_PREFIX}/orders/:orderId/shipments/:id/cancel`, () =>+ HttpResponse.json({ ...adminFixtures.shipment, state: 'canceled' })+ ),++ http.patch(`${API_PREFIX}/orders/:orderId/shipments/:id/resume`, () =>+ HttpResponse.json({ ...adminFixtures.shipment, state: 'ready' })+ ),++ http.patch(`${API_PREFIX}/orders/:orderId/shipments/:id/split`, () =>+ HttpResponse.json({ data: [+ { ...adminFixtures.shipment, id: 'ship_1' },+ { ...adminFixtures.shipment, id: 'ship_2', stock_location_id: 'sl_2' },+ ] })+ ),+http.patch(`${API_PREFIX}/orders/:orderId/shipments/:id`, () =>HttpResponse.json({ ...adminFixtures.shipment, tracking: '1Z999AA10123456784' })),diff --git a/spree/api/ADMIN_API_PLAN.md b/spree/api/ADMIN_API_PLAN.mdindex e30cb9a1e6..3126f1781f 100644--- a/spree/api/ADMIN_API_PLAN.md+++ b/spree/api/ADMIN_API_PLAN.md@@ -278,30 +278,32 @@ Here's the endpoint list we need to implement:- [x] `DELETE /api/v3/admin/orders/:order_id/line_items/:id` — Remove line item### Shipments (nested under Orders)-- [ ] `GET /api/v3/admin/orders/:order_id/shipments` — List shipments-- [ ] `GET /api/v3/admin/orders/:order_id/shipments/:id` — Show shipment+- [x] `GET /api/v3/admin/orders/:order_id/shipments` — List shipments+- [x] `GET /api/v3/admin/orders/:order_id/shipments/:id` — Show shipment- [ ] `POST /api/v3/admin/orders/:order_id/shipments` — Create shipment-- [ ] `PATCH /api/v3/admin/orders/:order_id/shipments/:id` — Update shipment-- [ ] `PATCH /api/v3/admin/orders/:order_id/shipments/:id/ship` — Mark shipment as shipped-- [ ] `POST /api/v3/admin/orders/:order_id/shipments/:id/transfer` — Transfer items between shipments+- [x] `PATCH /api/v3/admin/orders/:order_id/shipments/:id` — Update shipment+- [x] `PATCH /api/v3/admin/orders/:order_id/shipments/:id/ship` — Mark shipment as shipped+- [x] `PATCH /api/v3/admin/orders/:order_id/shipments/:id/cancel` — Cancel a shipment+- [x] `PATCH /api/v3/admin/orders/:order_id/shipments/:id/resume` — Resume a canceled shipment+- [x] `PATCH /api/v3/admin/orders/:order_id/shipments/:id/split` — Split/transfer items to a new shipment### Payments (nested under Orders)-- [ ] `GET /api/v3/admin/orders/:order_id/payments` — List payments-- [ ] `GET /api/v3/admin/orders/:order_id/payments/:id` — Show payment-- [ ] `POST /api/v3/admin/orders/:order_id/payments` — Create payment-- [ ] `PATCH /api/v3/admin/orders/:order_id/payments/:id/capture` — Capture payment-- [ ] `PATCH /api/v3/admin/orders/:order_id/payments/:id/void` — Void payment+- [x] `GET /api/v3/admin/orders/:order_id/payments` — List payments+- [x] `GET /api/v3/admin/orders/:order_id/payments/:id` — Show payment+- [x] `POST /api/v3/admin/orders/:order_id/payments` — Create payment+- [x] `PATCH /api/v3/admin/orders/:order_id/payments/:id/capture` — Capture payment+- [x] `PATCH /api/v3/admin/orders/:order_id/payments/:id/void` — Void payment### Refunds (nested under Orders)-- [ ] `GET /api/v3/admin/orders/:order_id/refunds` — List refunds-- [ ] `POST /api/v3/admin/orders/:order_id/refunds` — Create refund (with payment_id in body)+- [x] `GET /api/v3/admin/orders/:order_id/refunds` — List refunds+- [x] `POST /api/v3/admin/orders/:order_id/refunds` — Create refund (with payment_id in body)- [ ] `PATCH /api/v3/admin/orders/:order_id/refunds/:id` — Update refund### Adjustments (nested under Orders)-- [ ] `GET /api/v3/admin/orders/:order_id/adjustments` — List adjustments-- [ ] `POST /api/v3/admin/orders/:order_id/adjustments` — Create adjustment-- [ ] `PATCH /api/v3/admin/orders/:order_id/adjustments/:id` — Update adjustment-- [ ] `DELETE /api/v3/admin/orders/:order_id/adjustments/:id` — Delete adjustment+- [x] `GET /api/v3/admin/orders/:order_id/adjustments` — List adjustments+- [x] `POST /api/v3/admin/orders/:order_id/adjustments` — Create adjustment+- [x] `PATCH /api/v3/admin/orders/:order_id/adjustments/:id` — Update adjustment+- [x] `DELETE /api/v3/admin/orders/:order_id/adjustments/:id` — Delete adjustment### Order User Assignment- [ ] `PUT /api/v3/admin/orders/:order_id/user` — Assign user to orderdiff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/shipments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/shipments_controller.rbindex 150b0fcfbb..091522cbb9 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/shipments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/shipments_controller.rb@@ -7,8 +7,8 @@ module Spreeinclude Spree::Api::V3::OrderLockbefore_action :authorize_order_access!- skip_before_action :set_resource, only: [:index]- before_action :set_shipment, only: [:show, :update, :ship]+ skip_before_action :set_resource, only: [:index, :show, :update, :ship, :cancel, :resume, :split]+ before_action :set_shipment, only: [:show, :update, :ship, :cancel, :resume, :split]# PATCH /api/v3/admin/orders/:order_id/shipments/:iddef update@@ -29,15 +29,55 @@ module Spree# PATCH /api/v3/admin/orders/:order_id/shipments/:id/shipdef shipwith_order_lock do- result = Spree.shipment_change_state_service.call(- shipment: @resource,- state: 'ship'- )+ @resource.ship!+ render json: serialize_resource(@resource.reload)+ rescue StateMachines::InvalidTransition => e+ render_service_error(e.message)+ end+ end- if result.success?- render json: serialize_resource(@resource.reload)+ # PATCH /api/v3/admin/orders/:order_id/shipments/:id/cancel+ def cancel+ with_order_lock do+ @resource.cancel!+ render json: serialize_resource(@resource.reload)+ rescue StateMachines::InvalidTransition => e+ render_service_error(e.message)+ end+ end++ # PATCH /api/v3/admin/orders/:order_id/shipments/:id/resume+ def resume+ with_order_lock do+ @resource.resume!+ render json: serialize_resource(@resource.reload)+ rescue StateMachines::InvalidTransition => e+ render_service_error(e.message)+ end+ end++ # PATCH /api/v3/admin/orders/:order_id/shipments/:id/split+ def split+ with_order_lock do+ variant = Spree::Variant.find_by_prefix_id!(params[:variant_id])+ quantity = params[:quantity].to_i++ stock_location = if params[:stock_location_id].present?+ Spree::StockLocation.find_by_prefix_id!(params[:stock_location_id])+ else+ @resource.stock_location+ end++ fulfilment_changer = @resource.transfer_to_location(variant, quantity, stock_location)++ if fulfilment_changer.run!+ # Original shipment may be destroyed if all items were transferred+ shipments = @order.reload.shipments+ render json: {+ data: shipments.map { |s| serialize_resource(s) }+ }else- render_service_error(result.error)+ render_validation_error(fulfilment_changer.errors)endendenddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 06cff873b9..0c1e5ef1ef 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -127,6 +127,9 @@ Spree::Core::Engine.add_routes doresources :shipments, controller: 'orders/shipments', only: [:index, :show, :update] domember dopatch :ship+ patch :cancel+ patch :resume+ patch :splitendendresources :payments, controller: 'orders/payments', only: [:index, :show, :create] dodiff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/shipments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/shipments_controller_spec.rbindex 79be3ff2d4..78e0293434 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/shipments_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/shipments_controller_spec.rb@@ -46,7 +46,6 @@ RSpec.describe Spree::Api::V3::Admin::Orders::ShipmentsController, type: :controdescribe 'PATCH #ship' doit 'marks the shipment as shipped' do- # Ensure shipment is readyshipment.ready! if shipment.can_ready?patch :ship, params: {@@ -58,4 +57,49 @@ RSpec.describe Spree::Api::V3::Admin::Orders::ShipmentsController, type: :controexpect(json_response['state']).to eq('shipped')endend++ describe 'PATCH #cancel' do+ it 'cancels the shipment' do+ patch :cancel, params: {+ order_id: order.prefixed_id,+ id: shipment.prefixed_id+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['state']).to eq('canceled')+ end+ end++ describe 'PATCH #resume' do+ it 'resumes a canceled shipment' do+ shipment.cancel!++ patch :resume, params: {+ order_id: order.prefixed_id,+ id: shipment.prefixed_id+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(%w[pending ready]).to include(json_response['state'])+ end+ end++ describe 'PATCH #split' do+ it 'splits items to a new shipment at a different stock location' do+ variant = shipment.inventory_units.first.variant+ target_stock_location = create(:stock_location, name: 'Warehouse 2')+ target_stock_location.stock_items.find_or_create_by(variant: variant).set_count_on_hand(10)++ patch :split, params: {+ order_id: order.prefixed_id,+ id: shipment.prefixed_id,+ variant_id: variant.prefixed_id,+ quantity: 1,+ stock_location_id: target_stock_location.prefixed_id+ }, as: :json++ expect(response).to have_http_status(:ok), "Expected 200 but got #{response.status}: #{response.body}"+ expect(json_response['data']).to be_an(Array)+ end+ endenddiff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/shipments_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/shipments_spec.rbindex ecc2c5172c..d5b8a571d2 100644--- a/spree/api/spec/integration/spree/api/v3/admin/orders/shipments_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/shipments_spec.rb@@ -130,4 +130,109 @@ RSpec.describe 'Admin Order Shipments API', type: :request, swagger_doc: 'api-reendendend++ path '/api/v3/admin/orders/{order_id}/shipments/{id}/cancel' do+ patch 'Cancel a shipment' do+ tags 'Shipments'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Cancels a pending or ready shipment.'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ parameter name: :order_id, in: :path, type: :string, required: true,+ description: 'Order prefixed ID'+ parameter name: :id, in: :path, type: :string, required: true,+ description: 'Shipment prefixed ID'++ response '200', 'shipment canceled' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:order_id) { order.prefixed_id }+ let(:id) { shipment.prefixed_id }++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['state']).to eq('canceled')+ end+ end+ end+ end++ path '/api/v3/admin/orders/{order_id}/shipments/{id}/resume' do+ patch 'Resume a shipment' do+ tags 'Shipments'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Resumes a canceled shipment.'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ parameter name: :order_id, in: :path, type: :string, required: true,+ description: 'Order prefixed ID'+ parameter name: :id, in: :path, type: :string, required: true,+ description: 'Shipment prefixed ID'++ response '200', 'shipment resumed' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:order_id) { order.prefixed_id }+ let(:id) { shipment.prefixed_id }++ before do+ shipment.cancel!+ end++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(%w[pending ready]).to include(data['state'])+ end+ end+ end+ end++ path '/api/v3/admin/orders/{order_id}/shipments/{id}/split' do+ patch 'Split a shipment' do+ tags 'Shipments'+ consumes 'application/json'+ produces 'application/json'+ security [api_key: [], bearer_auth: []]+ description 'Transfers items from this shipment to a new shipment at a different stock location.'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true,+ description: 'Bearer token for admin authentication'+ parameter name: :order_id, in: :path, type: :string, required: true,+ description: 'Order prefixed ID'+ parameter name: :id, in: :path, type: :string, required: true,+ description: 'Shipment prefixed ID'+ parameter name: :body, in: :body, schema: {+ type: :object,+ required: %w[variant_id quantity],+ properties: {+ variant_id: { type: :string, description: 'Variant prefixed ID' },+ quantity: { type: :integer, example: 1 },+ stock_location_id: { type: :string, description: 'Target stock location prefixed ID' }+ }+ }++ response '200', 'shipment split' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:order_id) { order.prefixed_id }+ let(:id) { shipment.prefixed_id }+ let(:variant) { shipment.inventory_units.first.variant }+ let(:stock_location) { create(:stock_location, name: 'Warehouse 2') }+ let(:body) { { variant_id: variant.prefixed_id, quantity: 1, stock_location_id: stock_location.prefixed_id } }++ before do+ stock_location.stock_items.find_or_create_by(variant: variant).set_count_on_hand(10)+ end++ run_test! do |response|+ data = JSON.parse(response.body)+ expect(data['data']).to be_an(Array)+ end+ end+ end+ endend