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
Storefront API - Checkout Select Shipping Method endpoint (#11458)
Damian Legawiec2e0ce229c227
diff --git a/api/app/controllers/spree/api/v2/storefront/checkout_controller.rb b/api/app/controllers/spree/api/v2/storefront/checkout_controller.rbindex a7d0a87dbb..5248f44b4b 100644--- a/api/app/controllers/spree/api/v2/storefront/checkout_controller.rb+++ b/api/app/controllers/spree/api/v2/storefront/checkout_controller.rb@@ -54,6 +54,12 @@ module Spreeendend+ def select_shipping_method+ result = select_shipping_method_service.call(order: spree_current_order, params: params)++ render_order(result)+ end+def add_store_creditspree_authorize! :update, spree_current_order, order_token@@ -132,6 +138,10 @@ module SpreeSpree::Api::Dependencies.storefront_payment_create_service.constantizeend+ def select_shipping_method_service+ Spree::Api::Dependencies.storefront_checkout_select_shipping_method_service.constantize+ end+def serialize_payment_methods(payment_methods)payment_methods_serializer.new(payment_methods, params: serializer_params).serializable_hashenddiff --git a/api/app/serializers/spree/v2/storefront/shipment_serializer.rb b/api/app/serializers/spree/v2/storefront/shipment_serializer.rbindex a671d9f54f..a05ec214a4 100644--- a/api/app/serializers/spree/v2/storefront/shipment_serializer.rb+++ b/api/app/serializers/spree/v2/storefront/shipment_serializer.rb@@ -12,6 +12,7 @@ module Spreeendhas_many :shipping_rates+ has_one :selected_shipping_rate, serializer: :shipping_ratebelongs_to :stock_locationenddiff --git a/api/config/routes.rb b/api/config/routes.rbindex 27cade3e44..6a45f09a61 100644--- a/api/config/routes.rb+++ b/api/config/routes.rb@@ -150,6 +150,7 @@ Spree::Core::Engine.add_routes dopost :remove_store_creditget :payment_methodsget :shipping_rates+ patch :select_shipping_methodendresource :account, controller: :account, only: %i[show create update]diff --git a/api/docs/v2/storefront/index.yaml b/api/docs/v2/storefront/index.yamlindex 54c5fb2cf6..cbcd84dbed 100644--- a/api/docs/v2/storefront/index.yaml+++ b/api/docs/v2/storefront/index.yaml@@ -6,9 +6,9 @@ servers:description: localhostinfo:version: 2.0.0- title: Storefront API v2+ title: Storefront APIdescription: |-- Storefront API v2 is a modern REST API based on the [JSON API spec](https://jsonapi.org/) which provides you with all the necessary endpoints to build amazing user intefaces either in JavaScript frameworks or native mobile libraries.+ Storefront API is a modern REST API based on the [JSON API spec](https://jsonapi.org/) which provides you with all the necessary endpoints to build amazing user intefaces either in JavaScript frameworks or native mobile libraries.Download [official JavaScript & TypeScript SDK](https://github.com/spree/spree-storefront-api-v2-js-sdk)@@ -868,6 +868,54 @@ paths:summary: Complete Checkouttags:- Checkout / State+ /api/v2/storefront/checkout/select_shipping_method:+ patch:+ description: |-+ Selects shipping method for Shipment(s).++ To generate shipments you first need to fetch shipping rates via++ [Get Shipping Rates](https://api.spreecommerce.org/docs/api-v2/b3A6MzE0Mjc2MQ-list-shipping-rates) endpoint+ operationId: select-shipping-method+ responses:+ '200':+ $ref: '#/components/responses/Cart'+ '404':+ $ref: '#/components/responses/404NotFound'+ '422':+ $ref: '#/components/responses/422UnprocessableEntity'+ security:+ - orderToken: []+ - bearerAuth: []+ requestBody:+ content:+ application/vnd.api+json:+ schema:+ type: object+ properties:+ shipping_method_id:+ type: string+ description: ID of the selected Shipping Method+ shipment_id:+ type: string+ description: 'ID of the selected Shipment. If not supplied it will try to set selected shipping method for all shipments'+ required:+ - shipping_method_id+ examples:+ Set shippng method for all shipments:+ value:+ shipping_method_id: '1'+ Set shipping method for specific shipment:+ value:+ shipping_method_id: '1'+ shipment_id: '1'+ description: ''+ parameters:+ - $ref: '#/components/parameters/CartIncludeParam'+ - $ref: '#/components/parameters/SparseFieldsCart'+ summary: Selects shipping method for shipment(s)+ tags:+ - Checkout / Shipments/api/v2/storefront/checkout/create_payment:post:description: |-@@ -1010,7 +1058,7 @@ paths:get:description: Returns a list of available payment methods for this checkout.tags:- - Checkout+ - Checkout / PaymentsoperationId: payment-methodsresponses:'200':@@ -1028,7 +1076,7 @@ paths:Shipping rates are grouped against shipments. Each checkout can have multiple shipments. Some products are in stock and will be shipped immediately, while others might be back-ordered and sent later.tags:- - Checkout+ - Checkout / ShipmentsoperationId: shipping-ratesresponses:'200':@@ -16083,6 +16131,7 @@ tags:- name: Cart / Other- name: Checkout- name: Checkout / State+ - name: Checkout / Shipments- name: Checkout / Payments- name: Checkout / Store Credit- name: CMS Pagesdiff --git a/api/lib/spree/api/api_dependencies.rb b/api/lib/spree/api/api_dependencies.rbindex 36ffbe779b..2449bfea9d 100644--- a/api/lib/spree/api/api_dependencies.rb+++ b/api/lib/spree/api/api_dependencies.rb@@ -22,6 +22,7 @@ module Spree:storefront_cart_empty_service, :storefront_cart_destroy_service, :storefront_credit_cards_destroy_service, :platform_products_sorter,:storefront_cart_change_currency_service, :storefront_payment_serializer,:storefront_payment_create_service, :storefront_address_create_service, :storefront_address_update_service,+ :storefront_checkout_select_shipping_method_service,:platform_admin_user_serializer, :platform_coupon_handler, :platform_order_update_service,:platform_order_use_store_credit_service, :platform_order_remove_store_credit_service,@@ -68,6 +69,7 @@ module Spree@storefront_checkout_add_store_credit_service = Spree::Dependencies.checkout_add_store_credit_service@storefront_checkout_remove_store_credit_service = Spree::Dependencies.checkout_remove_store_credit_service@storefront_checkout_get_shipping_rates_service = Spree::Dependencies.checkout_get_shipping_rates_service+ @storefront_checkout_select_shipping_method_service = Spree::Dependencies.checkout_select_shipping_method_service# account services@storefront_account_create_service = Spree::Dependencies.account_create_servicediff --git a/api/spec/requests/spree/api/v2/storefront/checkout_spec.rb b/api/spec/requests/spree/api/v2/storefront/checkout_spec.rbindex 7135638f63..3a1c2cca33 100644--- a/api/spec/requests/spree/api/v2/storefront/checkout_spec.rb+++ b/api/spec/requests/spree/api/v2/storefront/checkout_spec.rb@@ -746,6 +746,77 @@ describe 'API V2 Storefront Checkout Spec', type: :request doendend+ describe 'checkout#select_shipping_method' do+ let(:headers) { headers_bearer }+ let(:params) do+ {+ shipping_method_id: shipping_method_2.id+ }+ end+ let(:zone) { create(:zone_with_country) }++ let(:country) { create(:country) }+ let(:order) { create(:order_with_totals, store: store, user: user, ship_address: create(:address, user: user, country: country)) }+ let(:shipping_category) { order.products.first.shipping_category }+ let!(:shipping_method) do+ create(:shipping_method, zones: [zone], shipping_categories: [shipping_category]) do |shipping_method|+ shipping_method.calculator.preferred_amount = 10+ shipping_method.calculator.save+ end+ end+ let!(:shipping_method_2) do+ create(:shipping_method, zones: [zone], shipping_categories: [shipping_category]) do |shipping_method|+ shipping_method.calculator.preferred_amount = 15+ shipping_method.calculator.save+ end+ end+ let!(:shipping_method_3) do+ create(:shipping_method, zones: [create(:zone)], shipping_categories: [shipping_category]) do |shipping_method|+ shipping_method.calculator.preferred_amount = 5+ shipping_method.calculator.save+ end+ end+ let(:shipment) { order.shipments.first }+ let(:selected_shipping_rate) { shipment.selected_shipping_rate }+ let(:execute) { patch '/api/v2/storefront/checkout/select_shipping_method?include=shipments', headers: headers, params: params }++ before do+ zone.countries << country+ # making sure our store is in the geo zone supported by shipping method+ store.update(checkout_zone: zone)+ # generate shipping rates+ get '/api/v2/storefront/checkout/shipping_rates', headers: headers+ end++ context 'one shipment' do+ context 'valid shipping method' do+ before { execute }++ it_behaves_like 'returns 200 HTTP status'++ it 'sets selected shipping method for shipment' do+ expect(json_response['included'][0]).to have_id(shipment.id.to_s)+ expect(json_response['included'][0]).to have_type('shipment')+ expect(selected_shipping_rate).to be_present+ expect(json_response['included'][0]).to have_relationship(:selected_shipping_rate).with_data({ 'id' => selected_shipping_rate.id.to_s, 'type' => 'shipping_rate' })+ expect(selected_shipping_rate.shipping_method).to eq(shipping_method_2)+ end+ end++ context 'missing shipping method' do+ let(:params) do+ {+ shipping_method_id: shipping_method_3.id+ }+ end++ before { execute }++ it_behaves_like 'returns 422 HTTP status'+ end+ end+ end+orders_requiring_delivery = ['order with a physical line item', 'order with a physical and digital line item'].freezeorders_requiring_delivery.each do |physical_goods_context|diff --git a/api/spec/swagger_helper.rb b/api/spec/swagger_helper.rbindex 88b3c15c99..705b186e2b 100644--- a/api/spec/swagger_helper.rb+++ b/api/spec/swagger_helper.rb@@ -19,13 +19,13 @@ RSpec.configure do |config|'v2/platform/index.yaml' => {openapi: '3.0.3',info: {- title: 'Platform API v2',+ title: 'Platform API',contact: {name: 'Spark Solutions',url: 'https://sparksolutions.co',email: '[email protected]',},- description: 'Spree Platform API v2',+ description: 'Spree Platform API',version: 'v2'},paths: {},diff --git a/core/app/services/spree/checkout/select_shipping_method.rb b/core/app/services/spree/checkout/select_shipping_method.rbnew file mode 100644index 0000000000..ce3fa41b73--- /dev/null+++ b/core/app/services/spree/checkout/select_shipping_method.rb@@ -0,0 +1,49 @@+module Spree+ module Checkout+ class SelectShippingMethod+ prepend Spree::ServiceModule::Base++ def call(order:, params:)+ if params[:shipment_id].present?+ shipment = order.shipments.valid.find_by(id: params[:shipment_id])+ return failure(:shipment_not_found) if shipment.nil?+ end++ shipping_method = Spree::ShippingMethod.find_by(id: params[:shipping_method_id])+ return failure(:shipping_method_not_found) if shipping_method.nil?++ # single shipment passed+ if shipment.present?+ result = set_shipping_rate_based_on_method(shipment: shipment, shipping_method: shipping_method)++ return failure(result.value, result.error) unless result.success?+ else+ # set shipping method for all shipments+ order.shipments.valid.each do |s|+ result = set_shipping_rate_based_on_method(shipment: s, shipping_method: shipping_method)++ return failure(result.value, result.error) unless result.success?+ end+ end++ success(order)+ end++ def set_shipping_rate_based_on_method(shipment:, shipping_method:)+ selected_shipping_rate = shipment.shipping_rates.find_by(shipping_method: shipping_method)++ if selected_shipping_rate.nil?+ return failure(+ :selected_shipping_method_not_found,+ "Couldn't find shipping rates for Shipping Method with ID = #{shipping_method.id} and Shipment with ID = #{shipment.id}"+ )+ end++ shipment.selected_shipping_rate_id = selected_shipping_rate.id+ shipment.update_amounts++ success(shipment)+ end+ end+ end+enddiff --git a/core/lib/spree/core/app_dependencies.rb b/core/lib/spree/core/app_dependencies.rbindex f3289c00ad..8d7dcb7660 100644--- a/core/lib/spree/core/app_dependencies.rb+++ b/core/lib/spree/core/app_dependencies.rb@@ -16,7 +16,8 @@ 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,- :payment_create_service, :address_create_service, :address_update_service+ :payment_create_service, :address_create_service, :address_update_service,+ :checkout_select_shipping_method_service].freezeattr_accessor *INJECTION_POINTS@@ -57,6 +58,7 @@ module Spree@checkout_add_store_credit_service = 'Spree::Checkout::AddStoreCredit'@checkout_remove_store_credit_service = 'Spree::Checkout::RemoveStoreCredit'@checkout_get_shipping_rates_service = 'Spree::Checkout::GetShippingRates'+ @checkout_select_shipping_method_service = 'Spree::Checkout::SelectShippingMethod'# order@order_approve_service = 'Spree::Orders::Approve'diff --git a/core/spec/services/spree/checkout/select_shipping_method_spec.rb b/core/spec/services/spree/checkout/select_shipping_method_spec.rbnew file mode 100644index 0000000000..dce99877f4--- /dev/null+++ b/core/spec/services/spree/checkout/select_shipping_method_spec.rb@@ -0,0 +1,123 @@+require 'spec_helper'++module Spree+ describe Checkout::SelectShippingMethod do+ subject { described_class }++ let(:country) { create(:country) }+ let(:store) { create(:store, checkout_zone: zone) }+ let(:order) { create(:order_with_totals, store: store, ship_address: create(:address, country: country)) }++ let(:execute) { subject.call(order: order, params: params) }+ let(:value) { execute.value }++ let(:params) do+ {+ shipping_method_id: shipping_method_2.id+ }+ end+ let(:zone) { create(:zone_with_country) }+ let(:shipping_category) { order.products.first.shipping_category }+ let!(:shipping_method) do+ create(:shipping_method, zones: [zone], shipping_categories: [shipping_category]) do |shipping_method|+ shipping_method.calculator.preferred_amount = 10+ shipping_method.calculator.save+ end+ end+ let!(:shipping_method_2) do+ create(:shipping_method, zones: [zone], shipping_categories: [shipping_category]) do |shipping_method|+ shipping_method.calculator.preferred_amount = 15+ shipping_method.calculator.save+ end+ end+ let!(:shipping_method_3) do+ create(:shipping_method, zones: [create(:zone)], shipping_categories: [shipping_category]) do |shipping_method|+ shipping_method.calculator.preferred_amount = 5+ shipping_method.calculator.save+ end+ end+ let(:shipment) { order.shipments.last }+ let(:selected_shipping_rate) { shipment.selected_shipping_rate }++ before do+ zone.countries << country+ end++ context 'one shipment' do+ before do+ Spree::Checkout::GetShippingRates.call(order: order)+ order.reload+ end++ context 'valid shipping method' do+ it { expect(execute.success?).to eq(true) }+ it { expect(execute.value).to be_kind_of(Spree::Order) }+ it { expect(execute.value.id).to eq(order.id) }++ it 'sets selected shipping method for shipment' do+ expect(shipment.shipping_rates.count).to eq(2)+ execute+ expect(selected_shipping_rate.shipping_method).to eq(shipping_method_2)+ end+ end++ context 'missing shipping method' do+ let(:params) do+ {+ shipping_method_id: shipping_method_3.id+ }+ end++ it { expect(execute.success?).to eq(false) }+ it { expect(execute.value).to eq(:selected_shipping_method_not_found) }+ it { expect(execute.error.to_s).to match(/Couldn't find shipping rate/) }+ end+ end++ context 'multiple shipments' do+ let(:product_2) { create(:product_in_stock, shipping_category: shipping_category) }+ let!(:line_item) { create(:line_item, variant: product_2.master, order: order) }++ let(:shipment) { order.shipments.first }+ let(:shipment_2) { order.shipments.last }++ before do+ Spree::Checkout::GetShippingRates.call(order: order)+ order.reload+ end++ context 'update selected shipment' do+ let(:params) do+ {+ shipment_id: shipment_2.id,+ shipping_method_id: shipping_method_2.id+ }+ end++ it { expect(execute.success?).to eq(true) }++ it 'sets selected shipping method for the specified shipment' do+ expect(order.shipments.count).to eq(2)+ expect(shipment.selected_shipping_rate.shipping_method).to eq(shipping_method)+ expect(shipment_2.selected_shipping_rate.shipping_method).to eq(shipping_method)+ execute+ expect(shipment.reload.selected_shipping_rate.shipping_method).to eq(shipping_method)+ expect(shipment_2.reload.selected_shipping_rate.shipping_method).to eq(shipping_method_2)+ end+ end++ context 'update all shipments' do+ it { expect(execute.success?).to eq(true) }++ it 'sets selected shipping method for all shipments' do+ expect(order.shipments.count).to eq(2)+ expect(shipment.selected_shipping_rate.shipping_method).to eq(shipping_method)+ expect(shipment_2.selected_shipping_rate.shipping_method).to eq(shipping_method)+ execute+ expect(shipment.reload.selected_shipping_rate.shipping_method).to eq(shipping_method_2)+ expect(shipment_2.reload.selected_shipping_rate.shipping_method).to eq(shipping_method_2)+ end+ end+ end+ end+end