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
Give an address a polymorphic owner and drop the business subclass
Damian Legawiecf3602f15d0bd
diff --git a/spree/core/app/models/concerns/spree/purchase/addresses.rb b/spree/core/app/models/concerns/spree/purchase/addresses.rbindex f89107bcfd..2173cfc7dc 100644--- a/spree/core/app/models/concerns/spree/purchase/addresses.rb+++ b/spree/core/app/models/concerns/spree/purchase/addresses.rb@@ -138,7 +138,7 @@ module Spreeaddress = Spree::Address.find_by(id: id)# rubocop:disable Style/ConditionalAssignment- if address && customer_id.present? && address.customer_id == customer_id+ if address && customer_id.present? && address.owner_id == customer_id && address.customer_owned?self['bill_address_id'] = address.idelseself['bill_address_id'] = nil@@ -165,7 +165,7 @@ module Spreeaddress = Spree::Address.find_by(id: id)# rubocop:disable Style/ConditionalAssignment- if address && customer_id.present? && address.customer_id == customer_id+ if address && customer_id.present? && address.owner_id == customer_id && address.customer_owned?self['ship_address_id'] = address.idelseself['ship_address_id'] = nil@@ -193,7 +193,7 @@ module Spreeattributes.transform_values!(&:presence)attributes = attributes.to_h.symbolize_keys- default_address_scope = customer ? customer.addresses : ::Spree::Address.where(customer_id: nil)+ default_address_scope = customer ? customer.addresses : ::Spree::Address.where(owner_id: nil)default_address = default_address_scope.find_by(id: attributes[:id])if default_address&.editable?@@ -203,7 +203,7 @@ module Spreeendattributes = attributes.except(:id, :updated_at, :created_at)- attributes[:customer_id] = customer&.id+ attributes[:owner] = customer::Spree::Address.find_duplicate(attributes) || ::Spree::Address.create(attributes)end@@ -213,7 +213,7 @@ module Spreeenddef should_assign_user_default_address?(address)- customer.present? && address.present? && address.valid? && address.customer == customer && !address.quick_checkout?+ customer.present? && address.present? && address.valid? && address.customer_owner == customer && !address.quick_checkout?endendenddiff --git a/spree/core/app/models/concerns/spree/user_address.rb b/spree/core/app/models/concerns/spree/user_address.rbindex 088f3c6703..80331ce324 100644--- a/spree/core/app/models/concerns/spree/user_address.rb+++ b/spree/core/app/models/concerns/spree/user_address.rb@@ -16,7 +16,7 @@ module Spreeaccepts_nested_attributes_for :ship_address, :bill_addresshas_many :addresses, -> { where(deleted_at: nil).order('updated_at DESC') },- class_name: 'Spree::Address', foreign_key: :customer_id+ class_name: 'Spree::Address', as: :ownervalidate :address_not_associated_with_other_user, :address_not_deprecated_in_completed_order@@ -45,8 +45,8 @@ module Spreeprivatedef address_not_associated_with_other_user- errors.add(:bill_address_id, :belongs_to_other_user) if bill_address&.customer_id && self != bill_address&.customer- errors.add(:ship_address_id, :belongs_to_other_user) if ship_address&.customer_id && self != ship_address&.customer+ errors.add(:bill_address_id, :belongs_to_other_user) if bill_address&.owner && self != bill_address.owner+ errors.add(:ship_address_id, :belongs_to_other_user) if ship_address&.owner && self != ship_address.ownerenddef address_not_deprecated_in_completed_orderdiff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rbindex 2dbe028e78..1cdeb9f12f 100644--- a/spree/core/app/models/spree/address.rb+++ b/spree/core/app/models/spree/address.rb@@ -26,7 +26,7 @@ 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 customer_id metadata)+ EXCLUDED_KEYS_FOR_COMPARISON = %w(id updated_at created_at deleted_at label owner_type owner_id metadata)if defined?(Spree::Security::Addresses)include Spree::Security::Addressesend@@ -53,20 +53,27 @@ module Spreealias_attribute :state_abbr, :state_codealias_attribute :country_iso, :country_code- # we need a safe operator here as Address is added to custom_field_enabled_resources in Engine- belongs_to :customer, class_name: Spree.customer_class&.name, optional: true, touch: true- include Spree::DeprecatedCustomerAlias+ # Who the address belongs to: a customer's address book, a company node's,+ # or a seller's billing address. One relationship with three cardinalities,+ # so a further owner costs no schema change — and what the row requires+ # follows from the owner rather than from a subclass.+ #+ # Order and cart addresses have no owner: completion copies the attributes+ # onto a fresh row, and that snapshot belongs to the order, not to anyone's+ # book.+ belongs_to :owner, polymorphic: true, optional: true, touch: true+has_many :fulfillments, class_name: 'Spree::Fulfillment', inverse_of: :addresshas_many :shipments, class_name: 'Spree::Fulfillment', foreign_key: :address_id, deprecated: true- after_initialize :set_default_values, if: -> { new_record? && customer.present? }+ after_initialize :set_default_values, if: -> { new_record? && customer_owned? }before_validation :normalize_countrybefore_validation :normalize_statebefore_validation :clear_invalid_state_entities, if: -> { country.present? }, on: :update- after_create :set_user_attributes, if: -> { customer.present? }+ after_create :set_user_attributes, if: -> { customer_owned? }after_commit :async_geocode@@ -83,7 +90,7 @@ module Spreevalidate :address_validators, on: [:create, :update]validates :label, uniqueness: { conditions: -> { where(deleted_at: nil) },- scope: :customer_id,+ scope: [:owner_type, :owner_id],case_sensitive: false,allow_blank: true,allow_nil: true }@@ -168,7 +175,7 @@ module Spreeendself.whitelisted_ransackable_attributes = ADDRESS_FIELDS + %w[country_code state_code]- self.whitelisted_ransackable_associations = %w[customer]+ self.whitelisted_ransackable_associations = %w[owner]def self.required_fieldsSpree::Address.validators.map do |v|@@ -176,15 +183,68 @@ module Spreeend.flattenend+ # The owner when it is a customer, so customer-specific behaviour (the+ # address book defaults, the profile back-fill) reads nil for a company's+ # or a seller's row and simply does not apply.+ #+ # @return [Object, nil]+ def customer_owner+ owner if customer_owned?+ end++ # @return [Boolean]+ def customer_owned?+ owner_type == Spree.customer_class.to_s+ end++ # @deprecated The address's owner may be a customer, a company node or a+ # seller, so {#owner} replaces the customer-only association. Removed in+ # Spree 6.1.+ def user+ Spree::Deprecation.warn('Spree::Address#user is deprecated and will be removed in Spree 6.1. Use #owner instead.') if defined?(Spree::Deprecation)+ customer_owner+ end++ def user=(value)+ Spree::Deprecation.warn('Spree::Address#user= is deprecated and will be removed in Spree 6.1. Use #owner= instead.') if defined?(Spree::Deprecation)+ self.owner = value+ end++ def user_id+ Spree::Deprecation.warn('Spree::Address#user_id is deprecated and will be removed in Spree 6.1. Use #owner_id instead.') if defined?(Spree::Deprecation)+ owner_id if customer_owned?+ end++ # A company node's or a seller's address: nobody is named on it, and the+ # business is the part that cannot be left out.+ #+ # @return [Boolean]+ def business_owned?+ owner_type == 'Spree::Company' || owner_type == 'Spree::Seller'+ end++ # The company line. A stored value wins, so an order's copied address keeps+ # what it was sent with even after the node is renamed, and a member can+ # override the line for one site. An owned book entry with nothing stored+ # tracks its node's current name.+ #+ # @return [String, nil]+ def company+ stored = read_attribute(:company)+ return stored if stored.present?++ owner.name if owner.is_a?(Spree::Company)+ end+# In 6.0 these become real columns on Address, replacing User#bill_address_id / ship_address_id.# For now they delegate to the User FK so the API shape is stable.def is_default_billing?- customer.present? && id == customer.bill_address_id+ customer_owner.present? && id == customer_owner.bill_address_idendalias_method :is_default_billing, :is_default_billing?def is_default_shipping?- customer.present? && id == customer.ship_address_id+ customer_owner.present? && id == customer_owner.ship_address_idendalias_method :is_default_shipping, :is_default_shipping?@@ -262,14 +322,23 @@ module Spree!quick_checkout && (country ? country.zipcode_required? : true)end+ # A business address names no person: a company site or a seller's billing+ # address has no contact to insist on, which is why the owner decides this+ # rather than a subclass.def require_name?- !quick_checkout+ !quick_checkout && !business_owned?enddef require_company?+ return false if quick_checkout+ # A company node names itself, so the line is always answerable; a+ # seller's billing address is what a commission invoice is addressed to,+ # and that is the part which cannot be left out.+ return true if business_owned?+# Only meaningful when the field is on the form at all — requiring a# value the customer is never shown would make checkout unfinishable.- !quick_checkout && show_company_address_field? && store_preference(:address_requires_company, false)+ show_company_address_field? && store_preference(:address_requires_company, false)enddef require_street?@@ -277,6 +346,8 @@ module Spreeenddef show_company_address_field?+ return true if business_owned?+store_preference(:company_field_enabled, false)end@@ -328,9 +399,9 @@ module Spreeenddef set_default_values- self.firstname ||= customer.first_name- self.lastname ||= customer.last_name- self.phone ||= customer.phone+ self.firstname ||= customer_owner.first_name+ self.lastname ||= customer_owner.last_name+ self.phone ||= customer_owner.phoneend# The ISO code is what the address stores; the association is kept in step@@ -394,6 +465,7 @@ module Spreeenddef set_user_attributes+ customer = customer_ownerif customer.name.blank?customer.first_name = firstnamecustomer.last_name = lastname@@ -439,6 +511,7 @@ module Spreeenddef assign_new_default_address_to_user+ customer = customer_ownerreturn unless customercustomer.reload@@ -452,11 +525,11 @@ module Spreeenddef assign_new_default_address_to_user_scope- customer.addresses.not_quick_checkout.reorder(created_at: :desc)+ customer_owner.addresses.not_quick_checkout.reorder(created_at: :desc)enddef unassign_from_incomplete_orders- orders = Spree::Order.incomplete.where(customer_id: customer_id)+ orders = Spree::Order.incomplete.where(customer_id: owner_id)orders.where(ship_address_id: id).update_all(ship_address_id: nil, updated_at: Time.current)orders.where(bill_address_id: id).update_all(bill_address_id: nil, updated_at: Time.current)enddiff --git a/spree/core/app/models/spree/base.rb b/spree/core/app/models/spree/base.rbindex 9f0da393c7..04aba81c87 100644--- a/spree/core/app/models/spree/base.rb+++ b/spree/core/app/models/spree/base.rb@@ -76,7 +76,9 @@ class Spree::Base < ApplicationRecordenddef self.json_api_columns- column_names.reject { |c| c.match(/_id$|id|preferences|(.*)password|(.*)token|(.*)api_key|^original_(.*)/) }+ # `_type` goes with `_id`: the two halves of a polymorphic reference name+ # an internal class, which is no more public than the key beside it.+ column_names.reject { |c| c.match(/_id$|id|_type$|preferences|(.*)password|(.*)token|(.*)api_key|^original_(.*)/) }enddef self.json_api_permitted_attributesdiff --git a/spree/core/app/models/spree/business_address.rb b/spree/core/app/models/spree/business_address.rbdeleted file mode 100644index bea06e8615..0000000000--- a/spree/core/app/models/spree/business_address.rb+++ /dev/null@@ -1,20 +0,0 @@-module Spree- # A seller's billing address, as a commission invoice must address it: no- # person to name, and the company is the part that cannot be left out.- #- # Shares `spree_addresses` rather than being STI — the table has no `type`- # column, and the owning association already says which kind this is.- class BusinessAddress < Spree::Address- def require_name?- false- end-- def require_company?- !quick_checkout- end-- def show_company_address_field?- true- end- end-enddiff --git a/spree/core/app/models/spree/company.rb b/spree/core/app/models/spree/company.rbindex 2fe25700f2..bba36391a4 100644--- a/spree/core/app/models/spree/company.rb+++ b/spree/core/app/models/spree/company.rb@@ -33,9 +33,12 @@ module Spreehas_many :children, class_name: 'Spree::Company', foreign_key: :parent_id,inverse_of: :parent, dependent: :destroy- has_many :company_addresses, class_name: 'Spree::CompanyAddress', dependent: :destroy,- inverse_of: :company- has_many :addresses, through: :company_addresses, class_name: 'Spree::Address'+ # The address book: rows the node owns outright, labelled per site. A+ # default is a pointer at one of them rather than a flag on the row, so+ # two entries can never both claim the same default.+ has_many :addresses, class_name: 'Spree::Address', as: :owner, dependent: :destroy+ belongs_to :default_bill_address, class_name: 'Spree::Address', optional: true+ belongs_to :default_ship_address, class_name: 'Spree::Address', optional: truehas_many :memberships, class_name: 'Spree::CompanyMembership', dependent: :destroy,inverse_of: :companyhas_many :customers, through: :memberships, class_name: Spree.customer_class.to_s@@ -58,6 +61,7 @@ module Spreevalidate :no_ancestry_cyclevalidate :depth_within_capvalidate :kind_change_keeps_tax_anchor+ validate :defaults_are_own_addresses# prepend: `dependent: :destroy` on children registers its own# before_destroy when the association is declared, so without this the@@ -173,12 +177,12 @@ module Spree## @return [Spree::Address, nil]def default_billing_address- default_address(:default_billing)+ default_address(:default_bill_address)end# @return [Spree::Address, nil]def default_shipping_address- default_address(:default_shipping)+ default_address(:default_ship_address)endprivate@@ -194,14 +198,26 @@ module Spreethrow(:abort)end- def default_address(flag)+ def default_address(attribute)self_and_ancestors.each do |node|- row = node.company_addresses.where(flag => true).first- return row.address if row+ address = node.public_send(attribute)+ return address if addressendnilend+ # A default must point at an address this node owns — otherwise it would+ # prefill checkout with another node's site.+ def defaults_are_own_addresses+ [:default_bill_address, :default_ship_address].each do |attribute|+ address = public_send(attribute)+ next if address.nil?+ next if address.owner_type == 'Spree::Company' && address.owner_id == id++ errors.add(attribute, :invalid)+ end+ end+def parent_in_same_storereturn if parent.nil? || store_id.nil?return if parent.store_id == store_iddiff --git a/spree/core/app/models/spree/company_address.rb b/spree/core/app/models/spree/company_address.rbdeleted file mode 100644index 1567eda8ae..0000000000--- a/spree/core/app/models/spree/company_address.rb+++ /dev/null@@ -1,48 +0,0 @@-module Spree- # An entry in a company node's address book — a labeled ship-to or bill-to- # site. The address row is owned outright, never shared with a customer's- # own address book, which is why it is destroyed with the entry.- #- # How many sites a node has never dictates how many nodes exist: structure- # is the tree, addresses are just addresses- # (docs/plans/6.0-b2b-companies-and-catalogs.md).- class CompanyAddress < Spree.base_class- has_prefix_id :caddr-- belongs_to :company, class_name: 'Spree::Company', inverse_of: :company_addresses- belongs_to :address, class_name: 'Spree::Address', dependent: :destroy-- # update_only, so editing one field of an existing address changes that- # row instead of building a replacement and orphaning the old one.- accepts_nested_attributes_for :address, update_only: true-- # The API reads and writes this under the same name, so the writer takes- # either a record or the nested hash a client sends.- def address=(value)- value.is_a?(Hash) || value.is_a?(ActionController::Parameters) ? self.address_attributes = value : super- end-- validates :address, presence: true-- # Demote any prior default in the same transaction so the partial unique- # index ("one default of each kind per node") never sees two TRUE rows.- # Runs before save so MySQL — which can't enforce a partial unique index —- # also arrives at a single default (same shape as Channel#default).- before_save :demote_other_default_billing, if: -> { default_billing? && will_save_change_to_default_billing? }- before_save :demote_other_default_shipping, if: -> { default_shipping? && will_save_change_to_default_shipping? }-- delegate :store, :store_id, to: :company-- self.whitelisted_ransackable_attributes = %w[label default_billing default_shipping]-- private-- def demote_other_default_billing- self.class.where(company_id: company_id, default_billing: true).where.not(id: id).update_all(default_billing: false)- end-- def demote_other_default_shipping- self.class.where(company_id: company_id, default_shipping: true).where.not(id: id).update_all(default_shipping: false)- end- end-enddiff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rbindex f7527a4a1d..b27569fce4 100644--- a/spree/core/app/models/spree/seller.rb+++ b/spree/core/app/models/spree/seller.rb@@ -60,12 +60,12 @@ module Spree# Associations#belongs_to :store, class_name: 'Spree::Store'- # Typed as the subclass so a saved address is read back with the business- # rules — otherwise editing one field of it would fail on a personal name- # nobody was ever asked for. Not `dependent: :destroy`: a seller is- # paranoid, so destroy is a soft delete, and taking the address with it- # would hard-delete a row historical commission invoices still point at.- belongs_to :billing_address, class_name: 'Spree::BusinessAddress', optional: true+ # The address knows it is a seller's from its owner, so it is read back+ # with the business rules — no personal name insisted on, the company line+ # required. Not `dependent: :destroy`: a seller is paranoid, so destroy is+ # a soft delete, and taking the address with it would hard-delete a row+ # historical commission invoices still point at.+ belongs_to :billing_address, class_name: 'Spree::Address', optional: true# `update_only` edits the existing row rather than building a replacement# and orphaning it; the association carries the saving and validation that@@ -75,16 +75,16 @@ module Spree# The API reads and writes this under one name, so the writer takes the# attributes a client sends as well as a record. Never an id: an address# carries no store of its own, so binding one by id would reach another- # store's rows. A plain Spree::Address is accepted too — the two share- # `spree_addresses` and differ only in which fields they insist on, so a- # valid row should not be refused over its Ruby class.+ # store's rows. Either way the row is stamped as this seller's, which is+ # what makes it read back with the business rules.def billing_address=(value)case valuewhen Hash, ActionController::Parameters- super(Spree::BusinessAddress.new) if billing_address.nil?+ super(Spree::Address.new(owner: self)) if billing_address.nil?self.billing_address_attributes = valuewhen Spree::Address- super(value.becomes(Spree::BusinessAddress))+ value.owner = self+ super(value)elsesuperenddiff --git a/spree/core/app/models/spree/storefront/access_policy.rb b/spree/core/app/models/spree/storefront/access_policy.rbindex 774b44dfe8..1cea6dcd52 100644--- a/spree/core/app/models/spree/storefront/access_policy.rb+++ b/spree/core/app/models/spree/storefront/access_policy.rb@@ -133,7 +133,7 @@ module Spree# Enterprise narrows this by overriding these entry points# (docs/plans/6.0-b2b-companies-and-catalogs.md).def company_record?(record)- record.is_a?(Spree::Company) || record.is_a?(Spree::CompanyAddress) ||+ record.is_a?(Spree::Company) ||record.is_a?(Spree::CompanyMembership) || record.is_a?(Spree::CompanyInvitation)end@@ -157,6 +157,11 @@ module Spree# user_id -> customer_id rename (a record with no such column is owned by# no one, so the check fails closed). Deliberately not the deprecated# `user_id` alias, which disappears with the shim in 6.1.+ #+ # A model whose owner is polymorphic (Address, whose row may belong to a+ # customer, a company or a seller) answers `customer_id` for its own+ # customer rows only, so a business-owned row is owned by no customer and+ # the check fails closed there too.def owned?(record)user.present? && record.respond_to?(:customer_id) && record.customer_id == user.idend@@ -164,7 +169,11 @@ module Spreedef owned_scope(base)return base.none if user.blank?- base.where(customer_id: user.id)+ if base.klass.column_names.include?('owner_id')+ base.where(owner_type: Spree.customer_class.to_s, owner_id: user.id)+ else+ base.where(customer_id: user.id)+ endendendenddiff --git a/spree/core/app/services/spree/addresses/create.rb b/spree/core/app/services/spree/addresses/create.rbindex 7e50571691..60ece797da 100644--- a/spree/core/app/services/spree/addresses/create.rb+++ b/spree/core/app/services/spree/addresses/create.rb@@ -10,7 +10,7 @@ module Spreedefault_shipping = address_params.key?(:is_default_shipping) ? address_params.delete(:is_default_shipping) : opts.fetch(:default_shipping, false)address = Spree::Address.new(address_params)- address.customer = user if user.present?+ address.owner = user if user.present?ApplicationRecord.transaction doif address.savediff --git a/spree/core/app/services/spree/addresses/update.rb b/spree/core/app/services/spree/addresses/update.rbindex e59b70cfd3..27333b448e 100644--- a/spree/core/app/services/spree/addresses/update.rb+++ b/spree/core/app/services/spree/addresses/update.rb@@ -32,7 +32,7 @@ module Spreeaddress_changed = address_changes.any?if !address_changed && defaults_changed?(address, default_billing, default_shipping)assign_to_user_as_default(- user: address.customer,+ user: address.customer_owner,address_id: address.id,default_billing: default_billing,default_shipping: default_shipping@@ -44,9 +44,9 @@ module Spreeif address.editable?address.update!(address_params)- if address.customer.present?+ if address.customer_owner.present?assign_to_user_as_default(- user: address.customer,+ user: address.customer_owner,address_id: address.id,default_billing: default_billing,default_shipping: default_shipping@@ -60,12 +60,12 @@ module Spreeold_address_id = address.idaddress.destroy!- if new_address.customer.present?+ if new_address.customer_owner.present?default_billing = address.is_default_billing? || default_billingdefault_shipping = address.is_default_shipping || default_shippingassign_to_user_as_default(- user: new_address.customer,+ user: new_address.customer_owner,address_id: new_address.id,default_billing: default_billing,default_shipping: default_shipping@@ -83,19 +83,20 @@ module Spree# An update that names no country keeps the one already on the address —# the edit forms post a partial set of fields.def prepare_address_params!(address, address_params)- address_params[:customer_id] = address&.customer_id+ address_params[:owner_type] = address&.owner_type+ address_params[:owner_id] = address&.owner_idaddress_params[:country_code] ||= address.country_codeaddress_params.transform_values!(&:presence)enddef reassign_incomplete_orders(old_address_id, new_address)- orders = Spree::Order.incomplete.where(customer_id: new_address.customer_id)+ orders = Spree::Order.incomplete.where(customer_id: new_address.owner_id)orders.where(ship_address_id: old_address_id).update_all(ship_address_id: new_address.id, updated_at: Time.current)orders.where(bill_address_id: old_address_id).update_all(bill_address_id: new_address.id, updated_at: Time.current)enddef defaults_changed?(address, default_billing, default_shipping)- user = address.customer+ user = address.customer_owneruser.present? && ((default_billing.present? && user.bill_address != address) ||diff --git a/spree/core/app/services/spree/imports/row_processors/customer.rb b/spree/core/app/services/spree/imports/row_processors/customer.rbindex 0323fcdb2f..aee6e74ce2 100644--- a/spree/core/app/services/spree/imports/row_processors/customer.rb+++ b/spree/core/app/services/spree/imports/row_processors/customer.rb@@ -34,7 +34,7 @@ module Spreeenddef assign_address(user)- # Save user first so the address can FK to it via user_id (has_many :addresses).+ # Save user first so the address can point at it through the polymorphic owner.user.save! if user.new_record?address = user.bill_address || user.addresses.builddiff --git a/spree/core/app/workflows/spree/customers/create.rb b/spree/core/app/workflows/spree/customers/create.rbindex 56ffb2fe83..63995db40b 100644--- a/spree/core/app/workflows/spree/customers/create.rb+++ b/spree/core/app/workflows/spree/customers/create.rb@@ -137,11 +137,11 @@ module Spree# linkage the checkout accepted.def adopt_addressesaddresses = { bill_address_id: order.bill_address, ship_address_id: order.ship_address }.- select { |_, address| address.present? && address.customer_id.nil? }+ select { |_, address| address.present? && address.owner_id.nil? }return if addresses.empty?addresses.values.uniq.each do |address|- address.update_columns(customer_id: customer.id, updated_at: Time.current)+ address.update_columns(owner_type: Spree.customer_class.to_s, owner_id: customer.id, updated_at: Time.current)endcustomer.update_columns(addresses.transform_values(&:id).merge(updated_at: Time.current))diff --git a/spree/core/db/migrate/20260728000003_rename_user_id_to_customer_id.rb b/spree/core/db/migrate/20260728000003_rename_user_id_to_customer_id.rbindex 4d08c053c9..cfd1ece432 100644--- a/spree/core/db/migrate/20260728000003_rename_user_id_to_customer_id.rb+++ b/spree/core/db/migrate/20260728000003_rename_user_id_to_customer_id.rb@@ -10,7 +10,9 @@ class RenameUserIdToCustomerId < ActiveRecord::Migration[7.2]endrename_column :spree_orders, :user_id, :customer_id- rename_column :spree_addresses, :user_id, :customer_id+ # spree_addresses is not renamed here: its owner becomes polymorphic+ # (owner_type / owner_id) in AddOwnerToSpreeAddresses, so renaming the+ # column first would be churn.rename_column :spree_credit_cards, :user_id, :customer_idrename_column :spree_store_credits, :user_id, :customer_idrename_column :spree_wishlists, :user_id, :customer_iddiff --git a/spree/core/db/migrate/20260807000001_create_spree_companies.rb b/spree/core/db/migrate/20260807000001_create_spree_companies.rbindex 21d83c7e36..d5d6dc847a 100644--- a/spree/core/db/migrate/20260807000001_create_spree_companies.rb+++ b/spree/core/db/migrate/20260807000001_create_spree_companies.rb@@ -16,32 +16,17 @@ class CreateSpreeCompanies < ActiveRecord::Migration[8.1]elset.json :metadataend+ # Which of the node's addresses to prefill with. The address book itself+ # is ordinary spree_addresses rows owned by the node, so a default is a+ # pointer at one of them — the same shape the customer+ # (bill_address_id / ship_address_id) and the seller+ # (billing_address_id) already use. Two columns cannot disagree about+ # which row is default, so nothing has to demote a previous one.+ t.bigint :default_bill_address_id+ t.bigint :default_ship_address_idt.timestampsend- # The address book: rows a node owns outright, never shared with a- # customer's own address book.- create_table :spree_company_addresses do |t|- t.references :company, null: false- t.references :address, null: false- t.string :label- t.boolean :default_billing, null: false, default: false- t.boolean :default_shipping, null: false, default: false- t.timestamps- end-- # Partial unique indexes: at most one default of each kind per node.- # Supported on Postgres and SQLite; MySQL ignores +where:+, so the model- # demotes prior defaults before save (same shape as Channel#default).- unless ActiveRecord::Base.connection.adapter_name.match?(/mysql/i)- add_index :spree_company_addresses, :company_id, unique: true,- where: 'default_billing = TRUE',- name: 'idx_company_addresses_default_billing'- add_index :spree_company_addresses, :company_id, unique: true,- where: 'default_shipping = TRUE',- name: 'idx_company_addresses_default_shipping'- end-# Membership gives a customer standing over the node and its subtree.# Always customer-backed — the not-yet-registered case is an invitation.create_table :spree_company_memberships do |t|diff --git a/spree/core/db/migrate/20260826000001_add_owner_to_spree_addresses.rb b/spree/core/db/migrate/20260826000001_add_owner_to_spree_addresses.rbnew file mode 100644index 0000000000..c59613415d--- /dev/null+++ b/spree/core/db/migrate/20260826000001_add_owner_to_spree_addresses.rb@@ -0,0 +1,30 @@+class AddOwnerToSpreeAddresses < ActiveRecord::Migration[8.1]+ def up+ # One relationship with three cardinalities: a customer's address book, a+ # company node's, and a seller's billing address. The user FK becomes the+ # first case of a polymorphic owner rather than a column the other two have+ # to work around — and what an address requires (a person's name, or a+ # company's) follows from who owns it, so the Spree::BusinessAddress+ # subclass that used to carry those rules is gone.+ add_column :spree_addresses, :owner_type, :string+ add_column :spree_addresses, :owner_id, :bigint+ add_index :spree_addresses, [:owner_type, :owner_id], name: 'index_spree_addresses_on_owner'++ Spree::Address.unscoped.where.not(user_id: nil).+ update_all(owner_type: Spree.customer_class.to_s, owner_id: Arel.sql('user_id'))++ remove_column :spree_addresses, :user_id+ end++ def down+ add_column :spree_addresses, :user_id, :bigint+ add_index :spree_addresses, :user_id, name: 'index_spree_addresses_on_user_id'++ Spree::Address.unscoped.where(owner_type: Spree.customer_class.to_s).+ update_all(user_id: Arel.sql('owner_id'))++ remove_index :spree_addresses, name: 'index_spree_addresses_on_owner'+ remove_column :spree_addresses, :owner_type+ remove_column :spree_addresses, :owner_id+ end+enddiff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rbindex 52ead788c2..c380690ea2 100644--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@ -323,7 +323,7 @@ module Spreeregister_resource(:customers, group: :customers, subjects: -> {[Spree.customer_class, Spree::Address, Spree::CreditCard, Spree::CustomerGroup,- Spree::Company, Spree::CompanyAddress, Spree::CompanyMembership,+ Spree::Company, Spree::CompanyMembership,Spree::CompanyInvitation,Spree::TaxIdentifier, Spree::TaxExemptionCertificate,Spree::CustomField]diff --git a/spree/core/lib/spree/testing_support/factories/address_factory.rb b/spree/core/lib/spree/testing_support/factories/address_factory.rbindex 6941078c6f..db116acc94 100644--- a/spree/core/lib/spree/testing_support/factories/address_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/address_factory.rb@@ -14,6 +14,11 @@ FactoryBot.define do# plain codes; country/state stay as transient value objects so specs can# keep passing them (or country_code/state_code directly).transient do+ # The owner is polymorphic; these keep the customer case readable, since+ # a customer's address book is what most specs are building.+ customer { nil }+ user { nil }+country { Spree::Country.by_iso('US') }# NY only when the country is actually the US — specs that pass a@@ -38,12 +43,18 @@ FactoryBot.define do# one; the rest just need something the country accepts.zipcode { Spree::TestingSupport::CountryPool.postal_code_for(country&.iso) }- # An address addressed to a company rather than a person — a seller's- # billing address. Shares the table with its parent, so the only- # difference is which fields it asks for.- factory :business_address, class: Spree::BusinessAddress do+ after(:build) do |address, evaluator|+ owner = evaluator.customer || evaluator.user+ address.owner = owner if owner+ end++ # An address addressed to a business rather than a person. What it asks+ # for follows from its owner, so naming one is the whole difference.+ factory :business_address do+ association :owner, factory: :sellerfirstname { nil }lastname { nil }+ company { 'Acme Industrial' }endendenddiff --git a/spree/core/lib/spree/testing_support/factories/company_factory.rb b/spree/core/lib/spree/testing_support/factories/company_factory.rbindex 4cba9690a3..35e7a41a4d 100644--- a/spree/core/lib/spree/testing_support/factories/company_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/company_factory.rb@@ -11,9 +11,11 @@ FactoryBot.define doendend- factory :company_address, class: Spree::CompanyAddress do- company- address+ # A company node's address book entry: an ordinary address the node owns.+ factory :company_address, parent: :address do+ association :owner, factory: :company+ firstname { nil }+ lastname { nil }sequence(:label) { |n| "Site #{n}" }enddiff --git a/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb b/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rbindex 1eb47cac91..799af42210 100644--- a/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb@@ -9,7 +9,7 @@ RSpec.shared_examples 'an addresses host' dolet(:user) { create(:user) }let(:address_attributes) do- attributes_for(:address).merge(user_id: nil)+ attributes_for(:address).merge(owner: nil)enddescribe '#ship_address_attributes=' do@@ -21,10 +21,10 @@ RSpec.shared_examples 'an addresses host' doendit 'reuses an identical existing address instead of creating a duplicate' do- existing = Spree::Address.create!(address_attributes.merge(user_id: user.id))+ existing = Spree::Address.create!(address_attributes.merge(owner: user))expect do- record.ship_address_attributes = address_attributes.merge(user_id: user.id)+ record.ship_address_attributes = address_attributes.merge(owner: user)end.not_to change(Spree::Address, :count)expect(record.ship_address).to eq(existing)diff --git a/spree/core/spec/models/spree/address_spec.rb b/spree/core/spec/models/spree/address_spec.rbindex e2a30c79c1..e01ac1a110 100644--- a/spree/core/spec/models/spree/address_spec.rb+++ b/spree/core/spec/models/spree/address_spec.rb@@ -40,11 +40,11 @@ describe Spree::Address, type: :model doenddescribe 'clone' do- it 'creates a copy of the address with the exception of the id, label, user_id, updated_at and created_at attributes' do+ 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,label: 'Home',- user_id: 976,+ customer: create(:customer),address1: FFaker::Address.street_address,address2: FFaker::Address.secondary_address,alternative_phone: FFaker::PhoneNumberAU.mobile_phone_number,diff --git a/spree/core/spec/models/spree/base_spec.rb b/spree/core/spec/models/spree/base_spec.rbindex 0e747d901b..638024714a 100644--- a/spree/core/spec/models/spree/base_spec.rb+++ b/spree/core/spec/models/spree/base_spec.rb@@ -59,7 +59,7 @@ describe Spree::Base doenddescribe '.json_api_permitted_attributes' do- it { expect(Spree::Address.json_api_permitted_attributes).to contain_exactly('firstname', 'lastname', 'address1', 'address2', 'city', 'zipcode', 'phone', 'country_code', 'state_code', 'state_name', 'alternative_phone', 'company', 'country_id', 'state_id', 'created_at', 'updated_at', 'customer_id', 'deleted_at', 'label', 'metadata', 'quick_checkout', 'latitude', 'longitude') }+ it { expect(Spree::Address.json_api_permitted_attributes).to contain_exactly('firstname', 'lastname', 'address1', 'address2', 'city', 'zipcode', 'phone', 'country_code', 'state_code', 'state_name', 'alternative_phone', 'company', 'country_id', 'state_id', 'created_at', 'updated_at', 'owner_id', 'owner_type', 'deleted_at', 'label', 'metadata', 'quick_checkout', 'latitude', 'longitude') }enddescribe '.additional_permitted_attributes' dodiff --git a/spree/core/spec/models/spree/company_address_spec.rb b/spree/core/spec/models/spree/company_address_spec.rbdeleted file mode 100644index cb9a3fee21..0000000000--- a/spree/core/spec/models/spree/company_address_spec.rb+++ /dev/null@@ -1,44 +0,0 @@-require 'spec_helper'--describe Spree::CompanyAddress, type: :model do- let(:store) { @default_store }- let(:company) { create(:company, store: store) }-- it 'owns its address row outright' do- entry = create(:company_address, company: company)-- expect { entry.destroy }.to change(Spree::Address, :count).by(-1)- end-- it 'accepts a nested address hash under the read name' do- entry = create(:company_address, company: company)- entry.update!(address: { city: 'Springfield' })-- expect(entry.reload.address.city).to eq('Springfield')- end-- describe 'defaults' do- it 'keeps at most one default billing entry per node' do- first = create(:company_address, company: company, default_billing: true)- second = create(:company_address, company: company, default_billing: true)-- expect(first.reload.default_billing).to be(false)- expect(second.reload.default_billing).to be(true)- end-- it 'keeps at most one default shipping entry per node' do- first = create(:company_address, company: company, default_shipping: true)- second = create(:company_address, company: company, default_shipping: true)-- expect(first.reload.default_shipping).to be(false)- expect(second.reload.default_shipping).to be(true)- end-- it 'leaves another node untouched' do- other = create(:company_address, company: create(:company, store: store), default_billing: true)- create(:company_address, company: company, default_billing: true)-- expect(other.reload.default_billing).to be(true)- end- end-enddiff --git a/spree/core/spec/models/spree/company_spec.rb b/spree/core/spec/models/spree/company_spec.rbindex 3b7fa30c94..93fb7d860a 100644--- a/spree/core/spec/models/spree/company_spec.rb+++ b/spree/core/spec/models/spree/company_spec.rb@@ -205,15 +205,17 @@ describe Spree::Company, type: :model dolet(:division) { create(:company, store: store, kind: 'division', parent: root) }it 'reads its own default first' do- own = create(:company_address, company: division, default_billing: true)+ own = create(:company_address, owner: division)+ division.update!(default_bill_address: own)- expect(division.default_billing_address).to eq(own.address)+ expect(division.default_billing_address).to eq(own)endit 'falls back to the nearest ancestor default' do- inherited = create(:company_address, company: root, default_shipping: true)+ inherited = create(:company_address, owner: root)+ root.update!(default_ship_address: inherited)- expect(division.default_shipping_address).to eq(inherited.address)+ expect(division.default_shipping_address).to eq(inherited)endit 'is nil when nobody set one' do@@ -265,11 +267,11 @@ describe Spree::Company, type: :model doit 'destroys its memberships, addresses and invitations' docompany = create(:company, store: store)create(:company_membership, company: company)- create(:company_address, company: company)+ create(:company_address, owner: company)create(:company_invitation, company: company)expect { company.destroy }.to change(Spree::CompanyMembership, :count).by(-1).- and change(Spree::CompanyAddress, :count).by(-1).+ and change(Spree::Address, :count).by(-1).and change(Spree::CompanyInvitation, :count).by(-1)endenddiff --git a/spree/core/spec/models/spree/seller_spec.rb b/spree/core/spec/models/spree/seller_spec.rbindex 54b212951c..0112d3b8af 100644--- a/spree/core/spec/models/spree/seller_spec.rb+++ b/spree/core/spec/models/spree/seller_spec.rb@@ -233,16 +233,17 @@ describe Spree::Seller docity: 'London', postal_code: 'EC1A 1BB', country_code: 'GB' })reloaded = described_class.find(seller.id)- expect(reloaded.billing_address).to be_a(Spree::BusinessAddress)+ expect(reloaded.billing_address.owner).to eq(seller)+ expect(reloaded.billing_address.require_name?).to be(false)expect(reloaded.update(billing_address: { city: 'Manchester' })).to be(true)end# A seller is paranoid, so destroy is a soft delete. Taking the addresses# with it would hard-delete rows a restored seller still points at.it 'keeps its addresses when soft-deleted, and finds them again on restore' do- seller.update!(billing_address: Spree::BusinessAddress.create!(- company: 'Sparks Trading Ltd', address1: '1 Seller Way', city: 'London',- zipcode: 'EC1A 1BB', country_code: 'GB'+ seller.update!(billing_address: Spree::Address.create!(+ owner: seller, company: 'Sparks Trading Ltd', address1: '1 Seller Way',+ city: 'London', zipcode: 'EC1A 1BB', country_code: 'GB'))address_id = seller.billing_address_iddiff --git a/spree/core/spec/models/spree/storefront/access_policy_spec.rb b/spree/core/spec/models/spree/storefront/access_policy_spec.rbindex 097bd2e2ac..a60a118f18 100644--- a/spree/core/spec/models/spree/storefront/access_policy_spec.rb+++ b/spree/core/spec/models/spree/storefront/access_policy_spec.rb@@ -91,7 +91,7 @@ RSpec.describe Spree::Storefront::AccessPolicy, type: :model doendit 'denies unowned records to everyone' do- unowned = build(:address, customer_id: nil)+ unowned = build(:address, owner: nil)expect(policy.readable?(unowned)).to be falseexpect(guest_policy.readable?(unowned)).to be falseenddiff --git a/spree/core/spec/workflows/spree/customers/create_spec.rb b/spree/core/spec/workflows/spree/customers/create_spec.rbindex 478f46899f..946b426ce8 100644--- a/spree/core/spec/workflows/spree/customers/create_spec.rb+++ b/spree/core/spec/workflows/spree/customers/create_spec.rb@@ -108,7 +108,7 @@ RSpec.describe Spree::Customers::Create doexpect(customer.ship_address).to eq(order.ship_address)expect(customer.bill_address).to eq(order.bill_address)- expect(order.bill_address.reload.customer_id).to eq(customer.id)+ expect(order.bill_address.reload.owner_id).to eq(customer.id)endit 'links the order to the customer' do@@ -119,11 +119,11 @@ RSpec.describe Spree::Customers::Create doit 'does not adopt an address that belongs to another customer' doother_customer = create(:user)- address.update_columns(customer_id: other_customer.id)+ address.update_columns(owner_type: Spree.customer_class.to_s, owner_id: other_customer.id)customer = result.value- expect(address.reload.customer_id).to eq(other_customer.id)+ expect(address.reload.owner_id).to eq(other_customer.id)expect(customer.bill_address_id).to be_nilexpect(customer.ship_address_id).to be_nilend