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
Share the items-payload parsing instead of copying it
Łukasz Adamczyk6bc23d84e350
diff --git a/packages/dashboard/src/components/spree/stock-history-card.tsx b/packages/dashboard/src/components/spree/stock-history-card.tsxindex 385521d898..c56c77195e 100644--- a/packages/dashboard/src/components/spree/stock-history-card.tsx+++ b/packages/dashboard/src/components/spree/stock-history-card.tsx@@ -121,14 +121,10 @@ export function StockHistoryCard({* merchant's correction had.*/function QuantityChange({ movement }: { movement: StockMovement }) {- const leaves = movement.kind === 'shipped'- const magnitude = Math.abs(movement.quantity)- const signed =- movement.kind === 'adjusted' && movement.quantity < 0- ? -magnitude- : leaves- ? -magnitude- : magnitude+ // Only `shipped` needs flipping: it is stored positive and means a+ // departure. `adjusted` already carries the sign the merchant entered, and+ // every other kind is an addition.+ const signed = movement.kind === 'shipped' ? -Math.abs(movement.quantity) : movement.quantityreturn (<span className={signed < 0 ? 'text-danger' : 'text-success'}>diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rbindex fd1c685e93..ed780e174a 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/receivable_actions.rb@@ -15,15 +15,7 @@ module Spree# evidence of whose record it is.module ReceivableActionsextend ActiveSupport::Concern-- # A payload whose `items` is not a list. Raised out of the params- # helper so it cannot be mistaken for a workflow rejection, and- # answered as the client mistake it is rather than a 500.- class InvalidItems < StandardError; end-- included do- rescue_from InvalidItems, with: :render_invalid_items- end+ include Spree::Api::V3::ItemsPayloadprotected@@ -102,29 +94,13 @@ module Spreecurrent_store.variants.accessible_by(current_ability, :show)end- def render_invalid_items- errors = ActiveModel::Errors.new(@resource || model_class.new)- errors.add(:items, :invalid)- render_validation_error(errors)- end-private# Raw `params`, not `permitted_params`: the latter decodes anything# shaped like a prefixed id into a primary key, and these lines are# looked up by prefixed id precisely so their scope is checked.- #- # The list-ness is checked before `permit`, which silently drops a- # scalar `items` — leaving a client typo indistinguishable from "no- # lines named", and answering 201 to a payload nobody meant.def sent_items(keys)- return nil unless params.key?(:items)-- raw = params[:items]- return [] if raw.nil?- raise InvalidItems unless raw.is_a?(Array)-- params.permit(items: keys)[:items] || []+ items_payload(keys)endendenddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/items_payload.rb b/spree/api/app/controllers/concerns/spree/api/v3/items_payload.rbnew file mode 100644index 0000000000..83152feb9e--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/items_payload.rb@@ -0,0 +1,54 @@+module Spree+ module Api+ module V3+ # The `items` list a request names, for the endpoints that take one:+ # receiving a return, an exchange, a claim, a stock transfer or a+ # purchase order, and opening any of them.+ #+ # The distinction all of them need is between *omitted* and *empty*. An+ # omitted `items` means "all of it, as recorded" — receive the whole+ # return, the whole delivery. An empty list, or an explicit `null`, means+ # the caller named nothing, and must not fall through to that default.+ module ItemsPayload+ extend ActiveSupport::Concern++ # A payload whose `items` is not a list. Raised out of the params+ # helper so it cannot be mistaken for a workflow rejection, and+ # answered as the client mistake it is rather than a 500.+ class InvalidItems < StandardError; end++ included do+ rescue_from InvalidItems, with: :render_invalid_items+ end++ protected++ # @param keys [Array<Symbol>] the per-item keys to permit+ # @return [Array<ActionController::Parameters>, nil] nil when the+ # payload said nothing about items+ def items_payload(keys)+ return nil unless params.key?(:items)++ raw = params[:items]+ return [] if raw.nil?+ # Checked before `permit`, which silently drops a scalar `items` —+ # leaving a client typo indistinguishable from "named nothing".+ raise InvalidItems unless raw.is_a?(Array)++ params.permit(items: keys)[:items] || []+ end++ # Reported against `:base`, not `:items`. The payload is malformed+ # rather than a field being wrong, and ActiveModel reads the named+ # attribute off the record to interpolate a message — which raises for+ # every record whose lines are not called `items` (a return's are+ # `return_line_items`).+ def render_invalid_items+ errors = ActiveModel::Errors.new(@resource || model_class.new)+ errors.add(:base, :invalid_items, message: Spree.t('errors.messages.items_not_a_list'))+ render_validation_error(errors)+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rbindex 9d07e36d2b..a4de82243c 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb@@ -16,15 +16,7 @@ module Spree# the other — and this code never learns which.module PostSaleActionsextend ActiveSupport::Concern-- # A payload whose `items` is not a list. Raised out of the params- # helper so it cannot be mistaken for a workflow rejection, and- # answered as the client mistake it is rather than a 500.- class InvalidItems < StandardError; end-- included do- rescue_from InvalidItems, with: :render_invalid_items- end+ include Spree::Api::V3::ItemsPayloadprotected@@ -48,31 +40,13 @@ module Spreeraise NotImplementedError, "#{self.class} must implement #workflow_record_key"end- def render_invalid_items- errors = ActiveModel::Errors.new(@resource || model_class.new)- errors.add(:items, :invalid)- render_validation_error(errors)- end-# The units a receive request named, or nil when it named none.- #- # An omitted `items` means "receive it all as requested". Naming an- # empty list — or an explicit `null`, which is the same statement —- # means the caller named no units, and must not fall through to- # receive-all. Anything else that is not a list is refused rather- # than iterated, which would answer a 500 to a client mistake.+ # See {Spree::Api::V3::ItemsPayload} for what omitted and empty mean.## @param keys [Array<Symbol>] the per-item keys to permit# @return [Array<ActionController::Parameters>, nil]def received_items(keys)- return nil unless params.key?(:items)-- sent = params.permit(items: keys)[:items]- return [] if sent.nil?-- raise InvalidItems unless sent.respond_to?(:map) && !sent.is_a?(Hash)-- sent+ items_payload(keys)end# Opens the record against the order, through the entity's creatediff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rbindex 142edde87c..777d9dd3a1 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb@@ -129,12 +129,23 @@ RSpec.describe Spree::Api::V3::Admin::Orders::ReturnsController, type: :controllexpect(line.reload.received_quantity).to eq(0)end- it 'refuses an item list that is not a list' do- patch :receive, params: {- order_id: order.prefixed_id, id: return_record.prefixed_id, items: 'everything'- }, as: :json-- expect(response).to have_http_status(:unprocessable_content)+ # The refusal has to be the payload's own: an `items` the caller got wrong+ # must not be reported as "you named no units", and an object shape used to+ # answer a 500, because the message named an attribute a return has not got.+ [['a bare string', 'everything'], ['an object', { return_line_item_id: 'x' }]].each do |shape, items|+ it "refuses an item list that is #{shape}" do+ line = return_record.return_line_items.first++ patch :receive, params: {+ order_id: order.prefixed_id, id: return_record.prefixed_id, items: items+ }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['details']['base']).to include(+ hash_including('code' => 'invalid_items')+ )+ expect(line.reload.received_quantity).to eq(0)+ endendit 'records a partial, non-resellable receipt' dodiff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rbindex d8a18aaf78..ce8617cb99 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_transfers_controller_spec.rb@@ -140,10 +140,17 @@ RSpec.describe Spree::Api::V3::Admin::StockTransfersController, type: :controlleexpect(response).to have_http_status(:not_found)end- it 'refuses a payload whose items is not a list' do- post :create, params: base_params.merge(items: 'five'), as: :json-- expect(response).to have_http_status(:unprocessable_content)+ [['a bare string', 'five'], ['an object', { variant_id: 'x', quantity_shipped: 1 }]].each do |shape, items|+ it "refuses a payload whose items is #{shape}" do+ expect do+ post :create, params: base_params.merge(items: items), as: :json+ end.not_to change(Spree::StockTransfer, :count)++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['details']['base']).to include(+ hash_including('code' => 'invalid_items')+ )+ endendend@@ -234,6 +241,22 @@ RSpec.describe Spree::Api::V3::Admin::StockTransfersController, type: :controlleexpect(destination_location.stock_level(variant.id).reload.count_on_hand).to eq(10)end+ # An `items` the caller got wrong must not fall through to receive-all.+ it 'refuses a receive whose items is an object rather than a list' do+ patch :mark_in_transit, params: { id: transfer.prefixed_id }, as: :json++ patch :receive, params: {+ id: transfer.prefixed_id, items: { id: 'x', quantity_received: 1 }+ }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['details']['base']).to include(+ hash_including('code' => 'invalid_items')+ )+ expect(transfer.reload.status).to eq('in_transit')+ expect(transfer.quantity_received_total).to eq(0)+ end+it "returns 404 for a line belonging to another transfer" dopatch :mark_in_transit, params: { id: transfer.prefixed_id }, as: :jsonforeign_item = create_draft.items.solediff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex daf62ba9a7..f7e146d41f 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1075,6 +1075,7 @@ en:invalid_refund_method: must be one of original_payment, store_creditinvalid_seller_requirement: is not a registered seller requirementinvalid_storefront_access: is not a valid storefront access level+ items_not_a_list: items must be a list of objectsmust_be_greater_than_min_amount: must be greater than or equal to the minimummust_be_origin_only: must be an origin (scheme and host) without path, query, or fragmentno_pickup_point_provider: this delivery method has no pickup point provider configured