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
Make some improvements to address book (#12187)
Łukasz Adamczykbc012a9cab34
diff --git a/api/spec/controllers/spree/api/v2/storefront/account/addresses_controller_spec.rb b/api/spec/controllers/spree/api/v2/storefront/account/addresses_controller_spec.rbindex bc91f0f74d..13fb643168 100644--- a/api/spec/controllers/spree/api/v2/storefront/account/addresses_controller_spec.rb+++ b/api/spec/controllers/spree/api/v2/storefront/account/addresses_controller_spec.rb@@ -154,7 +154,7 @@ describe 'Spree::Api::V2::Storefront::Account::AddressesController', type: :requendcontext 'when address is not editable' do- let!(:shipment) { create(:shipment, address: address) }+ let!(:complete_order) { create(:completed_order_with_totals, ship_address: address) }context 'valid request' dolet(:new_attributes) dodiff --git a/core/app/models/spree/address.rb b/core/app/models/spree/address.rbindex 34f440e7d5..d78272c7c8 100644--- a/core/app/models/spree/address.rb+++ b/core/app/models/spree/address.rb@@ -33,13 +33,17 @@ module Spree# we're not freezing this on purpose so developers can extend and manage# those attributes depending of the logic of their applicationsADDRESS_FIELDS = %w(firstname lastname company address1 address2 city state zipcode country phone)- EXCLUDED_KEYS_FOR_COMPARISON = %w(id updated_at created_at deleted_at label user_id)+ EXCLUDED_KEYS_FOR_COMPARISON = %w(id updated_at created_at deleted_at label user_id public_metadata private_metadata)scope :not_deleted, -> { where(deleted_at: nil) }+ scope :by_state_name_or_abbr, lambda { |state_name|+ joins(:state).merge(Spree::State.where(name: state_name).or(Spree::State.where(abbr: state_name)))+ }+belongs_to :country, class_name: 'Spree::Country'belongs_to :state, class_name: 'Spree::State', optional: true- belongs_to :user, class_name: "::#{Spree.user_class}", optional: true+ belongs_to :user, class_name: Spree.user_class.name, optional: true, touch: truehas_many :shipments, inverse_of: :address@@ -66,6 +70,7 @@ module Spreealias_attribute :first_name, :firstnamealias_attribute :last_name, :lastname+ alias_attribute :postal_code, :zipcodeself.whitelisted_ransackable_attributes = ADDRESS_FIELDSself.whitelisted_ransackable_associations = %w[country state user]@@ -88,6 +93,10 @@ module Spreestate_name.present? ? state_name : state&.nameend+ def street+ [address1, address2].join(' ')+ end+def to_s[full_name,@@ -148,11 +157,11 @@ module Spreeenddef editable?- new_record? || (shipments.empty? && !Order.complete.where('bill_address_id = ? OR ship_address_id = ?', id, id).exists?)+ new_record? || Order.complete.where('bill_address_id = ? OR ship_address_id = ?', id, id).none?enddef can_be_deleted?- shipments.empty? && !Order.complete.where('bill_address_id = ? OR ship_address_id = ?', id, id).exists?+ shipments.empty? && Order.complete.where('bill_address_id = ? OR ship_address_id = ?', id, id).none?enddef check@@ -162,11 +171,12 @@ module Spreeenddef destroy+ assign_new_default_address_to_user+if can_be_deleted?superelseupdate_column :deleted_at, Time.current- assign_new_default_address_to_userendend@@ -206,16 +216,14 @@ module Spreeend# ensure state_name belongs to country without states, or that it matches a predefined state name/abbr- if state_name.present?- if country.states.present?- states = country.states.find_all_by_name_or_abbr(state_name)-- if states.size == 1- self.state = states.first- clear_state_name- else- errors.add(:state, :invalid)- end+ if state_name.present? && country.states.present?+ states = country.states.find_all_by_name_or_abbr(state_name)++ if states.size == 1+ self.state = states.first+ clear_state_name+ else+ errors.add(:state, :invalid)endend@@ -238,8 +246,16 @@ module Spreedef assign_new_default_address_to_userreturn unless user- user.bill_address = user.addresses.last if user.bill_address == self- user.ship_address = user.addresses.last if user.ship_address == self+ user.reload+ return if user.bill_address != self && user.ship_address != self++ last_address = user.+ addresses.+ reorder(created_at: :desc).+ find { |address| address.id != id && address.valid? }++ user.bill_address = last_address if user.bill_address == self+ user.ship_address = last_address if user.ship_address == selfuser.save!endenddiff --git a/core/app/models/spree/order/address_book.rb b/core/app/models/spree/order/address_book.rbindex 7aaa6444cb..dfd9ac604c 100644--- a/core/app/models/spree/order/address_book.rb+++ b/core/app/models/spree/order/address_book.rb@@ -1,20 +1,13 @@-# https://github.com/spree-contrib/spree_address_book/blob/master/app/models/spree/order_decorator.rbmodule Spreeclass Order < Spree::Basemodule AddressBook- extend ActiveSupport::Concern # FIXME: this module is not required to be a concern-def clone_shipping_address- if ship_address- self.bill_address = ship_address- end+ self.bill_address_id = ship_address_id if ship_address_idtrueenddef clone_billing_address- if bill_address- self.ship_address = bill_address- end+ self.ship_address_id = bill_address_id if bill_address_idtrueend@@ -30,7 +23,12 @@ module Spreedef bill_address_attributes=(attributes)self.bill_address = update_or_create_address(attributes)- user.bill_address = bill_address if user && user.bill_address.nil?++ if should_assign_user_default_address?(bill_address)+ user_old_address = user&.bill_address+ user_old_address&.delete unless user_old_address&.valid?+ user&.update(bill_address: bill_address)+ endenddef ship_address_id=(id)@@ -45,7 +43,12 @@ module Spreedef ship_address_attributes=(attributes)self.ship_address = update_or_create_address(attributes)- user.ship_address = ship_address if user && user.ship_address.nil?++ if should_assign_user_default_address?(ship_address)+ user_old_address = user&.ship_address+ user_old_address&.delete unless user_old_address&.valid?+ user&.update(ship_address: ship_address)+ endendprivate@@ -53,10 +56,10 @@ module Spreedef update_or_create_address(attributes = {})return if attributes.blank?- attributes.transform_values! { |v| v == '' ? nil : v }+ attributes.transform_values!(&:presence)attributes = attributes.to_h.symbolize_keys- default_address_scope = user ? user.addresses : ::Spree::Address+ default_address_scope = user ? user.addresses : ::Spree::Address.where(user_id: nil)default_address = default_address_scope.find_by(id: attributes[:id])if default_address&.editable?@@ -65,7 +68,26 @@ module Spreereturn default_addressend- ::Spree::Address.find_or_create_by(attributes.except(:id, :updated_at, :created_at))+ attributes = attributes.except(:id, :updated_at, :created_at)+ attributes[:user_id] = user&.id++ existing_address = find_existing_address(attributes)+ return existing_address if existing_address++ ::Spree::Address.create(attributes)+ end++ def find_existing_address(attributes)+ address_attributes = attributes.except(:firstname, :state_name)+ state_name = attributes[:state_name]++ scope = Spree::Address.not_deleted.where(address_attributes)+ scope = scope.by_state_name_or_abbr(state_name) if state_name.present?+ scope.first+ end++ def should_assign_user_default_address?(address)+ address.present? && address.valid?endendenddiff --git a/core/spec/models/spree/address_spec.rb b/core/spec/models/spree/address_spec.rbindex a058d0ceaf..3cbe04aab1 100644--- a/core/spec/models/spree/address_spec.rb+++ b/core/spec/models/spree/address_spec.rb@@ -200,6 +200,13 @@ describe Spree::Address, type: :model doexpect(address.errors['zipcode']).not_to include('is invalid')end+ it 'accepts an unformatted zip code' do+ allow(address.country).to receive(:iso).and_return('GB')+ address.zipcode = ' AL38QE'+ address.valid?+ expect(address.errors['zipcode']).not_to include('is invalid')+ end+context 'does not validate' doit 'does not have a country' doaddress.country = nil@@ -439,14 +446,9 @@ describe Spree::Address, type: :model dolet(:address3) { create(:address, user: user) }let(:order) { create(:completed_order_with_totals) }- let(:order2) { create(:order_with_line_items) }-let(:user) { create(:user) }- before do- order.update_attribute(:bill_address, address2)- order2.update_attribute(:ship_address, address3)- end+ before { order.update_attribute(:bill_address, address2) }it 'has required attributes' doexpect(Spree::Address.required_fields).to eq([:firstname, :lastname, :address1, :city, :country, :zipcode, :phone])@@ -464,7 +466,7 @@ describe Spree::Address, type: :model doexpect(address2).to_not be_editableend- it "can't be deleted when there is a complete associated order" do+ it "can't be deleted when there is an associated order" doexpect(address2).to_not be_can_be_deletedend@@ -483,34 +485,104 @@ describe Spree::Address, type: :model doexpect(Spree::Address.not_deleted.where(['id = (?)', address2.id])).to be_emptyend- context 'when address can not be deleted' do- let!(:order) { create(:completed_order_with_totals, bill_address: address, ship_address: address) }+ context 'when saving user raises error' do+ before do+ user.update(ship_address: address2, bill_address: address2)+ user.reload+ allow_any_instance_of(Spree::LegacyUser).to receive(:save!).and_raise(ActiveRecord::RecordInvalid.new)+ end- context 'when address is default user address' do- before { user.update(bill_address: address, ship_address: address) }+ it 'does not set deleted_at attribute for address' do+ expect { address2.destroy }.to raise_error(ActiveRecord::RecordInvalid)+ expect(address2.reload.deleted_at).to be_nil+ end+ end++ describe '#assign_new_default_address_to_user' do+ shared_examples 'default address' do+ context 'when 2 addresses are available' do+ let!(:address3) { create(:address, user: user) }- context 'when user have many addresses' doit 'assigns last available address as default to bill and ship address' do+ user.update!(bill_address: address, ship_address: address)destroy_address+ expect(user.bill_address).to eq(address3)+ expect(user.ship_address).to eq(address3)++ address3.destroy- expect(user.reload.bill_address_id).to eq address2.id- expect(user.reload.ship_address_id).to eq address2.id+ expect(user.bill_address).to eq(address2)+ expect(user.ship_address).to eq(address2)endend- context 'when deleted address was the only one' do+ context 'when the only address left is invalid' dobefore do- address2.destroy- address3.destroy+ address2.update_columns(address1: nil, city: nil, zipcode: nil, phone: nil)+ user.update_columns(bill_address_id: address.id, ship_address_id: address.id)end- it 'does not assign any address' do- destroy_address+ it 'does not raise errors and sets addresses to nil' do+ expect { destroy_address }.not_to raise_error+ expect(user.bill_address).to be_nil+ expect(user.ship_address).to be_nil+ end+ end++ context 'when the only address left is soft-deleted' do+ before do+ address2.update_columns(deleted_at: Time.current)+ end- expect(user.reload.bill_address_id).to be nil- expect(user.reload.ship_address_id).to be nil+ it 'does not raise errors and sets addresses to nil' do+ expect { destroy_address }.not_to raise_error+ expect(user.bill_address).to be_nil+ expect(user.ship_address).to be_nilendend++ context 'when deleted address was not assigned to the user' do+ before { address.update(user: nil) }++ it 'does not touch user' do+ expect{ destroy_address }.not_to change{ user.reload.updated_at }+ end+ end++ context 'when deleted address was not default' do+ before do+ user.update_columns(bill_address_id: address2.id, ship_address_id: address2.id)+ user.reload+ end++ it 'does not change user bill address' do+ expect{ destroy_address }.not_to change{ user.reload.bill_address_id }+ end++ it 'does not change user ship address' do+ expect{ destroy_address }.not_to change{ user.reload.ship_address_id }+ end+ end+ end++ context 'when address is deleted' do+ it 'is deleted' do+ destroy_address+ expect(Spree::Address.find_by(id: address.id)).to be_nil+ end++ it_behaves_like 'default address'+ end++ context 'when address is soft deleted' do+ let!(:order) { create(:completed_order_with_totals, bill_address: address, ship_address: address) }++ it 'is soft deleted' do+ destroy_address+ expect(Spree::Address.find_by(id: address.id).deleted_at).to be_present+ end++ it_behaves_like 'default address'endendenddiff --git a/core/spec/models/spree/order_spec.rb b/core/spec/models/spree/order_spec.rbindex e2fb03385a..75f6ddb2ff 100644--- a/core/spec/models/spree/order_spec.rb+++ b/core/spec/models/spree/order_spec.rb@@ -1473,7 +1473,7 @@ describe Spree::Order, type: :model doit { expect { order.valid? }.to change(order, :number).to('R1234') }end- describe "bill_address_id=" do+ describe 'bill_address_id=' dolet(:user) { create(:user) }let(:order) { create(:order, user: user) }let(:address) { create(:address, user: user) }@@ -1505,10 +1505,43 @@ describe Spree::Order, type: :model docontext 'when user has default bill address' dolet!(:user) { create(:user_with_addresses) }- it 'does not change user default bill addresss' do+ it 'changes user default bill address' doexpect(user.bill_address_id).not_to be nil- expect { subject }.not_to change { user.bill_address_id }+ expect { subject }.to(change { user.bill_address_id })+ end+ end++ context 'when user\'s default address is invalid' do+ let(:invalid_address) { build(:address, firstname: nil, lastname: nil, address1: nil, phone: nil) }+ let(:user) { create(:user, bill_address_id: invalid_address.id) }++ before do+ invalid_address.save(validate: false)+ user+ order.reload+ end++ it 'deletes it and assign new address' do+ expect(user.bill_address_id).to eq invalid_address.id++ subject++ expect(user.reload.bill_address_id).to be_present+ expect(user.bill_address_id).to_not eq(invalid_address.id)++ expect { invalid_address.reload }.to raise_error ActiveRecord::RecordNotFound+ end+ end++ context 'when user has no default address' do+ let!(:user) { create(:user) }++ it 'assigns a new default address' do+ subject++ expect(user.bill_address).to be_present+ expect(user.bill_address.address1).to eq(address_attributes[:address1])endend@@ -1538,7 +1571,7 @@ describe Spree::Order, type: :model doendend- describe "ship_address_id=" do+ describe 'ship_address_id=' dolet(:user) { create(:user) }let(:order) { create(:order, user: user) }let(:address) { create(:address, user: user) }@@ -1570,17 +1603,48 @@ describe Spree::Order, type: :model docontext 'when user has default ship address' dolet!(:user) { create(:user_with_addresses) }- it 'does not change user default ship addresss' do- expect(user.ship_address_id).not_to be nil+ it 'changes user default ship addresss' do+ expect { subject }.to(change { user.ship_address_id })+ end+ end++ context 'when user\'s default address is invalid' do+ let(:invalid_address) { build(:address, firstname: nil, lastname: nil, address1: nil, phone: nil) }+ let(:user) { create(:user, ship_address_id: invalid_address.id) }++ before do+ invalid_address.save(validate: false)+ user+ order.reload+ end++ it 'deletes it and assign new address' do+ expect(user.ship_address_id).to eq invalid_address.id++ subject++ expect(user.reload.ship_address_id).to be_present+ expect(user.ship_address_id).not_to eq(invalid_address.id)++ expect { invalid_address.reload }.to raise_error ActiveRecord::RecordNotFound+ end+ end++ context 'when user has no default address' do+ let!(:user) { create(:user) }++ it 'assigns a new default address' do+ subject- expect { subject }.not_to change { user.ship_address_id }+ expect(user.ship_address).to be_present+ expect(user.ship_address.address1).to eq(address_attributes[:address1])endendcontext 'when user does not have any addresses' dolet!(:user) { create(:user) }- it 'changes user default ship addresss' do+ it 'changes user default ship address' doexpect(user.ship_address_id).to be nilexpect(user.addresses).to be_empty@@ -1594,7 +1658,7 @@ describe Spree::Order, type: :model dobefore { user.update(ship_address: nil) }- it 'changes user default ship addresss' do+ it 'changes user default ship address' doexpect(user.ship_address_id).to be nilexpect(user.addresses).not_to be_empty