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
Added Platform API Shipments create endpoint
Damian Legawiec381b9845262b
diff --git a/api/app/controllers/concerns/spree/api/v2/number_resource.rb b/api/app/controllers/concerns/spree/api/v2/number_resource.rbnew file mode 100644index 0000000000..945195abd9--- /dev/null+++ b/api/app/controllers/concerns/spree/api/v2/number_resource.rb@@ -0,0 +1,11 @@+module Spree+ module Api+ module V2+ module NumberResource+ def resource+ @resource ||= scope.find_by(number: params[:id]) || scope.find(params[:id])+ end+ end+ end+ end+enddiff --git a/api/app/controllers/spree/api/v2/base_controller.rb b/api/app/controllers/spree/api/v2/base_controller.rbindex 57f8abc1cb..b3196b29ec 100644--- a/api/app/controllers/spree/api/v2/base_controller.rb+++ b/api/app/controllers/spree/api/v2/base_controller.rb@@ -64,9 +64,9 @@ module Spreerender json: json, status: status, content_type: content_typeend- def render_result(result)+ def render_result(result, ok_status = 200)if result.success?- render_serialized_payload { serialize_resource(result.value) }+ render_serialized_payload(ok_status) { serialize_resource(result.value) }elserender_error_payload(result.error)enddiff --git a/api/app/controllers/spree/api/v2/platform/shipments_controller.rb b/api/app/controllers/spree/api/v2/platform/shipments_controller.rbnew file mode 100644index 0000000000..6e4d526bec--- /dev/null+++ b/api/app/controllers/spree/api/v2/platform/shipments_controller.rb@@ -0,0 +1,151 @@+module Spree+ module Api+ module V2+ module Platform+ class ShipmentsController < ResourceController+ include NumberResource++ before_action :load_variant, only: %i[add_item remove_item transfer_to_location transfer_to_shipment]+ before_action :load_stock_location, only: %i[transfer_to_location]++ SHIPMENT_STATES = %w[ready ship cancel resume pend]++ def create+ result = create_service.call(+ store: current_store,+ shipment_attributes: params.require(:shipment).permit(+ :order_id, :stock_location_id, :variant_id, :quantity+ )+ )+ render_result(result, 201)+ end++ def update+ result = update_service.call(shipment: resource, shipment_attributes: permitted_resource_params)+ render_result(result)+ end++ SHIPMENT_STATES.each do |state|+ define_method state do+ result = change_state_service.call(shipment: resource, state: state)+ render_result(result)+ end+ end++ # adds item to an existing shipment+ # if this variant is already added to the cart it will increase the quantity+ # if not it will create new line item+ # def add_item+ # quantity = params.dig(:shipment, :quantity)&.to_i || 1++ # Spree::Dependencies.cart_add_item_service.constantize.call(order: resource.order,+ # variant: @variant,+ # quantity: quantity,+ # options: { shipment: resource })++ # render_serialized_payload { serialize_resource(resource) }+ # end++ # removes an item (variant) from shipment+ # quantity can be passed+ # if there is no quantity left for this item for this shipent, shipment itself will be removed+ # TODO: move this code+ # def remove_item+ # quantity = params.dig(:shipment, :quantity)&.to_i || resource.inventory_units_for(variant).sum(:quantity)++ # result = Spree::Dependencies.cart_remove_item_service.constantize.call(order: resource.order,+ # variant: @variant,+ # quantity: quantity,+ # options: { shipment: resource })++ # if result.success?+ # if resource.inventory_units.any?+ # render_serialized_payload { serialize_resource(resource.reload) }+ # elsif resource.detroy!+ # head 204+ # else+ # render_error_payload(resource)+ # end+ # else+ # render_error_payload(result.error)+ # end+ # end++ # def transfer_to_location+ # quantity = params.dig(:shipment, :quantity)&.to_i || 1++ # unless quantity > 0+ # unprocessable_entity("#{Spree.t(:shipment_transfer_errors_occurred, scope: 'api')} \n #{Spree.t(:negative_quantity, scope: 'api')}")+ # return+ # end++ # transfer = resource.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+ # @target_shipment = Spree::Shipment.find_by!(number: params[:target_shipment_number])++ # error =+ # if @quantity < 0 && @target_shipment == @original_shipment+ # "#{Spree.t(:negative_quantity, scope: 'api')}, \n#{Spree.t('wrong_shipment_target', scope: 'api')}"+ # elsif @target_shipment == @original_shipment+ # Spree.t(:wrong_shipment_target, scope: 'api')+ # elsif @quantity < 0+ # Spree.t(:negative_quantity, scope: 'api')+ # end++ # if error+ # unprocessable_entity("#{Spree.t(:shipment_transfer_errors_occurred, scope: 'api')} \n#{error}")+ # else+ # 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++ private++ def model_class+ Spree::Shipment+ end++ def load_variant+ @variant = current_store.variants.find_by(id: params.dig(:shipment, :variant_id))+ end++ def load_stock_location+ @stock_location = Spree::StockLocation.find(params.dig(:shipment, :stock_location_id))+ end++ def spree_permitted_attributes+ Spree::Shipment.json_api_permitted_attributes + [+ :selected_shipping_rate_id+ ]+ end++ def create_service+ Spree::Api::Dependencies.platform_shipment_create_service.constantize+ end++ def update_service+ Spree::Api::Dependencies.platform_shipment_update_service.constantize+ end++ def change_state_service+ Spree::Api::Dependencies.platform_shipment_change_state_service.constantize+ end+ end+ end+ end+ end+enddiff --git a/api/app/serializers/spree/api/v2/platform/shipments_controller.rb b/api/app/serializers/spree/api/v2/platform/shipments_controller.rbdeleted file mode 100644index b8aaf46c7f..0000000000--- a/api/app/serializers/spree/api/v2/platform/shipments_controller.rb+++ /dev/null@@ -1,47 +0,0 @@-module Spree- module Api- module V2- module Platform- class ShipmentsController < ResourceController- SHIPMENT_STATES = %w[ready ship cancel resume pend]-- def update- result = update_service.call(shipment: resource, shipment_attributes: resource_permitted_attributes)- render_result(result)- end-- SHIPMENT_STATES.each do |state|- define_method state do- result = change_state_service.call(shipment: resource, state: state)- render_result(result)- end- end-- private-- def model_class- Spree::Shipment- end-- def resource- @resource ||= scope.find_by(number: params[:id]) || scope.find(params[:id])- end-- def spree_permitted_attributes- Spree::Shipment.json_api_permitted_attributes + [- :selected_shipping_rate_id- ]- end-- def update_service- Spree::Api::Dependencies.platform_shipment_update_service.constantize- end-- def change_state_service- Spree::Api::Dependencies.platform_shipment_change_state_service.constantize- end- end- end- end- end-enddiff --git a/api/lib/spree/api/api_dependencies.rb b/api/lib/spree/api/api_dependencies.rbindex 2449bfea9d..ba109b7c38 100644--- a/api/lib/spree/api/api_dependencies.rb+++ b/api/lib/spree/api/api_dependencies.rb@@ -30,7 +30,7 @@ module Spree:platform_order_next_service, :platform_order_advance_service,:platform_line_item_create_service, :platform_line_item_update_service, :platform_line_item_destroy_service,:platform_order_approve_service, :platform_order_cancel_service,- :platform_shipment_change_state_service, :platform_shipment_update_service+ :platform_shipment_change_state_service, :platform_shipment_create_service, :platform_shipment_update_service].freezeattr_accessor *INJECTION_POINTS@@ -152,6 +152,7 @@ module Spree@platform_line_item_destroy_service = Spree::Dependencies.line_item_destroy_service# shipment services+ @platform_shipment_create_service = Spree::Dependencies.shipment_create_service@platform_shipment_update_service = Spree::Dependencies.shipment_update_service@platform_shipment_change_state_service = Spree::Dependencies.shipment_change_state_serviceenddiff --git a/api/spec/integration/api/v2/platform/shipments_spec.rb b/api/spec/integration/api/v2/platform/shipments_spec.rbindex a091ceef37..dcd9425878 100644--- a/api/spec/integration/api/v2/platform/shipments_spec.rb+++ b/api/spec/integration/api/v2/platform/shipments_spec.rb@@ -10,33 +10,46 @@ describe 'Shipments API', swagger: true dofilter_examples: [{ name: 'filter[state_eq]', example: 'complete' }]}- let(:order) { create(:order_ready_to_ship) }+ let(:order) { create(:order_ready_to_ship, store: store) }+ let(:product) { create(:product_in_stock, stores: [store]) }let(:id) { create(:shipment, order: order).id }let(:records_list) { create_list(:shipment, 2) }let(:store) { Spree::Store.default }let(:valid_create_param_value) do{-+ shipment: {+ stock_location_id: create(:stock_location).id,+ order_id: create(:order_with_totals, store: store).id,+ variant_id: product.master.id,+ quantity: 1+ }+ }+ end+ let(:invalid_create_param_value) do+ {+ shipment: {+ stock_location_id: 1412431243,+ order_id: create(:order_with_totals, store: store).id,+ variant_id: product.master.id+ }}endlet(:valid_update_param_value) do{+ shipment: {+ tracking: 'MY-TRACKING-NUMBER-1234'+ }}endlet(:invalid_param_value) do{+ shipment: {+ stock_location_id: 'invalid'+ }}end- path "/api/v2/platform/#{resource_path}" do- include_examples 'GET records list', resource_name, options- end-- path "/api/v2/platform/#{resource_path}/{id}" do- include_examples 'GET record', resource_name, options- # include_examples 'PATCH update record', resource_name, options- include_examples 'DELETE record', resource_name- end+ include_examples 'CRUD examples', resource_name, optionspath "/api/v2/platform/#{resource_path}/{id}/ready" dopatch "Mark Shipment as ready to be shipped" do@@ -91,6 +104,11 @@ describe 'Shipments API', swagger: true dopath "/api/v2/platform/#{resource_path}/{id}/resume" dolet(:id) { create(:shipment, order: order, state: :canceled).id }+ # we need to ensure that the item is in stock before resuming+ before do+ order.line_items.first.variant.stock_items.update_all(count_on_hand: 10)+ end+patch "Resumes the Shipment" dotags resource_name.pluralizesecurity [ bearer_auth: [] ]diff --git a/core/app/services/spree/shipments/create.rb b/core/app/services/spree/shipments/create.rbnew file mode 100644index 0000000000..9c0ffbeba3--- /dev/null+++ b/core/app/services/spree/shipments/create.rb@@ -0,0 +1,64 @@+module Spree+ module Shipments+ class Create+ prepend Spree::ServiceModule::Base++ attr_accessor :shipment++ def call(store:, shipment_attributes:)+ ActiveRecord::Base.transaction do+ run :prepare_arguments+ run :create_shipment+ run :add_or_update_line_item+ end+ end++ protected++ def prepare_arguments(store:, shipment_attributes:)+ order_id_or_number = shipment_attributes[:order_id]+ order = store.orders.find_by(number: order_id_or_number) || store.orders.find_by(id: order_id_or_number)++ return failure(nil, :order_not_found) if order.nil?++ variant = store.variants.find_by(id: shipment_attributes[:variant_id])+ return failure(nil, :variant_not_found) if variant.nil?++ stock_location = Spree::StockLocation.find_by(id: shipment_attributes[:stock_location_id])+ return failure(nil, :stock_location_not_found) if stock_location.nil?++ quantity = shipment_attributes[:quantity]&.to_i || 1++ success(order: order, stock_location: stock_location, variant: variant, quantity: quantity)+ end++ def create_shipment(order:, stock_location:, variant:, quantity:)+ @shipment = order.shipments.create(+ order_id: order.id,+ stock_location_id: stock_location.id+ )+ return failure(shipment) unless shipment.persisted?++ success(order: order, variant: variant, quantity: quantity, shipment: shipment)+ end++ def return_shipment(line_item)+ success(line_item.target_shipment)+ end++ def add_or_update_line_item(order:, variant:, quantity:, shipment:)+ result = add_item_service.call(order: order, variant: variant, quantity: quantity, options: { shipment: shipment})++ if result.success?+ success(shipment.reload)+ else+ failure(result.value, result.error)+ end+ end++ def add_item_service+ Spree::Dependencies.cart_add_item_service.constantize+ end+ end+ end+enddiff --git a/core/lib/spree/core/app_dependencies.rb b/core/lib/spree/core/app_dependencies.rbindex 8d7dcb7660..6740085b53 100644--- a/core/lib/spree/core/app_dependencies.rb+++ b/core/lib/spree/core/app_dependencies.rb@@ -16,6 +16,7 @@ module Spree:classification_reposition_service, :credit_cards_destroy_service, :cart_associate_service, :cart_change_currency_service,:line_item_create_service, :line_item_update_service, :line_item_destroy_service,:order_approve_service, :order_cancel_service, :shipment_change_state_service, :shipment_update_service,+ :shipment_create_service,:payment_create_service, :address_create_service, :address_update_service,:checkout_select_shipping_method_service].freeze@@ -66,6 +67,7 @@ module Spree# shipment@shipment_change_state_service = 'Spree::Shipments::ChangeState'+ @shipment_create_service = 'Spree::Shipments::Create'@shipment_update_service = 'Spree::Shipments::Update'# sorterdiff --git a/core/spec/services/spree/shipments/create_spec.rb b/core/spec/services/spree/shipments/create_spec.rbnew file mode 100644index 0000000000..1bd111bcf2--- /dev/null+++ b/core/spec/services/spree/shipments/create_spec.rb@@ -0,0 +1,131 @@+require 'spec_helper'++module Spree+ describe Shipments::Create do+ subject { described_class }++ let(:store) { create(:store) }+ let(:order) { create(:order_with_totals, store: store, user: nil, email: '[email protected]') }+ let(:product) { create(:product_in_stock, stores: [store]) }+ let(:variant) { product.master }+ let(:stock_location) { product.stock_items.first.stock_location }++ let(:execute) { subject.call(store: store, shipment_attributes: shipment_attributes) }+ let(:value) { execute.value }++ let(:shipment_attributes) do+ {+ order_id: order.id,+ variant_id: variant.id,+ quantity: 2,+ stock_location_id: stock_location.id+ }+ end++ let(:shipment) { order.shipments.last }+ let(:line_item) { shipment.line_items.last }++ context 'valid attributes' do+ shared_context 'creates a shipment' do+ it 'creates new shipment record' do+ expect { execute }.to change(order.shipments, :count).by(1)+ expect(shipment.stock_location).to eq(stock_location)+ end++ it { expect(execute.success?).to eq(true) }+ it { expect(execute.value).to be_kind_of(Spree::Shipment) }+ end++ shared_context 'creates a line item' do+ it 'creates new line item record' do+ expect { execute }.to change(order.line_items, :count).by(1)+ expect(line_item.variant).to eq(variant)+ expect(line_item.quantity).to eq(2)+ end+ end++ context 'without pre-existing line item' do+ it_behaves_like 'creates a shipment'+ it_behaves_like 'creates a line item'+ end++ context 'with existing line item' do+ let!(:old_line_item) { create(:line_item, order: order, variant: variant, quantity: 2) }++ it_behaves_like 'creates a shipment'++ it 'does not create a new line item' do+ expect { execute }.not_to change(order.line_items, :count)+ end++ it 'adds quantity to the existing line item' do+ expect(old_line_item.quantity).to eq(2)+ execute+ expect(old_line_item.reload.quantity).to eq(4)+ end++ it 'updates line item totals' do+ expect(old_line_item.total).to eq(20)+ execute+ expect(old_line_item.reload.total).to eq(BigDecimal(40)) # 4 x 10 unit price+ end+ end+ end++ context 'missing variant' do+ let(:shipment_attributes) do+ {+ order_id: order.id,+ variant_id: 1312415,+ quantity: 1,+ stock_location_id: stock_location.id+ }+ end++ it { expect(execute.success?).to eq(false) }+ it { expect(execute.error.to_s).to eq('variant_not_found') }+ end++ context 'missing order' do+ let(:shipment_attributes) do+ {+ order_id: 1231243,+ variant_id: variant.id,+ quantity: 1,+ stock_location_id: stock_location.id+ }+ end++ it { expect(execute.success?).to eq(false) }+ it { expect(execute.error.to_s).to eq('order_not_found') }+ end++ context 'missing stock location' do+ let(:shipment_attributes) do+ {+ order_id: order.id,+ variant_id: variant.id,+ quantity: 1,+ stock_location_id: 1341234+ }+ end++ it { expect(execute.success?).to eq(false) }+ it { expect(execute.error.to_s).to eq('stock_location_not_found') }+ end++ xcontext 'invalid attributes' do+ let(:shipment_attributes) do+ {+ order_id: order.id,+ variant_id: variant.id,+ quantity: 'invalid', # this will not work as we're doing `to_i` casting+ stock_location_id: stock_location.id+ }+ end++ it { expect(execute.success?).to eq(false) }+ it { expect(execute.error.value).to be_kind_of(ActiveModel::Errors) }+ end+ end+end