Skip to content

armgit / spree

Public Imported from GitHub
0

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.

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.rb
index 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 Update
prepend Spree::ServiceModule::Base
- include Spree::Addresses::Helper
-
- PERMITTED_ORDER_PARAMS = %i[
- email
- special_instructions
- currency
- bill_address_id
- ship_address_id
- ].freeze
def 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 Spree
attr_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_attributes
order.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_id
return
end
@@ -130,52 +72,26 @@ module Spree
if 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_id
else
# 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)
end
end
- 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)&.id
end
# Revert order state to 'address' when address changes
# This ensures shipments are recreated when transitioning back to delivery
def revert_to_address_state
- return if order.state == 'cart' || order.state == 'address'
+ return if ['cart', 'address'].include?(order.state)
order.state = 'address'
end
diff --git a/api/spec/services/spree/api/v3/orders/update_spec.rb b/api/spec/services/spree/api/v3/orders/update_spec.rb
index 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 do
expect(subject).to be_success
expect(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
+ end
end
describe 'updating currency' do
@@ -141,40 +157,45 @@ RSpec.describe Spree::Api::V3::Orders::Update do
end
end
- describe 'address ownership validation' do
+ describe 'address ownership' do
let(: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}" do
let(: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)
end
end
context "when using another user's address via #{address_type}_id" do
let(: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)
end
end
end
- 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_id
expect(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)
end
end
end
@@ -212,8 +233,10 @@ RSpec.describe Spree::Api::V3::Orders::Update do
context 'with invalid address prefix_id' do
let(: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)
end
end
diff --git a/core/app/models/spree/address.rb b/core/app/models/spree/address.rb
index eb449c26f9..9bfb3eb6a0 100644
--- a/core/app/models/spree/address.rb
+++ b/core/app/models/spree/address.rb
@@ -50,6 +50,8 @@ module Spree
after_initialize :set_default_values, if: -> { new_record? && user.present? }
+ before_validation :normalize_country
+ before_validation :normalize_state
before_validation :clear_invalid_state_entities, if: -> { country.present? }, on: :update
before_validation :remove_emoji_and_normalize
@@ -85,6 +87,16 @@ module Spree
alias_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_FIELDS
self.whitelisted_ransackable_associations = %w[country state user]
@@ -249,6 +261,22 @@ module Spree
self.phone ||= user.phone
end
+ 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_state
self.state = nil
end
diff --git a/core/app/models/spree/order/address_book.rb b/core/app/models/spree/order/address_book.rb
index 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 Spree
end
def 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.rb
index 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.rb
index 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 do
expect(address.require_phone?).to be(true)
end
end
-
+
context 'and Spree::Config[:address_requires_phone] is false' do
before { Spree::Config[:address_requires_phone] = false }
@@ -739,4 +739,125 @@ describe Spree::Address, type: :model do
end
end
end
+
+ 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
+ end
end