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
Refactor address handling: snapshot for orders, dedup in address books (#14533)
Damian Legawiecb33f5b14fbc5
diff --git a/docs/plans/6.0-cart-order-split.md b/docs/plans/6.0-cart-order-split.mdindex 4b4e36627d..287cff1b34 100644--- a/docs/plans/6.0-cart-order-split.md+++ b/docs/plans/6.0-cart-order-split.md@@ -253,6 +253,8 @@ Also in 6.1 (2026-07-29): `spree_orders.market_id` and `spree_orders.channel_id`- Don't read or filter on `order.state` in new code — use `completed_at`/`status` predicates and the requirements API.- New money/fulfillment tables are born with the cart/order owner XOR (already honored by split-adjustments and fulfillment plans).- Don't build on `state_changes` rows at all — the model is gone (2026-08-07); subscribe to lifecycle events.+- An order's address copy is made with `Spree::Address#snapshot`, never `dup` (2026-08-31): the copy records where the parcel went and belongs to the order, so it carries no owner and no label. `dup` kept the owner, which added two fresh copies of the buyer's saved address to their address book on every order they placed. Reuse of an existing address row is confined to the buyer's own book — the ownerless rows are other people's cart addresses and the snapshots placed orders keep.+- Address copying and address equality are two questions, and each has exactly one answer (2026-08-31). `#snapshot` makes the copy; `#==` / `value_attributes` / `EXCLUDED_KEYS_FOR_COMPARISON` answer whether two rows mean the same place, and nothing that makes a copy may read them — otherwise editing equality semantics silently changes what orders record. `Spree::Address#clone` was the third answer and is deprecated: it becomes the standard Ruby `Object#clone` in 6.1, so don't call it and don't build on it.## Resolved Questionsdiff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rbindex 91a207ce6e..06adf7d28f 100644--- a/spree/core/app/models/concerns/spree/customer_methods.rb+++ b/spree/core/app/models/concerns/spree/customer_methods.rb@@ -326,12 +326,12 @@ module Spreeraise Spree::Core::DestroyWithOrdersError if !spree_admin? && orders.complete.present?end+ # One entry, both slots — which is what "ship to my billing address" means+ # in an address book. Copying instead produced either an ownerless row the+ # customer's own book could not see, or a second entry carrying the first+ # one's label, which the per-book label index refuses.def clone_billing_address- if bill_address && ship_address.nil?- self.ship_address = bill_address.clone- else- ship_address.attributes = bill_address.attributes.except('id', 'updated_at', 'created_at')- end+ self.ship_address = bill_address if bill_addresstrueenddiff --git a/spree/core/app/models/concerns/spree/purchase/addresses.rb b/spree/core/app/models/concerns/spree/purchase/addresses.rbindex 69bc774936..1f81951f26 100644--- a/spree/core/app/models/concerns/spree/purchase/addresses.rb+++ b/spree/core/app/models/concerns/spree/purchase/addresses.rb@@ -147,7 +147,7 @@ module Spree## @param attributes [Hash, ActionController::Parameters]def bill_address_attributes=(attributes)- self.bill_address = update_or_create_address(attributes)+ self.bill_address = update_or_create_address(attributes, guest_row: guest_editable_address(bill_address, ship_address_id))customer.bill_address = bill_address if should_assign_user_default_address?(bill_address)end@@ -167,7 +167,7 @@ module Spree## @param attributes [Hash, ActionController::Parameters]def ship_address_attributes=(attributes)- self.ship_address = update_or_create_address(attributes)+ self.ship_address = update_or_create_address(attributes, guest_row: guest_editable_address(ship_address, bill_address_id))customer.ship_address = ship_address if should_assign_user_default_address?(ship_address)self.ship_address = nil if quick_checkout_address?(attributes[:quick_checkout]) && !ship_address.persisted?end@@ -201,27 +201,51 @@ module Spreecompany.self_and_ancestors.any? { |node| node.id == address.owner_id } ? address : nilend- def update_or_create_address(attributes = {})+ # Reuse never reaches past what the buyer already owns: a signed-in buyer+ # may name any entry of their own address book, and a guest — who keeps+ # no book — may only edit the row already in the slot being written.+ # Every other ownerless row is someone else's cart address or the+ # snapshot a placed order keeps, and reaching into those would let one+ # checkout read or rewrite another's address.+ def update_or_create_address(attributes = {}, guest_row: nil)return if attributes.blank?attributes.transform_values!(&:presence)attributes = attributes.to_h.symbolize_keys- default_address_scope = customer ? customer.addresses : ::Spree::Address.where(owner_id: nil)- default_address = default_address_scope.find_by(id: attributes[:id])+ reusable_address = customer ? customer.addresses.find_by(id: attributes[:id]) : guest_row- if default_address&.editable?- default_address.update(attributes)+ if reusable_address&.editable?+ reusable_address.update(attributes)- return default_address+ return reusable_addressendattributes = attributes.except(:id, :updated_at, :created_at)+ return ::Spree::Address.create(attributes) if customer.nil?+attributes[:owner] = customer::Spree::Address.find_duplicate(attributes) || ::Spree::Address.create(attributes)end+ # The row a guest write may edit in place rather than replace: the one+ # already in this slot, which is the only address a guest owns. Editing+ # it keeps a correction from leaving the row it corrected behind as an+ # orphan carrying someone's name and street.+ #+ # It is left alone while the other slot points at the same row — checkout+ # shares one row between the two whenever shipping is copied onto billing,+ # and editing it there would move the parcel as well as the invoice.+ #+ # @return [Spree::Address, nil]+ def guest_editable_address(address, other_slot_address_id)+ return nil if customer.present? || address.nil? || !address.persisted?+ return nil if address.owner_id.present? || address.id == other_slot_address_id++ address+ end+def quick_checkout_address?(quick_checkout_param)quick_checkout_param.present? ? quick_checkout_param.to_b : falseenddiff --git a/spree/core/app/models/concerns/spree/user_address.rb b/spree/core/app/models/concerns/spree/user_address.rbindex 4c2aa04542..01cf9315c2 100644--- a/spree/core/app/models/concerns/spree/user_address.rb+++ b/spree/core/app/models/concerns/spree/user_address.rb@@ -27,7 +27,14 @@ module Spree@address ||= bill_address || ship_address || addresses.firstend+ # @deprecated Nothing in Spree calls this. Checkout promotes the addresses+ # it accepts to the customer's defaults on its own (see+ # Spree::Purchase::Addresses), and a guest who registers after placing+ # an order has that order's addresses adopted by Spree::Customers::Create.+ # Removed in Spree 6.1.def persist_order_address(order)+ Spree::Deprecation.warn('Spree::UserAddress#persist_order_address is deprecated and will be removed in Spree 6.1. Checkout already promotes the addresses it accepts to the customer\'s defaults.')+# FIXME: we should check if the User's address is associated with country accepted by Store# if not we should try to find an address with valid country in User's address book# or we should call `build_bill_address`diff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rbindex 8b3bb803ee..506450e3db 100644--- a/spree/core/app/models/spree/address.rb+++ b/spree/core/app/models/spree/address.rb@@ -26,7 +26,18 @@ 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 owner_type owner_id metadata)+ # Beyond identity and ownership, three groups are excluded because they+ # cannot tell two addresses apart. Latitude and longitude are derived from+ # the address, so an entry whose geocoding has already run would otherwise+ # never match the same address freshly typed in. country_id and state_id+ # are the pre-6.0 foreign keys, which the upgrade task copies into codes+ # and leaves populated: comparing them makes every migrated row differ+ # from every new one. Both are handled the same way by .find_duplicate,+ # which drops the legacy keys through .resolve_geo_params.+ EXCLUDED_KEYS_FOR_COMPARISON = %w(+ id updated_at created_at deleted_at label owner_type owner_id metadata+ latitude longitude country_id state_id+ )if defined?(Spree::Security::Addresses)include Spree::Security::Addressesend@@ -287,10 +298,60 @@ module Spree].reject(&:blank?).map { |attribute| ERB::Util.html_escape(attribute) }.join('<br/>')end+ # @deprecated Overriding Ruby's +Object#clone+ was a mistake: this returns+ # a value copy with the owner, label and metadata stripped, which is not+ # what +clone+ means anywhere else in Ruby. The override is removed in+ # Spree 6.1 and +clone+ becomes the standard shallow copy. Use+ # {#snapshot} for the ownerless copy a purchase keeps.def clone+ Spree::Deprecation.warn(+ 'Spree::Address#clone is deprecated. From Spree 6.1 it behaves as the standard Ruby Object#clone — a shallow copy keeping the owner and every other attribute. Use #snapshot for the ownerless copy a purchase keeps.'+ )+self.class.new(value_attributes)end+ # A copy of this address for a purchase to keep. An order's address records+ # where the parcel actually went, so it belongs to the order and not to+ # anyone's address book — a copy that kept the owner would file a second+ # entry in the buyer's book on every order they place. Having no owner it+ # carries no label either: a label is unique within one book, so every+ # ownerless snapshot would compete for the same one.+ #+ # @return [Spree::Address]+ def snapshot+ dup.tap do |copy|+ copy.owner = nil+ copy.label = nil+ copy.deleted_at = nil+ end+ end++ # The entry the owner's book already holds for this, if there is one, so+ # someone re-entering an address they already saved gets the entry they+ # have back instead of a near-copy filed beside it.+ #+ # An entry is more than a place. Two rows match only when they mean the+ # same place ({#==}) *and* agree on the things the owner attached to the+ # entry itself — its label and its metadata. A company filing "Dock A" and+ # "Dock B" at one site keeps two entries, and neither request silently+ # loses the name it was filed under.+ #+ # Owners that keep no book, including no owner at all, have nothing to+ # match against.+ #+ # @return [Spree::Address, nil]+ def duplicate_in_address_book+ return nil unless owner.respond_to?(:addresses)++ owner.addresses.not_deleted.detect do |existing|+ existing.id != id &&+ existing == self &&+ existing.label == label &&+ existing.metadata.to_h == metadata.to_h+ end+ end+def ==(other)return false unless other&.respond_to?(:value_attributes)diff --git a/spree/core/app/services/spree/addresses/create.rb b/spree/core/app/services/spree/addresses/create.rbindex 18409801ad..5b80bcfee1 100644--- a/spree/core/app/services/spree/addresses/create.rb+++ b/spree/core/app/services/spree/addresses/create.rb@@ -19,32 +19,71 @@ module Spreeaddress.owner = owner if owner.present?ApplicationRecord.transaction do- if address.save- if owner.present?- # The first address a book gets is its default of both kinds —- # there is nothing for it to displace.- if owner.addresses.pluck(:id) == [address.id]- assign_owner_default(owner: owner, address_id: address.id)- else- assign_owner_default(- owner: owner,- address_id: address.id,- default_billing: default_billing,- default_shipping: default_shipping- )- end- end+ arguments = { order: order, default_billing: default_billing, default_shipping: default_shipping }+ next write(address, **arguments) if owner.nil?- assign_to_order(order: order, address_id: address.id) if order.present?- success(address)- else- failure(address)- end+ # One writer per book at a time. Looking for an entry and then filing+ # one when there is none is a read the write depends on, and no+ # unique index stands behind it, so two requests arriving together+ # would each find nothing and file an entry each — the very duplicate+ # the lookup exists to prevent.+ owner.with_lock { write(address, **arguments) }endendprivate+ def write(address, order:, default_billing:, default_shipping:)+ owner = address.owner+ existing = existing_entry(address)++ if existing.present?+ assign_owner_default(+ owner: owner,+ address_id: existing.id,+ default_billing: default_billing,+ default_shipping: default_shipping+ )++ assign_to_order(order: order, address_id: existing.id) if order.present?+ success(existing)+ elsif address.save+ if owner.present?+ # The first address a book gets is its default of both kinds —+ # there is nothing for it to displace.+ if owner.addresses.pluck(:id) == [address.id]+ assign_owner_default(owner: owner, address_id: address.id)+ else+ assign_owner_default(+ owner: owner,+ address_id: address.id,+ default_billing: default_billing,+ default_shipping: default_shipping+ )+ end+ end++ assign_to_order(order: order, address_id: address.id) if order.present?+ success(address)+ else+ failure(address)+ end+ end++ # The entry the book already holds for this, so a book that has it gets+ # that entry back rather than a second copy of it.+ #+ # Validation runs first only to resolve the country and state codes, and+ # its verdict is deliberately ignored: a resubmission carrying the label+ # it was filed under is invalid precisely because that entry already+ # exists, and answering it with "name has already been taken" instead of+ # the entry itself would be absurd. A genuinely invalid address matches+ # nothing and fails on the save that follows.+ def existing_entry(address)+ address.validate+ address.duplicate_in_address_book+ end+def assign_to_order(order:, address_id:)order.update(ship_address_id: address_id)enddiff --git a/spree/core/app/services/spree/carts/split_by_seller.rb b/spree/core/app/services/spree/carts/split_by_seller.rbindex 7853cfc893..2414a469a7 100644--- a/spree/core/app/services/spree/carts/split_by_seller.rb+++ b/spree/core/app/services/spree/carts/split_by_seller.rb@@ -84,8 +84,8 @@ module Spreecurrency: cart.currency,email: cart.email,token: cart.token,- ship_address: cart.ship_address&.dup,- bill_address: cart.bill_address&.dup+ ship_address: cart.ship_address&.snapshot,+ bill_address: cart.bill_address&.snapshot)groupend@@ -114,8 +114,8 @@ module Spree'status' => 'draft',# Copies, not the same rows: each order has to be able to have its# address corrected without moving a sibling's parcel.- 'ship_address' => source_order.ship_address&.dup,- 'bill_address' => source_order.bill_address&.dup+ 'ship_address' => source_order.ship_address&.snapshot,+ 'bill_address' => source_order.bill_address&.snapshot))diff --git a/spree/core/app/services/spree/orders/create.rb b/spree/core/app/services/spree/orders/create.rbindex 50f4c1c13f..2380076954 100644--- a/spree/core/app/services/spree/orders/create.rb+++ b/spree/core/app/services/spree/orders/create.rb@@ -103,8 +103,8 @@ module Spreeif @params[:use_customer_default_address] && @customer@customer.association(:bill_address).load_target@customer.association(:ship_address).load_target- order.bill_address = @customer.bill_address&.dup- order.ship_address = @customer.ship_address&.dup+ order.bill_address = @customer.bill_address&.snapshot+ order.ship_address = @customer.ship_address&.snapshotendassign_address(order, :ship_address, @params[:shipping_address_id], @params[:shipping_address])diff --git a/spree/core/app/services/spree/orders/create_from_cart.rb b/spree/core/app/services/spree/orders/create_from_cart.rbindex afc0196965..1a7e6cb5ce 100644--- a/spree/core/app/services/spree/orders/create_from_cart.rb+++ b/spree/core/app/services/spree/orders/create_from_cart.rb@@ -55,8 +55,8 @@ module Spreemetadata: cart.metadata.to_h,preferred_stock_location_id: cart.preferred_stock_location_id,token: Spree::GenerateToken.new.call(Spree::Order),- ship_address: cart.ship_address&.dup,- bill_address: cart.bill_address&.dup+ ship_address: cart.ship_address&.snapshot,+ bill_address: cart.bill_address&.snapshot)enddiff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex e5e495b7db..23fe5f597c 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -224,8 +224,8 @@ module Spreecustomer_note: cart.customer_note,po_number: cart.po_number,last_ip_address: cart.last_ip_address,- ship_address: cart.ship_address&.dup,- bill_address: cart.bill_address&.dup+ ship_address: cart.ship_address&.snapshot,+ bill_address: cart.bill_address&.snapshot)order.save!diff --git a/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb b/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rbindex 114d690fe2..718d046613 100644--- a/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb@@ -50,6 +50,68 @@ RSpec.shared_examples 'an addresses host' doexpect(user.ship_address).to be_nilend++ # Reuse means "an address this buyer already owns". A guest owns none, so+ # the ownerless rows around them — other guests' cart addresses, and the+ # snapshots placed orders keep — must stay out of reach.+ context 'on a guest record' do+ it 'writes its own row rather than reusing an ownerless one' do+ ownerless = Spree::Address.create!(address_attributes)++ guest_record.ship_address_attributes = address_attributes++ expect(guest_record.ship_address).to be_persisted+ expect(guest_record.ship_address.id).not_to eq(ownerless.id)+ end++ it 'ignores an id naming an ownerless address it does not hold' do+ ownerless = Spree::Address.create!(address_attributes)++ guest_record.ship_address_attributes = { id: ownerless.id, first_name: 'Renamed' }++ expect(guest_record.ship_address.id).not_to eq(ownerless.id)+ expect(ownerless.reload.first_name).not_to eq('Renamed')+ end++ # The row already in the slot is the one address a guest owns, so a+ # correction edits it rather than leaving it behind carrying someone's+ # name and street.+ it 'edits the row already in the slot' do+ guest_record.update!(ship_address_attributes: address_attributes)+ own = guest_record.ship_address++ expect do+ guest_record.update!(ship_address_attributes: address_attributes.merge(address1: '2 Other Street'))+ end.not_to change(Spree::Address, :count)++ expect(guest_record.ship_address.id).to eq(own.id)+ expect(own.reload.address1).to eq('2 Other Street')+ end++ it 'accepts a partial payload naming the row it holds' do+ guest_record.update!(ship_address_attributes: address_attributes)+ own = guest_record.ship_address++ expect(guest_record.update(ship_address_attributes: { id: own.id, zipcode: '10118' })).to be(true)+ expect(own.reload.zipcode).to eq('10118')+ expect(own.reload.address1).to eq(address_attributes[:address1])+ end++ # use_shipping points both slots at one row; editing it for billing+ # would move the parcel as well as the invoice.+ it 'does not edit a row the other slot points at too' do+ guest_record.update!(ship_address_attributes: address_attributes)+ guest_record.update!(use_shipping: true)+ shared = guest_record.reload.ship_address+ expect(guest_record.bill_address_id).to eq(shared.id)++ guest_record.use_shipping = false+ guest_record.update!(bill_address_attributes: address_attributes.merge(address1: '2 Other Street'))++ expect(guest_record.bill_address.id).not_to eq(shared.id)+ expect(shared.reload.address1).to eq(address_attributes[:address1])+ end+ endenddescribe '#bill_address_attributes=' dodiff --git a/spree/core/spec/models/spree/address_spec.rb b/spree/core/spec/models/spree/address_spec.rbindex e01ac1a110..8003e0027e 100644--- a/spree/core/spec/models/spree/address_spec.rb+++ b/spree/core/spec/models/spree/address_spec.rb@@ -39,7 +39,15 @@ describe Spree::Address, type: :model doendend- describe 'clone' do+ describe 'clone (deprecated, becomes the standard Ruby clone in 6.1)' do+ before { allow(Spree::Deprecation).to receive(:warn) }++ it 'warns and points at #snapshot' do+ create(:address).clone++ expect(Spree::Deprecation).to have_received(:warn).with(/#snapshot/)+ end+it 'creates a copy of the address with the exception of the id, label, owner, updated_at and created_at attributes' dostate = create(:state)original = create(:address,@@ -526,7 +534,7 @@ describe Spree::Address, type: :model docontext '#==' dolet(:address) { create(:address) }- let(:address2) { address.clone }+ let(:address2) { address.snapshot }context 'same addresses' doit { expect(address == address2).to eq(true) }@@ -972,4 +980,110 @@ describe Spree::Address, type: :model doexpect(described_class.find_duplicate(address1: 'nowhere at all')).to be_nilendend++ describe '#snapshot' do+ let(:customer) { create(:customer) }+ let(:address) { create(:address, owner: customer, label: 'Home') }++ subject(:snapshot) { address.snapshot }++ it 'copies the address without an owner, so it stays out of the book it came from' do+ expect(snapshot.owner).to be_nil+ expect(snapshot.address1).to eq(address.address1)+ expect(snapshot.city).to eq(address.city)+ expect(snapshot.zipcode).to eq(address.zipcode)+ end++ it 'drops the label, which belongs to the entry in the book' do+ expect(snapshot.label).to be_nil+ end++ it 'is a new record' do+ expect(snapshot).to be_new_record+ end++ it 'lets two snapshots of the same labelled address be saved side by side' do+ expect(address.snapshot.save).to be(true)+ expect(address.snapshot.save).to be(true)+ end+ end++ describe '#duplicate_in_address_book' do+ let(:customer) { create(:customer) }+ let(:attributes) do+ { firstname: 'John', lastname: 'Doe', company: 'Company', address1: '1 Main St',+ address2: 'Northwest', city: 'New York', zipcode: '10001', state_code: 'NY',+ country_code: 'US', phone: '555-1212', alternative_phone: '555-1213' }+ end+ let!(:saved) { create(:address, attributes.merge(owner: customer)) }++ def build_for(owner, overrides = {})+ described_class.new(attributes.merge(overrides)).tap do |address|+ address.owner = owner+ address.valid?+ end+ end++ it 'finds the entry the book already holds' do+ expect(build_for(customer).duplicate_in_address_book).to eq(saved)+ end++ it 'ignores geocoding, which is derived from the address' do+ saved.update_columns(latitude: 40.7, longitude: -74.0)++ expect(build_for(customer).duplicate_in_address_book).to eq(saved)+ end++ it 'returns nil when the address differs' do+ expect(build_for(customer, address1: '2 Main St').duplicate_in_address_book).to be_nil+ end++ it 'returns nil for a deleted entry' do+ saved.update_column(:deleted_at, Time.current)++ expect(build_for(customer).duplicate_in_address_book).to be_nil+ end++ it 'never reaches into another owner\'s book' do+ expect(build_for(create(:customer)).duplicate_in_address_book).to be_nil+ end++ it 'returns nil without an owner' do+ expect(build_for(nil).duplicate_in_address_book).to be_nil+ end++ it 'does not match the address against itself' do+ expect(saved.duplicate_in_address_book).to be_nil+ end++ # The upgrade task copies the pre-6.0 foreign keys into codes and leaves+ # them populated, so comparing them would make every migrated entry differ+ # from every newly typed one and silently disable deduplication.+ it 'matches an entry still carrying the pre-6.0 country and state ids' do+ saved.update_columns(country_id: 42, state_id: 7)++ expect(build_for(customer).duplicate_in_address_book).to eq(saved)+ end++ # A label names the entry, not the place: "Dock A" and "Dock B" at one site+ # are two entries a company is entitled to keep.+ it 'does not match an entry filed under a different label' do+ saved.update!(label: 'Dock A')++ expect(build_for(customer, label: 'Dock B').duplicate_in_address_book).to be_nil+ end++ it 'matches an entry filed under the same label' do+ saved.update!(label: 'Dock A')++ expect(build_for(customer, label: 'Dock A').duplicate_in_address_book).to eq(saved)+ end++ it 'does not match when the request carries metadata the entry lacks' do+ built = build_for(customer)+ built.metadata = { 'gate_code' => '1234' }++ expect(built.duplicate_in_address_book).to be_nil+ end+ endenddiff --git a/spree/core/spec/models/spree/customer_spec.rb b/spree/core/spec/models/spree/customer_spec.rbindex 9b12d4ceba..24de728ddd 100644--- a/spree/core/spec/models/spree/customer_spec.rb+++ b/spree/core/spec/models/spree/customer_spec.rb@@ -51,6 +51,33 @@ describe Spree::Customer, type: :model dolet(:lockable) { customer }end+ describe 'use_billing' do+ let(:customer) { create(:customer) }+ let(:address) { create(:address, owner: customer) }++ # One entry serving both slots. The old copy left the customer's default+ # shipping address as a row their own address book could not see.+ it 'points the shipping slot at the billing entry' do+ customer.bill_address = address+ customer.use_billing = true+ customer.save!++ expect(customer.reload.ship_address_id).to eq(address.id)+ expect(customer.addresses.map(&:id)).to eq([address.id])+ end++ # Overwriting the existing shipping entry in place copied the billing+ # entry's label onto it, and two entries in one book cannot share a label.+ it 'replaces an existing shipping address rather than overwriting it' do+ labelled = create(:address, owner: customer, label: 'Home')+ customer.update!(bill_address: labelled, ship_address: create(:address, owner: customer, label: 'Office'))+ customer.use_billing = true++ expect(customer.save).to be(true)+ expect(customer.reload.ship_address_id).to eq(labelled.id)+ end+ end+describe 'prefixed id' doit 'uses the cust_ prefix' doexpect(customer.prefixed_id).to start_with('cust_')diff --git a/spree/core/spec/models/spree/user_spec.rb b/spree/core/spec/models/spree/user_spec.rbindex db7b49b986..ba2893d946 100644--- a/spree/core/spec/models/spree/user_spec.rb+++ b/spree/core/spec/models/spree/user_spec.rb@@ -59,7 +59,15 @@ describe Spree.customer_class, type: :model do # rubocop:disable RSpec/MultipleDendend- context 'persists order address' do+ context 'persists order address (deprecated, removed in 6.1)' do+ before { allow(Spree::Deprecation).to receive(:warn) }++ it 'warns that nothing needs to call it' do+ user.persist_order_address(order)++ expect(Spree::Deprecation).to have_received(:warn).with(/persist_order_address is deprecated/)+ end+it 'copies over order addresses' doexpect douser.persist_order_address(order)diff --git a/spree/core/spec/services/spree/addresses/create_spec.rb b/spree/core/spec/services/spree/addresses/create_spec.rbnew file mode 100644index 0000000000..a5559792ca--- /dev/null+++ b/spree/core/spec/services/spree/addresses/create_spec.rb@@ -0,0 +1,133 @@+require 'spec_helper'++RSpec.describe Spree::Addresses::Create do+ subject { described_class }++ let(:customer) { create(:customer) }+ let(:address_params) do+ {+ firstname: 'John',+ lastname: 'Doe',+ company: 'Company',+ address1: '1 Main Street',+ address2: 'Northwest',+ city: 'New York',+ zipcode: '10001',+ phone: '555-555-0199',+ alternative_phone: '555-555-0199',+ state_code: 'NY',+ country_code: 'US'+ }+ end++ describe '#call' do+ it 'creates the address and makes it the owner\'s default of both kinds' do+ result = subject.call(address_params: address_params.dup, owner: customer)++ expect(result).to be_success+ expect(customer.reload.addresses.count).to eq(1)+ expect(customer.bill_address_id).to eq(result.value.id)+ expect(customer.ship_address_id).to eq(result.value.id)+ end++ context 'when the owner already has the same address' do+ let!(:existing) { subject.call(address_params: address_params.dup, owner: customer).value }++ it 'returns the entry the book already holds' do+ result = subject.call(address_params: address_params.dup, owner: customer)++ expect(result).to be_success+ expect(result.value).to eq(existing)+ end++ it 'does not add a second copy' do+ expect {+ subject.call(address_params: address_params.dup, owner: customer)+ }.not_to change { customer.reload.addresses.count }+ end++ it 'reuses the entry even when the country is written in lower case' do+ result = subject.call(+ address_params: address_params.merge(country_code: 'us', state_code: 'ny'),+ owner: customer+ )++ expect(result.value).to eq(existing)+ end++ it 'still moves the requested default onto it' do+ other = subject.call(address_params: address_params.merge(address1: '2 Main Street'), owner: customer).value+ customer.reload.update!(bill_address_id: other.id)++ subject.call(address_params: address_params.dup, owner: customer, default_billing: true)++ expect(customer.reload.bill_address_id).to eq(existing.id)+ end++ # The entry keeps the name it was filed under. Returning the existing,+ # differently named entry would drop the label and make a second one+ # impossible.+ it 'files a second entry when the request names it differently' do+ first = subject.call(address_params: address_params.merge(label: 'Dock A'), owner: customer)+ second = subject.call(address_params: address_params.merge(label: 'Dock B'), owner: customer)++ expect(second).to be_success+ expect(second.value.id).not_to eq(first.value.id)+ expect(second.value.label).to eq('Dock B')+ end++ # The label is taken precisely because the entry is already there, so the+ # answer is that entry — never "name has already been taken".+ it 'returns the existing entry when the request repeats its label' do+ first = subject.call(address_params: address_params.merge(label: 'Dock A'), owner: customer)+ repeat = subject.call(address_params: address_params.merge(label: 'Dock A'), owner: customer)++ expect(repeat).to be_success+ expect(repeat.value.id).to eq(first.value.id)+ end++ it 'creates a new address when a field differs' do+ expect {+ subject.call(address_params: address_params.merge(address1: '2 Main Street'), owner: customer)+ }.to change { customer.reload.addresses.count }.by(1)+ end+ end++ # Finding no entry and then filing one is a read the write depends on, and+ # no unique index stands behind it.+ it 'serializes writes to one book so simultaneous requests cannot each file an entry' do+ expect(customer).to receive(:with_lock).once.and_call_original++ expect(subject.call(address_params: address_params.dup, owner: customer)).to be_success+ end++ it 'writes an ownerless address without a book to serialize on' do+ result = subject.call(address_params: address_params.dup)++ expect(result).to be_success+ expect(result.value).to be_persisted+ expect(result.value.owner).to be_nil+ end++ context 'when another customer has the same address' do+ let(:other_customer) { create(:customer) }++ before { subject.call(address_params: address_params.dup, owner: other_customer) }++ it 'creates its own entry rather than reusing theirs' do+ result = subject.call(address_params: address_params.dup, owner: customer)++ expect(result.value.owner).to eq(customer)+ expect(customer.reload.addresses.count).to eq(1)+ end+ end++ context 'with invalid params' do+ it 'fails without creating anything' do+ expect {+ expect(subject.call(address_params: address_params.merge(address1: nil), owner: customer)).to be_failure+ }.not_to change { Spree::Address.count }+ end+ end+ end+enddiff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rbindex 8a00860565..65ecdb9f33 100644--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb@@ -59,6 +59,23 @@ module Spreeexpect(order.token).to eq(ready_cart.token)end+ # The order's addresses record where the parcel went. Filing them in the+ # buyer's address book gave them two fresh copies of an address they had+ # already saved, on every single order.+ it 'leaves the addresses it copies out of the buyer\'s address book' do+ customer = create(:customer)+ ready_cart.update!(customer: customer)+ ready_cart.ship_address.update!(owner: customer)+ ready_cart.bill_address.update!(owner: customer)++ expect { subject }.not_to change { customer.reload.addresses.count }++ order = Spree::Order.find_by(cart_id: ready_cart.id)+ expect(order.ship_address.owner).to be_nil+ expect(order.bill_address.owner).to be_nil+ expect(order.ship_address.address1).to eq(ready_cart.ship_address.address1)+ end+it 'is idempotent — replay returns the same order' dofirst = subject.valuereplay = described_class.call(cart: ready_cart.reload)