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
Simplify the Api::V3::Orders::Update service
Damian Legawiecbbe665064688
diff --git a/api/app/services/spree/api/v3/orders/update.rb b/api/app/services/spree/api/v3/orders/update.rbindex d81e55d8e1..d71789c426 100644--- a/api/app/services/spree/api/v3/orders/update.rb+++ b/api/app/services/spree/api/v3/orders/update.rb@@ -24,34 +24,17 @@ module Spree# }# )#- # @example Change currency- # Spree::Api::V3::Orders::Update.call(- # order: order,- # params: { currency: "EUR" }- # )class Updateprepend Spree::ServiceModule::Base- include Spree::Addresses::Helper-- PERMITTED_ORDER_PARAMS = %i[- special_instructions- currency- bill_address_id- ship_address_id- ].freezedef call(order:, params:)@order = order@params = params.to_h.deep_symbolize_keys- return failure(order, validation_error) if validation_error.present?-ApplicationRecord.transaction do- update_currency if @params[:currency].present?- update_order_attributes- update_address(:ship_address)- update_address(:bill_address)+ assign_order_attributes+ assign_address(:ship_address)+ assign_address(:bill_address)order.save!end@@ -67,61 +50,20 @@ module Spreeattr_reader :order, :params- def validation_error- @validation_error ||= begin- error = validate_address_ownership(:ship_address)- error ||= validate_address_ownership(:bill_address)- error- end- end-- def validate_address_ownership(address_type)- # Check nested address params (ship_address: { id: ... })- address_params = params[address_type]- if address_params.is_a?(Hash) && address_params[:id].present?- return ownership_error_for(address_params[:id])- end-- # Check top-level address ID (ship_address_id: ...)- address_id = params[:"#{address_type}_id"]- if address_id.present?- return ownership_error_for(address_id)- end-- nil- end-- def ownership_error_for(address_id)- address = Spree::Address.find_by_prefix_id(address_id)- return nil unless address-- # Allow if address has no user (guest address) or belongs to the order's user- return nil if address.user_id.nil?- return nil if order.user_id.present? && address.user_id == order.user_id-- Spree.t(:address_not_owned_by_user)- end-- def update_currency- new_currency = params[:currency].upcase- return if order.currency == new_currency-- order.currency = new_currency- order.homogenize_line_item_currencies- end-- def update_order_attributes+ def assign_order_attributesorder.email = params[:email] if params[:email].present?- order.special_instructions = params[:special_instructions] if params[:special_instructions].present?+ order.special_instructions = params[:special_instructions] if params.key?(:special_instructions)+ order.currency = params[:currency].upcase if params[:currency].present?end- def update_address(address_type)+ def assign_address(address_type)address_id_param = params[:"#{address_type}_id"]address_params = params[address_type]# Priority 1: Direct address ID reference (ship_address_id / bill_address_id)if address_id_param.present?- assign_existing_address(address_type, address_id_param)+ address_id = resolve_address_id(address_id_param)+ order.public_send(:"#{address_type}_id=", address_id) if address_idreturnend@@ -130,52 +72,26 @@ module Spreeif address_params[:id].present?# Using existing address by ID within nested params- assign_existing_address(address_type, address_params[:id])+ address_id = resolve_address_id(address_params[:id])+ order.public_send(:"#{address_type}_id=", address_id) if address_idelse# Creating/updating address with provided attributes- build_address(address_type, address_params)+ revert_to_address_state if order.has_checkout_step?('address')+ order.public_send(:"#{address_type}_attributes=", address_params)endend- def assign_existing_address(address_type, prefix_id)- existing = Spree::Address.find_by_prefix_id!(prefix_id)- # Use bracket notation to bypass Order::AddressBook custom setter- # which requires address.user_id == order.user_id- order[:"#{address_type}_id"] = existing.id- end-- def build_address(address_type, address_params)- normalized = normalize_address_params(address_params)- revert_to_address_state if order.has_checkout_step?('address')+ # Translate prefix_id to internal id+ def resolve_address_id(prefix_id)+ return unless order.user- existing_address = order.public_send(address_type)- new_address = build_or_update_address(existing_address, normalized)- order.public_send(:"#{address_type}=", new_address)- end-- def normalize_address_params(address_params)- permitted_keys = Spree::PermittedAttributes.address_attributes.select { |attr| attr.is_a?(Symbol) }- # Also permit state_abbr which is handled by the helper but not in permitted attributes- permitted_keys += [:state_abbr]-- normalized = address_params.slice(*permitted_keys)- fill_country_and_state_ids(normalized)- normalized- end-- def build_or_update_address(existing_address, address_params)- if existing_address.present? && existing_address.editable?- existing_address.assign_attributes(address_params.except(:id))- existing_address- else- Spree::Address.new(address_params.except(:id).merge(user: order.user))- end+ order.user.addresses.find_by(prefix_id: prefix_id)&.idend# Revert order state to 'address' when address changes# This ensures shipments are recreated when transitioning back to deliverydef revert_to_address_state- return if order.state == 'cart' || order.state == 'address'+ return if ['cart', 'address'].include?(order.state)order.state = 'address'enddiff --git a/api/spec/services/spree/api/v3/orders/update_spec.rb b/api/spec/services/spree/api/v3/orders/update_spec.rbindex b62a314331..a9a6e93b26 100644--- a/api/spec/services/spree/api/v3/orders/update_spec.rb+++ b/api/spec/services/spree/api/v3/orders/update_spec.rb@@ -24,6 +24,22 @@ RSpec.describe Spree::Api::V3::Orders::Update doexpect(subject).to be_successexpect(order.reload.special_instructions).to eq('Leave at the door')end++ context 'when clearing special_instructions' do+ let(:order) { create(:order_with_line_items, user: user, store: store, special_instructions: 'Existing instructions') }++ it 'clears with empty string' do+ result = described_class.call(order: order, params: { special_instructions: '' })+ expect(result).to be_success+ expect(order.reload.special_instructions).to eq('')+ end++ it 'clears with nil' do+ result = described_class.call(order: order, params: { special_instructions: nil })+ expect(result).to be_success+ expect(order.reload.special_instructions).to be_nil+ end+ endenddescribe 'updating currency' do@@ -141,40 +157,45 @@ RSpec.describe Spree::Api::V3::Orders::Update doendend- describe 'address ownership validation' do+ describe 'address ownership' dolet(:other_user) { create(:user) }let(:other_users_address) { create(:address, user: other_user) }- shared_examples 'rejects other users address' do |address_type|+ shared_examples 'ignores other users address' do |address_type|context "when using another user's address for #{address_type}" dolet(:params) { { address_type => { id: other_users_address.prefix_id } } }- it 'returns failure' do- expect(subject).to be_failure- expect(subject.error).to be_present+ it 'ignores the address and keeps original' do+ original_address_id = order.public_send(:"#{address_type}_id")+ expect(subject).to be_success+ expect(order.reload.public_send(:"#{address_type}_id")).to eq(original_address_id)+ expect(order.public_send(:"#{address_type}_id")).not_to eq(other_users_address.id)endendcontext "when using another user's address via #{address_type}_id" dolet(:params) { { :"#{address_type}_id" => other_users_address.prefix_id } }- it 'returns failure' do- expect(subject).to be_failure- expect(subject.error).to be_present+ it 'ignores the address and keeps original' do+ original_address_id = order.public_send(:"#{address_type}_id")+ expect(subject).to be_success+ expect(order.reload.public_send(:"#{address_type}_id")).to eq(original_address_id)+ expect(order.public_send(:"#{address_type}_id")).not_to eq(other_users_address.id)endendend- include_examples 'rejects other users address', :ship_address- include_examples 'rejects other users address', :bill_address+ include_examples 'ignores other users address', :ship_address+ include_examples 'ignores other users address', :bill_address- context 'when using guest address (no user)' do- let(:guest_address) { create(:address, user: nil) }- let(:params) { { ship_address_id: guest_address.prefix_id } }+ context 'when order has no user (guest order)' do+ let(:order) { create(:order_with_line_items, user: nil, store: store) }+ let(:params) { { ship_address_id: other_users_address.prefix_id } }- it 'allows using the address' do+ it 'ignores address_id params and keeps existing address' do+ original_address_id = order.ship_address_idexpect(subject).to be_success- expect(order.reload.ship_address_id).to eq(guest_address.id)+ expect(order.reload.ship_address_id).to eq(original_address_id)endendend@@ -212,8 +233,10 @@ RSpec.describe Spree::Api::V3::Orders::Update docontext 'with invalid address prefix_id' dolet(:params) { { ship_address_id: 'addr_invalid123' } }- it 'returns failure' do- expect(subject).to be_failure+ it 'succeeds but does not change the address' do+ original_address_id = order.ship_address_id+ expect(subject).to be_success+ expect(order.reload.ship_address_id).to eq(original_address_id)endenddiff --git a/core/app/models/spree/address.rb b/core/app/models/spree/address.rbindex eb449c26f9..9bfb3eb6a0 100644--- a/core/app/models/spree/address.rb+++ b/core/app/models/spree/address.rb@@ -50,6 +50,8 @@ module Spreeafter_initialize :set_default_values, if: -> { new_record? && user.present? }+ before_validation :normalize_country+ before_validation :normalize_statebefore_validation :clear_invalid_state_entities, if: -> { country.present? }, on: :updatebefore_validation :remove_emoji_and_normalize@@ -85,6 +87,16 @@ module Spreealias_attribute :postal_code, :zipcode+ # Writer methods for API convenience - these set country/state from ISO/abbr codes+ # The reader methods (country_iso, state_abbr) are delegates to country.iso and state.abbr+ def country_iso=(value)+ @country_iso_input = value+ end++ def state_abbr=(value)+ @state_abbr_input = value+ end+self.whitelisted_ransackable_attributes = ADDRESS_FIELDSself.whitelisted_ransackable_associations = %w[country state user]@@ -249,6 +261,22 @@ module Spreeself.phone ||= user.phoneend+ def normalize_country+ iso = @country_iso_input+ return if iso.blank?++ self.country = Spree::Country.by_iso(iso)+ @country_iso_input = nil+ end++ def normalize_state+ abbr = @state_abbr_input+ return if abbr.blank? || country.blank?++ self.state = country.states.find_by(abbr: abbr)+ @state_abbr_input = nil+ end+def clear_stateself.state = nilenddiff --git a/core/app/models/spree/order/address_book.rb b/core/app/models/spree/order/address_book.rbindex d95107ece9..577c503624 100644--- a/core/app/models/spree/order/address_book.rb+++ b/core/app/models/spree/order/address_book.rb@@ -79,7 +79,8 @@ module Spreeenddef find_existing_address(attributes)- address_attributes = attributes.except(:state_name)+ # Exclude virtual attributes that are handled by Address model callbacks+ address_attributes = attributes.except(:state_name, :country_iso, :state_abbr)state_name = attributes[:state_name]scope = Spree::Address.not_deleted.where(address_attributes)diff --git a/core/lib/spree/permitted_attributes.rb b/core/lib/spree/permitted_attributes.rbindex 3862e8fdf6..4aceb4264f 100644--- a/core/lib/spree/permitted_attributes.rb+++ b/core/lib/spree/permitted_attributes.rb@@ -81,7 +81,7 @@ module Spree@@address_attributes = [:id, :firstname, :lastname, :first_name, :last_name,- :address1, :address2, :city, :country_iso, :country_id, :state_id,+ :address1, :address2, :city, :country_iso, :state_abbr, :country_id, :state_id,:zipcode, :phone, :state_name, :alternative_phone, :company,:user_id, :deleted_at, :label, :quick_checkout,{ country: [:iso, :name, :iso3, :iso_name],diff --git a/core/spec/models/spree/address_spec.rb b/core/spec/models/spree/address_spec.rbindex ecfbcaa9ca..5a8bf5bec6 100644--- a/core/spec/models/spree/address_spec.rb+++ b/core/spec/models/spree/address_spec.rb@@ -729,7 +729,7 @@ describe Spree::Address, type: :model doexpect(address.require_phone?).to be(true)endend-+context 'and Spree::Config[:address_requires_phone] is false' dobefore { Spree::Config[:address_requires_phone] = false }@@ -739,4 +739,125 @@ describe Spree::Address, type: :model doendendend++ describe 'country_iso= and state_abbr= writer methods' do+ let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }+ let!(:state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }++ describe '#country_iso=' do+ it 'sets country from ISO code on validation' do+ address = build(:address, country: nil)+ address.country_iso = 'US'+ address.valid?+ expect(address.country).to eq(country)+ end++ it 'is case-insensitive' do+ address = build(:address, country: nil)+ address.country_iso = 'us'+ address.valid?+ expect(address.country).to eq(country)+ end++ it 'does nothing when ISO is blank' do+ original_country = create(:country)+ address = build(:address, country: original_country)+ address.country_iso = ''+ address.valid?+ expect(address.country).to eq(original_country)+ end++ it 'sets country to nil when ISO is not found' do+ address = build(:address, country: nil)+ address.country_iso = 'XX'+ address.valid?+ expect(address.country).to be_nil+ end++ it 'clears the input after normalization' do+ address = build(:address, country: nil)+ address.country_iso = 'US'+ address.valid?+ # The input should be cleared so it doesn't re-run on next validation+ address.valid?+ expect(address.country).to eq(country)+ end+ end++ describe '#state_abbr=' do+ it 'sets state from abbreviation on validation' do+ address = build(:address, country: country, state: nil)+ address.state_abbr = 'NY'+ address.valid?+ expect(address.state).to eq(state)+ end++ it 'requires country to be set first' do+ address = build(:address, country: nil, state: nil)+ address.state_abbr = 'NY'+ address.valid?+ expect(address.state).to be_nil+ end++ it 'does nothing when abbreviation is blank' do+ address = build(:address, country: country, state: nil)+ address.state_abbr = ''+ address.valid?+ expect(address.state).to be_nil+ end++ it 'sets state to nil when abbreviation is not found for country' do+ address = build(:address, country: country, state: nil)+ address.state_abbr = 'XX'+ address.valid?+ expect(address.state).to be_nil+ end++ it 'only finds states belonging to the address country' do+ other_country = create(:country, iso: 'CA')+ other_state = create(:state, country: other_country, abbr: 'NY', name: 'Not York')++ address = build(:address, country: country, state: nil)+ address.state_abbr = 'NY'+ address.valid?+ expect(address.state).to eq(state)+ expect(address.state).not_to eq(other_state)+ end+ end++ describe 'combined country_iso and state_abbr' do+ it 'sets both country and state when both are provided' do+ address = build(:address, country: nil, state: nil)+ address.country_iso = 'US'+ address.state_abbr = 'NY'+ address.valid?+ expect(address.country).to eq(country)+ expect(address.state).to eq(state)+ end++ it 'works with new address creation' do+ address = Spree::Address.new(+ firstname: 'John',+ lastname: 'Doe',+ address1: '123 Main St',+ city: 'New York',+ zipcode: '10001',+ phone: '555-1234',+ country_iso: 'US',+ state_abbr: 'NY'+ )+ expect(address).to be_valid+ expect(address.country).to eq(country)+ expect(address.state).to eq(state)+ end++ it 'works with address update via assign_attributes' do+ address = create(:address)+ address.assign_attributes(country_iso: 'US', state_abbr: 'NY')+ address.valid?+ expect(address.country).to eq(country)+ expect(address.state).to eq(state)+ end+ end+ endend