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
Rename User to Customer and make the auth models gem-owned
Łukasz Adamczyk443247109662
diff --git a/docs/plans/6.0-platform-auth.md b/docs/plans/6.0-platform-auth.mdindex dee3c3ec47..9c10a36e96 100644--- a/docs/plans/6.0-platform-auth.md+++ b/docs/plans/6.0-platform-auth.md@@ -1,6 +1,6 @@# Platform-Owned Authentication & User Model Rename-**Status:** In Progress (RefreshToken shipped in 5.4 ✓, rest in 6.0)+**Status:** In Progress (RefreshToken shipped in 5.4 ✓; Phases 1 & 3 implemented on `feature/v-3514` — gem-owned `Spree::Customer`/`Spree::AdminUser` models + `Spree.customer_class` rename + `user_id`→`customer_id`; Phase 2 data migration + Phases 4–6 pending)**Target:** Spree 5.4 (RefreshToken ✓) + Spree 6.0 (Devise removal, User→Customer rename)**Depends on:** Admin SPA (6.0-admin-spa.md — removes Rails admin, kills Devise dependency) for Devise removal**Author:** Damian + Claude@@ -344,6 +344,15 @@ Two supported paths:- Rename `user_id` FK → `customer_id` on 11 customer-facing tables (see decisions.md entry)- Update `belongs_to :user` → `belongs_to :customer` on those models+**Implementation notes (Phases 1 & 3, `feature/v-3514`):**+- `Spree::Customer` (new `spree_customers`, complete column set) + `Spree::AdminUser` (existing `spree_admin_users` + `password_digest`) both use `has_secure_password validations: false` with a confirmation-only validation — password presence is **not** enforced at the model level (matches the prior LegacyUser default; storefront registration / admin-claim own that), so admin-created password-less accounts stay valid. `valid_password?` kept as an `authenticate` alias.+- Prefix IDs: `cust_` (was `cus`) / `adm_` (was `admin`).+- `Spree::UserMethods` → `Spree::CustomerMethods` (absorbs `UserAddress` + `UserPaymentSource`); constant-alias file keeps the old name. Concern made column-agnostic: password-reset token key falls back through `password_salt` → `encrypted_password` → `password_digest`; `login` write guarded by `has_attribute?`.+- FK/association back-compat via a `Spree::DeprecatedCustomerAlias` concern (deprecated `user`/`user_id`/`:user` reader+writer) included on the 10 models; `spree_customer_group_users` is polymorphic so `user_type` → `customer_type` too. Model-scoped i18n error keys added under `spree/customer`.+- Historical `add_*_to_spree_users` migrations now guard on `table_exists?(Spree.customer_class.table_name)` so a fresh default install (where the complete `spree_customers` is created by its own migration) skips them cleanly, while a custom user table still gets backfilled.+- `spree/admin` left untouched (removed in 6.0) — it rides the deprecated `Spree.user_class` alias.+- **Spree's own specs use `customer` directly, not the aliases** (aliases are only to smooth external-gem migration): factory calls migrated `user:` → `customer:` for renamed-model factories (Import/Export/Report/RoleUser/RefreshToken/StateChange/UserIdentity keep `user:`), `Spree.user_class` → `Spree.customer_class`. Core `spec/models` + `spec/services` + `spec/lib` are green (7094 examples). Remaining: first-party code `.user`/`.user_id` *reads* still on aliases (functional, warn-only) + `spree/api` & `spree/emails` spec migration/runs.+### Phase 4: Refresh token support- Create `Spree::RefreshToken` modeldiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 9b7587ccdb..2313fab966 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -208,7 +208,7 @@ storefront customer (not an admin user).- `spree_payment_sources.user_id` → `customer_id`- `spree_newsletter_subscribers.user_id` → `customer_id`- `spree_promotion_rule_users.user_id` → `customer_id`-- `spree_customer_group_users.user_id` → `customer_id`+- `spree_customer_group_users.user_id` → `customer_id` (polymorphic — `user_type` also renames to `customer_type` so `belongs_to :customer, polymorphic: true` resolves)**Keep as `user_id`** (5 models — FK references Spree.admin_user_class or is polymorphic):- `spree_imports.user_id` — admin who ran the importdiff --git a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rbindex e6e2f22f2c..0db7ca880e 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb@@ -104,7 +104,7 @@ module Spreewhen USER_TYPE_ADMINSpree.admin_user_class.find(user_id)else- Spree.user_class.find(user_id)+ Spree.customer_class.find(user_id)endenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rbindex d43490340f..2784fcf596 100644--- a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb@@ -106,7 +106,7 @@ module Spreedef parent_route_map@parent_route_map ||= Spree.metafields.enabled_resources.each_with_object({}) do |klass, m|m[klass.model_name.element.to_s] = klass.name- end.merge('customer' => Spree.user_class.name, 'category' => 'Spree::Category')+ end.merge('customer' => Spree.customer_class.name, 'category' => 'Spree::Category')end# Returns the first segment whose `<segment>_id` is present in params,diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rbindex d6fb3e6130..da5f40a816 100644--- a/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb@@ -21,7 +21,7 @@ module Spree# global in Spree (`User.for_store` is a no-op), so the ability is# the only boundary here.def set_parent- @parent = Spree.user_class.+ @parent = Spree.customer_class.accessible_by(current_ability, parent_ability_action).find_by_prefix_id!(params[:customer_id])enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rbindex 7cefa62e44..679ce5193b 100644--- a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb@@ -10,10 +10,10 @@ module Spreebefore_action :require_ids!, only: [:bulk_add_to_groups, :bulk_remove_from_groups]def create- @resource = Spree.user_class.new(permitted_params)+ @resource = Spree.customer_class.new(permitted_params)# Admin-created customers don't pick a password upfront — they# claim the account via password reset later.- # `Spree::UserMethods` exposes `skip_password_validation` so+ # `Spree::CustomerMethods` exposes `skip_password_validation` so# Devise's `:validatable` lets a nil credential through on this# code path. Storefront registration never sets the flag, so# customer self-signup still requires a password.@@ -63,7 +63,7 @@ module Spreeprotecteddef model_class- Spree.user_class+ Spree.customer_classenddef serializer_classdiff --git a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rbindex 4308b227b6..8e3f647d9a 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb@@ -133,7 +133,7 @@ module Spreecustomer_param = params[:customer_id].presence || params[:user_id].presencereturn unless customer_param- Spree.user_class.find_by_param!(customer_param)+ Spree.customer_class.find_by_param!(customer_param)enddef order_create_paramsdiff --git a/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rbindex d18ce9616d..73e42a8fc0 100644--- a/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb@@ -19,7 +19,7 @@ module Spree{'Spree::Product' => 'read_products','Spree::Order' => 'read_orders',- Spree.user_class.to_s => 'read_customers'+ Spree.customer_class.to_s => 'read_customers'}enddiff --git a/spree/api/app/controllers/spree/api/v3/base_controller.rb b/spree/api/app/controllers/spree/api/v3/base_controller.rbindex 1056efd193..6973f64037 100644--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb@@ -43,7 +43,7 @@ module Spreeprotected# Override to use current_user from JWT authentication- # @return [Spree.user_class]+ # @return [Spree.customer_class]def spree_current_usercurrent_userenddiff --git a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rbindex f6f6d5fa82..980bec5cbf 100644--- a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb@@ -119,7 +119,7 @@ module Spreestrategy_class.new(params: params,request_env: request.headers.env,- user_class: Spree.user_class+ user_class: Spree.customer_class)enddiff --git a/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rbindex 9f76905f2d..9630f5893c 100644--- a/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb@@ -29,7 +29,7 @@ module Spreeendend- user = Spree.user_class.find_by(email: params[:email])+ user = Spree.customer_class.find_by(email: params[:email])if usertoken = user.generate_token_for(:password_reset)@@ -44,7 +44,7 @@ module Spree# PATCH /api/v3/store/password_resets/:iddef update- user = Spree.user_class.find_by_password_reset_token(params[:id])+ user = Spree.customer_class.find_by_password_reset_token(params[:id])unless userreturn render_error(diff --git a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rbindex f18e80866b..cf6b1153ed 100644--- a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb@@ -11,7 +11,7 @@ module Spree# POST /api/v3/store/customersdef create- user = Spree.user_class.new(permitted_params.except(:current_password))+ user = Spree.customer_class.new(permitted_params.except(:current_password))if user.savelink_matching_newsletter_subscriber!(user)diff --git a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rbindex 984d7a6324..2ad26d598b 100644--- a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb@@ -14,7 +14,7 @@ module Spreedef createsubscriber = Spree::NewsletterSubscriber.subscribe(email: params[:email],- user: current_user,+ customer: current_user,store: current_store,redirect_url: validated_redirect_url)diff --git a/spree/core/app/finders/spree/orders/find_current.rb b/spree/core/app/finders/spree/orders/find_current.rbindex 0e06ce2e58..b7c3e30d4d 100644--- a/spree/core/app/finders/spree/orders/find_current.rb+++ b/spree/core/app/finders/spree/orders/find_current.rb@@ -11,7 +11,7 @@ module Spreereturn order unless order.nil?return if user.nil?- incomplete_orders.order(created_at: :desc).find_by(store: store, user: user, currency: params[:currency])+ incomplete_orders.order(created_at: :desc).find_by(store: store, customer: user, currency: params[:currency])endprivatediff --git a/spree/core/app/models/concerns/spree/admin_user_methods.rb b/spree/core/app/models/concerns/spree/admin_user_methods.rbindex 6ff12e89ff..b26e4cb244 100644--- a/spree/core/app/models/concerns/spree/admin_user_methods.rb+++ b/spree/core/app/models/concerns/spree/admin_user_methods.rb@@ -12,7 +12,7 @@ module Spree# emails through Spree's mailer.prepend Spree::AdminUserMethods::DeviseNotifications- has_prefix_id :admin+ has_prefix_id :admhas_person_name@@ -21,10 +21,11 @@ module Spree# Token auto-invalidates when password changes (salt changes)# Expiration is configurable via Spree::Config.admin_password_reset_expires_in (in minutes)generates_token_for :password_reset, expires_in: Spree::Config.admin_password_reset_expires_in.minutes do- # `try` rather than `&.`: models without a password_salt method or- # column at all (modern Devise) must fall through to encrypted_password- # — a bare call would raise NameError before the fallback.- try(:password_salt)&.last(10) || encrypted_password&.last(10)+ # `try` rather than `&.`: a model that lacks the method/column entirely+ # must fall through rather than raise NameError. `password_salt` covers+ # has_secure_password (which derives it from password_digest);+ # `encrypted_password` covers legacy bcrypt / Devise models.+ try(:password_salt)&.last(10) || try(:encrypted_password)&.last(10)enddef self.find_by_password_reset_token(token)diff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rbnew file mode 100644index 0000000000..ba37fa18b5--- /dev/null+++ b/spree/core/app/models/concerns/spree/customer_methods.rb@@ -0,0 +1,334 @@+module Spree+ module CustomerMethods+ extend ActiveSupport::Concern++ include Spree::PrefixedId+ include Spree::Metafields+ include Spree::Metadata+ include Spree::UserAddress+ include Spree::UserPaymentSource+ include Spree::UserReporting+ include Spree::UserRoles+ include Spree::RansackableAttributes+ include Spree::Searchable+ include Spree::Publishable++ # Opt-in escape hatch for admin-side customer creation. When the host+ # `Spree::User` includes Devise's `:validatable`, password presence is+ # enforced on every create; admin-created customers don't pick a+ # password upfront — they claim the account later via password reset.+ # The admin Customers controller flips `skip_password_validation = true`+ # when no password was supplied; the storefront registration path never+ # sets it, so customer self-signup still requires a password.+ #+ # Prepended (not just defined) so it sits above Devise's own+ # `password_required?` and can fall through with `super` when the flag+ # isn't set. On `LegacyUser` (gem default, no Devise) `super` raises+ # NoMethodError if invoked — but the early return covers the only+ # branch that ever reaches this method on that path, and `LegacyUser`+ # doesn't call `password_required?` at all, so the override is a no-op+ # there.+ module SkipPasswordValidation+ def password_required?+ return false if skip_password_validation && try(:encrypted_password).blank? && password.blank?+ super+ end+ end++ included do+ has_prefix_id :cust # Stripe: cus_++ attr_accessor :skip_password_validation++ prepend SkipPasswordValidation++ # Enable lifecycle events for user models+ publishes_lifecycle_events++ # Password reset token (Rails 7.1+ signed token, no DB column needed)+ # Token auto-invalidates when password changes (salt changes)+ # Expiration is configurable via Spree::Config.customer_password_reset_expires_in (in minutes)+ generates_token_for :password_reset, expires_in: Spree::Config.customer_password_reset_expires_in.minutes do+ # `try` rather than `&.`: a model that lacks the method/column entirely+ # must fall through rather than raise NameError. `password_salt` covers+ # has_secure_password (which derives it from password_digest);+ # `encrypted_password` covers legacy bcrypt / Devise models.+ try(:password_salt)&.last(10) || try(:encrypted_password)&.last(10)+ end++ # we need to have this callback before any dependent: :destroy associations+ # https://github.com/rails/rails/issues/3458+ before_validation :clone_billing_address, if: :use_billing?+ before_destroy :check_completed_orders++ after_save_commit :sync_newsletter_subscription_with_marketing_consent,+ if: :saved_change_to_accepts_email_marketing?++ attr_accessor :use_billing++ has_person_name+ normalizes :email, :first_name, :last_name, with: ->(value) { value&.to_s&.squish&.presence }+ acts_as_taggable_on :tags++ def tags=(tags)+ self.tag_list = tags+ end++ #+ # Associations+ #+ has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser', foreign_key: :customer_id, dependent: :destroy+ has_many :promotion_rules, through: :promotion_rule_users, class_name: 'Spree::PromotionRule'+ has_many :orders, foreign_key: :customer_id, class_name: 'Spree::Order'+ has_many :carts, -> { incomplete }, foreign_key: :customer_id, class_name: 'Spree::Order'+ has_many :completed_orders, -> { complete }, foreign_key: :customer_id, class_name: 'Spree::Order'+ has_many :store_credits, class_name: 'Spree::StoreCredit', foreign_key: :customer_id, dependent: :destroy+ has_many :wishlists, class_name: 'Spree::Wishlist', foreign_key: :customer_id, dependent: :destroy+ has_many :wished_items, through: :wishlists, source: :wished_items+ has_many :gateway_customers, class_name: 'Spree::GatewayCustomer', foreign_key: :customer_id+ has_many :gift_cards, class_name: 'Spree::GiftCard', foreign_key: :customer_id, dependent: :destroy+ has_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', as: :customer, dependent: :destroy+ has_many :customer_groups, through: :customer_group_users, class_name: 'Spree::CustomerGroup'+ has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy+ belongs_to :ship_address, class_name: 'Spree::Address', optional: true+ belongs_to :bill_address, class_name: 'Spree::Address', optional: true++ # Replaces the customer's group membership. Accepts both prefixed IDs and+ # raw integer IDs. Only groups belonging to the current store are+ # assigned — ids from another store are dropped, preventing cross-store+ # membership. Mirrors +Spree::Product#category_ids=+.+ def customer_group_ids=(ids)+ decoded_ids = Array(ids).filter_map do |id|+ id.to_s.include?('_') ? Spree::CustomerGroup.decode_prefixed_id(id) : id+ end+ super(Spree::CustomerGroup.for_store(Spree::Current.store).where(id: decoded_ids).ids)+ end++ #+ # Attachments+ #+ has_one_attached :avatar, service: Spree.public_storage_service_name+ has_rich_text :internal_note++ #+ # Attributes+ #+ attr_accessor :confirm_email, :terms_of_service++ def self.find_by_password_reset_token(token)+ find_by_token_for(:password_reset, token)+ end++ def self.find_by_password_reset_token!(token)+ find_by_token_for!(:password_reset, token)+ end++ def self.search(query)+ return none if query.blank?++ # `search_condition` handles sanitization itself — it escapes LIKE+ # wildcards for plain columns and compares encrypted columns by+ # equality. Pass the raw query so it can branch correctly.+ conditions = []+ conditions << search_condition(self, :email, query)+ conditions << search_condition(self, :first_name, query)+ conditions << search_condition(self, :last_name, query)++ full_name = NameOfPerson::PersonName.full(query.to_s.strip)++ if full_name.first.present? && full_name.last.present?+ conditions << search_condition(self, :first_name, full_name.first)+ conditions << search_condition(self, :last_name, full_name.last)+ end++ where(conditions.reduce(:or))+ end++ # Backward compatibility alias — remove in Spree 6.0+ def self.multi_search(query) = search(query)++ self.whitelisted_ransackable_associations = %w[bill_address ship_address addresses tags spree_roles orders customer_groups]+ self.whitelisted_ransackable_attributes = %w[id email first_name last_name phone accepts_email_marketing+ created_at updated_at last_sign_in_at]+ self.whitelisted_ransackable_scopes = %w[search multi_search with_min_total_spent]++ scope :with_min_total_spent, ->(amount) {+ joins(:orders).where(spree_orders: { state: 'complete' }).+ group("#{table_name}.id").+ having('SUM(spree_orders.total) >= ?', amount.to_d)+ }++ # Precomputes orders_count, total_spent, and last_order_completed_at via a+ # single aggregate join so list endpoints avoid 4 queries per user. The+ # values land on the user as virtual attributes.+ scope :with_order_aggregates, -> {+ order_table = Spree::Order.table_name+ select(+ "#{table_name}.*, " \+ "COALESCE(orders_agg.orders_count, 0) AS orders_count, " \+ "COALESCE(orders_agg.total_spent, 0) AS total_spent, " \+ "orders_agg.last_order_completed_at AS last_order_completed_at"+ ).joins(+ "LEFT JOIN (" \+ "SELECT customer_id, COUNT(*) AS orders_count, SUM(total) AS total_spent, MAX(completed_at) AS last_order_completed_at " \+ "FROM #{order_table} " \+ "WHERE state = 'complete' AND customer_id IS NOT NULL " \+ "GROUP BY customer_id" \+ ") orders_agg ON orders_agg.customer_id = #{table_name}.id"+ )+ }++ def self.with_email(query)+ where("#{table_name}.email LIKE ?", "%#{query}%")+ end++ def self.with_address(query, address = :ship_address)+ left_outer_joins(address).+ where("#{Spree::Address.table_name}.firstname like ?", "%#{query}%").+ or(left_outer_joins(address).where("#{Spree::Address.table_name}.lastname like ?", "%#{query}%"))+ end++ def self.with_email_or_address(email, address)+ left_outer_joins(:addresses).+ where("#{Spree::Address.table_name}.firstname LIKE ? or #{Spree::Address.table_name}.lastname LIKE ? or #{table_name}.email LIKE ?",+ "%#{address}%", "%#{address}%", "%#{email}%")+ end++ # We override this method because we cannot use for_store on users because it will return admin users+ def self.for_store(store)+ self+ end+ end++ # Returns the last incomplete spree order for the current store+ # @param [Spree::Store] store+ # @param [Hash] options+ # @option options [Array<Symbol>] :includes+ # @return [Spree::Order]+ def last_incomplete_spree_order(store, options = {})+ orders.where(store: store).incomplete.not_canceled.+ includes(options[:includes]).+ order('created_at DESC').+ first+ end++ # Returns the total available store credit for the current store per currency+ # @param [Spree::Store] store+ # @param [String] currency+ # @return [Float]+ def total_available_store_credit(currency = nil, store = nil)+ store ||= Store.default+ currency ||= store.default_currency++ # When the association is already loaded (e.g. preloaded via the admin+ # API's scope_includes), filter in memory to avoid an N+1 — but mirror+ # the query branch exactly: non-gift-card credits, scoped to the store+ # and currency. A gift card is identified by its originator_type.+ if store_credits.loaded?+ store_credits.+ select { |sc| sc.originator_type != 'Spree::GiftCard' && sc.store_id.to_s == store.id.to_s && sc.currency == currency }.+ sum(&:amount_remaining)+ else+ store_credits.without_gift_card.for_store(store).where(currency: currency).to_a.sum(&:amount_remaining)+ end+ end++ # Returns the available store credits for the current store per currency+ # @param [Spree::Store] store+ # @return [Array<Spree::Money>]+ def available_store_credits(store)+ store ||= Store.default++ store_credits.for_store(store).pluck(:currency).uniq.each_with_object([]) do |currency, arr|+ arr << Spree::Money.new(total_available_store_credit(currency, store), currency: currency)+ end+ end++ # Returns the default wishlist for the current store+ # if no default wishlist exists, it creates one+ # @param [Spree::Store] current_store+ # @return [Spree::Wishlist]+ def default_wishlist_for_store(current_store)+ wishlists.find_by(is_default: true, store_id: current_store.id) || ActiveRecord::Base.connected_to(role: :writing) do+ wishlists.create!(store: current_store, is_default: true, name: Spree.t(:default_wishlist_name))+ end+ end++ # Returns true if the user can be deleted+ # Customers can be deleted if they have no completed orders+ # @return [Boolean]+ def can_be_deleted?+ orders.complete.none?+ end++ # Returns the CSV row representation of the user+ # @param [Spree::Store] store+ # @return [Array<String>]+ def to_csv(_store = nil)+ Spree::CSV::CustomerPresenter.new(self).call+ end++ # Returns the full name of the user+ # @return [String]+ def full_name+ name&.full+ end++ def event_serializer_class+ 'Spree::Api::V3::CustomerSerializer'.safe_constantize+ end++ def event_prefix+ if self.class == Spree.admin_user_class && Spree.admin_user_class != Spree.customer_class+ 'admin'+ else+ 'user'+ end+ end++ # @param store [Spree::Store] store to scope the lookup to; defaults to the current store+ # @return [Spree::NewsletterSubscriber, nil] this user's newsletter subscriber for the given store+ def newsletter_subscriber(store = Spree::Current.store)+ return unless store++ Spree::NewsletterSubscriber.for_store(store).find_by(customer_id: id)+ end++ private++ def check_completed_orders+ raise Spree::Core::DestroyWithOrdersError if !spree_admin? && orders.complete.present?+ end++ 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+ true+ end++ def use_billing?+ use_billing.in?([true, 'true', '1'])+ end++ # Scrambles the email and names of the user+ def scramble_email_and_names+ self.email = "#{SecureRandom.uuid}@example.net"+ self.first_name = 'Deleted'+ self.last_name = 'User'+ self.login = email if has_attribute?(:login)+ save+ end++ def sync_newsletter_subscription_with_marketing_consent+ if accepts_email_marketing?+ Spree::NewsletterSubscriber.subscribe(email: email, customer: self)+ else+ # Only remove the subscriber for the current store, mirroring the store-scoped subscribe path.+ newsletter_subscriber&.destroy+ end+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/deprecated_customer_alias.rb b/spree/core/app/models/concerns/spree/deprecated_customer_alias.rbnew file mode 100644index 0000000000..09a66e9555--- /dev/null+++ b/spree/core/app/models/concerns/spree/deprecated_customer_alias.rb@@ -0,0 +1,22 @@+module Spree+ # Deprecation shim for the 6.0 user_id -> customer_id / belongs_to :user -> :customer+ # rename. Included by customer-facing models so `.user` / `.user_id` keep working+ # for one release. Remove in Spree 6.1.+ module DeprecatedCustomerAlias+ extend ActiveSupport::Concern++ included do+ alias_attribute :user_id, :customer_id+ end++ def user+ Spree::Deprecation.warn("#{self.class}#user is deprecated and will be removed in Spree 6.1. Use #customer instead.") if defined?(Spree::Deprecation)+ customer+ end++ def user=(value)+ Spree::Deprecation.warn("#{self.class}#user= is deprecated and will be removed in Spree 6.1. Use #customer= instead.") if defined?(Spree::Deprecation)+ self.customer = value+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/user_address.rb b/spree/core/app/models/concerns/spree/user_address.rbindex 832a53fc6a..088f3c6703 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: :user_id+ class_name: 'Spree::Address', foreign_key: :customer_idvalidate :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&.user_id && self != bill_address&.user- errors.add(:ship_address_id, :belongs_to_other_user) if ship_address&.user_id && self != ship_address&.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&.customerenddef address_not_deprecated_in_completed_orderdiff --git a/spree/core/app/models/concerns/spree/user_methods.rb b/spree/core/app/models/concerns/spree/user_methods.rbindex 7ff3e11ab3..cf0a4cc1b9 100644--- a/spree/core/app/models/concerns/spree/user_methods.rb+++ b/spree/core/app/models/concerns/spree/user_methods.rb@@ -1,332 +1,7 @@module Spree- module UserMethods- extend ActiveSupport::Concern-- include Spree::PrefixedId- include Spree::Metafields- include Spree::Metadata- include Spree::UserPaymentSource- include Spree::UserReporting- include Spree::UserRoles- include Spree::RansackableAttributes- include Spree::Searchable- include Spree::Publishable-- # Opt-in escape hatch for admin-side customer creation. When the host- # `Spree::User` includes Devise's `:validatable`, password presence is- # enforced on every create; admin-created customers don't pick a- # password upfront — they claim the account later via password reset.- # The admin Customers controller flips `skip_password_validation = true`- # when no password was supplied; the storefront registration path never- # sets it, so customer self-signup still requires a password.- #- # Prepended (not just defined) so it sits above Devise's own- # `password_required?` and can fall through with `super` when the flag- # isn't set. On `LegacyUser` (gem default, no Devise) `super` raises- # NoMethodError if invoked — but the early return covers the only- # branch that ever reaches this method on that path, and `LegacyUser`- # doesn't call `password_required?` at all, so the override is a no-op- # there.- module SkipPasswordValidation- def password_required?- return false if skip_password_validation && encrypted_password.blank? && password.blank?- super- end- end-- included do- has_prefix_id :cus # Stripe: cus_-- attr_accessor :skip_password_validation-- prepend SkipPasswordValidation-- # Enable lifecycle events for user models- publishes_lifecycle_events-- # Password reset token (Rails 7.1+ signed token, no DB column needed)- # Token auto-invalidates when password changes (salt changes)- # Expiration is configurable via Spree::Config.customer_password_reset_expires_in (in minutes)- generates_token_for :password_reset, expires_in: Spree::Config.customer_password_reset_expires_in.minutes do- # `try` rather than `&.`: models without a password_salt method or- # column at all (modern Devise) must fall through to encrypted_password- # — a bare call would raise NameError before the fallback.- try(:password_salt)&.last(10) || encrypted_password&.last(10)- end-- # we need to have this callback before any dependent: :destroy associations- # https://github.com/rails/rails/issues/3458- before_validation :clone_billing_address, if: :use_billing?- before_destroy :check_completed_orders-- after_save_commit :sync_newsletter_subscription_with_marketing_consent,- if: :saved_change_to_accepts_email_marketing?-- attr_accessor :use_billing-- has_person_name- normalizes :email, :first_name, :last_name, with: ->(value) { value&.to_s&.squish&.presence }- acts_as_taggable_on :tags-- def tags=(tags)- self.tag_list = tags- end-- #- # Associations- #- has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser', foreign_key: :user_id, dependent: :destroy- has_many :promotion_rules, through: :promotion_rule_users, class_name: 'Spree::PromotionRule'- has_many :orders, foreign_key: :user_id, class_name: 'Spree::Order'- has_many :carts, -> { incomplete }, foreign_key: :user_id, class_name: 'Spree::Order'- has_many :completed_orders, -> { complete }, foreign_key: :user_id, class_name: 'Spree::Order'- has_many :store_credits, class_name: 'Spree::StoreCredit', foreign_key: :user_id, dependent: :destroy- has_many :wishlists, class_name: 'Spree::Wishlist', foreign_key: :user_id, dependent: :destroy- has_many :wished_items, through: :wishlists, source: :wished_items- has_many :gateway_customers, class_name: 'Spree::GatewayCustomer', foreign_key: :user_id- has_many :gift_cards, class_name: 'Spree::GiftCard', foreign_key: :user_id, dependent: :destroy- has_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', foreign_key: :user_id, as: :user, dependent: :destroy- has_many :customer_groups, through: :customer_group_users, class_name: 'Spree::CustomerGroup'- has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy- belongs_to :ship_address, class_name: 'Spree::Address', optional: true- belongs_to :bill_address, class_name: 'Spree::Address', optional: true-- # Replaces the customer's group membership. Accepts both prefixed IDs and- # raw integer IDs. Only groups belonging to the current store are- # assigned — ids from another store are dropped, preventing cross-store- # membership. Mirrors +Spree::Product#category_ids=+.- def customer_group_ids=(ids)- decoded_ids = Array(ids).filter_map do |id|- id.to_s.include?('_') ? Spree::CustomerGroup.decode_prefixed_id(id) : id- end- super(Spree::CustomerGroup.for_store(Spree::Current.store).where(id: decoded_ids).ids)- end-- #- # Attachments- #- has_one_attached :avatar, service: Spree.public_storage_service_name- has_rich_text :internal_note-- #- # Attributes- #- attr_accessor :confirm_email, :terms_of_service-- def self.find_by_password_reset_token(token)- find_by_token_for(:password_reset, token)- end-- def self.find_by_password_reset_token!(token)- find_by_token_for!(:password_reset, token)- end-- def self.search(query)- return none if query.blank?-- # `search_condition` handles sanitization itself — it escapes LIKE- # wildcards for plain columns and compares encrypted columns by- # equality. Pass the raw query so it can branch correctly.- conditions = []- conditions << search_condition(self, :email, query)- conditions << search_condition(self, :first_name, query)- conditions << search_condition(self, :last_name, query)-- full_name = NameOfPerson::PersonName.full(query.to_s.strip)-- if full_name.first.present? && full_name.last.present?- conditions << search_condition(self, :first_name, full_name.first)- conditions << search_condition(self, :last_name, full_name.last)- end-- where(conditions.reduce(:or))- end-- # Backward compatibility alias — remove in Spree 6.0- def self.multi_search(query) = search(query)-- self.whitelisted_ransackable_associations = %w[bill_address ship_address addresses tags spree_roles orders customer_groups]- self.whitelisted_ransackable_attributes = %w[id email first_name last_name phone accepts_email_marketing- created_at updated_at last_sign_in_at]- self.whitelisted_ransackable_scopes = %w[search multi_search with_min_total_spent]-- scope :with_min_total_spent, ->(amount) {- joins(:orders).where(spree_orders: { state: 'complete' }).- group("#{table_name}.id").- having('SUM(spree_orders.total) >= ?', amount.to_d)- }-- # Precomputes orders_count, total_spent, and last_order_completed_at via a- # single aggregate join so list endpoints avoid 4 queries per user. The- # values land on the user as virtual attributes.- scope :with_order_aggregates, -> {- order_table = Spree::Order.table_name- select(- "#{table_name}.*, " \- "COALESCE(orders_agg.orders_count, 0) AS orders_count, " \- "COALESCE(orders_agg.total_spent, 0) AS total_spent, " \- "orders_agg.last_order_completed_at AS last_order_completed_at"- ).joins(- "LEFT JOIN (" \- "SELECT user_id, COUNT(*) AS orders_count, SUM(total) AS total_spent, MAX(completed_at) AS last_order_completed_at " \- "FROM #{order_table} " \- "WHERE state = 'complete' AND user_id IS NOT NULL " \- "GROUP BY user_id" \- ") orders_agg ON orders_agg.user_id = #{table_name}.id"- )- }-- def self.with_email(query)- where("#{table_name}.email LIKE ?", "%#{query}%")- end-- def self.with_address(query, address = :ship_address)- left_outer_joins(address).- where("#{Spree::Address.table_name}.firstname like ?", "%#{query}%").- or(left_outer_joins(address).where("#{Spree::Address.table_name}.lastname like ?", "%#{query}%"))- end-- def self.with_email_or_address(email, address)- left_outer_joins(:addresses).- where("#{Spree::Address.table_name}.firstname LIKE ? or #{Spree::Address.table_name}.lastname LIKE ? or #{table_name}.email LIKE ?",- "%#{address}%", "%#{address}%", "%#{email}%")- end-- # We override this method because we cannot use for_store on users because it will return admin users- def self.for_store(store)- self- end- end-- # Returns the last incomplete spree order for the current store- # @param [Spree::Store] store- # @param [Hash] options- # @option options [Array<Symbol>] :includes- # @return [Spree::Order]- def last_incomplete_spree_order(store, options = {})- orders.where(store: store).incomplete.not_canceled.- includes(options[:includes]).- order('created_at DESC').- first- end-- # Returns the total available store credit for the current store per currency- # @param [Spree::Store] store- # @param [String] currency- # @return [Float]- def total_available_store_credit(currency = nil, store = nil)- store ||= Store.default- currency ||= store.default_currency-- # When the association is already loaded (e.g. preloaded via the admin- # API's scope_includes), filter in memory to avoid an N+1 — but mirror- # the query branch exactly: non-gift-card credits, scoped to the store- # and currency. A gift card is identified by its originator_type.- if store_credits.loaded?- store_credits.- select { |sc| sc.originator_type != 'Spree::GiftCard' && sc.store_id.to_s == store.id.to_s && sc.currency == currency }.- sum(&:amount_remaining)- else- store_credits.without_gift_card.for_store(store).where(currency: currency).to_a.sum(&:amount_remaining)- end- end-- # Returns the available store credits for the current store per currency- # @param [Spree::Store] store- # @return [Array<Spree::Money>]- def available_store_credits(store)- store ||= Store.default-- store_credits.for_store(store).pluck(:currency).uniq.each_with_object([]) do |currency, arr|- arr << Spree::Money.new(total_available_store_credit(currency, store), currency: currency)- end- end-- # Returns the default wishlist for the current store- # if no default wishlist exists, it creates one- # @param [Spree::Store] current_store- # @return [Spree::Wishlist]- def default_wishlist_for_store(current_store)- wishlists.find_by(is_default: true, store_id: current_store.id) || ActiveRecord::Base.connected_to(role: :writing) do- wishlists.create!(store: current_store, is_default: true, name: Spree.t(:default_wishlist_name))- end- end-- # Returns true if the user can be deleted- # Customers can be deleted if they have no completed orders- # @return [Boolean]- def can_be_deleted?- orders.complete.none?- end-- # Returns the CSV row representation of the user- # @param [Spree::Store] store- # @return [Array<String>]- def to_csv(_store = nil)- Spree::CSV::CustomerPresenter.new(self).call- end-- # Returns the full name of the user- # @return [String]- def full_name- name&.full- end-- def event_serializer_class- 'Spree::Api::V3::CustomerSerializer'.safe_constantize- end-- def event_prefix- if self.class == Spree.admin_user_class && Spree.admin_user_class != Spree.user_class- 'admin'- else- 'user'- end- end-- # @param store [Spree::Store] store to scope the lookup to; defaults to the current store- # @return [Spree::NewsletterSubscriber, nil] this user's newsletter subscriber for the given store- def newsletter_subscriber(store = Spree::Current.store)- return unless store-- Spree::NewsletterSubscriber.for_store(store).find_by(user_id: id)- end-- private-- def check_completed_orders- raise Spree::Core::DestroyWithOrdersError if !spree_admin? && orders.complete.present?- end-- 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- true- end-- def use_billing?- use_billing.in?([true, 'true', '1'])- end-- # Scrambles the email and names of the user- def scramble_email_and_names- self.email = "#{SecureRandom.uuid}@example.net"- self.first_name = 'Deleted'- self.last_name = 'User'- self.login = email- save- end-- def sync_newsletter_subscription_with_marketing_consent- if accepts_email_marketing?- Spree::NewsletterSubscriber.subscribe(email: email, user: self)- else- # Only remove the subscriber for the current store, mirroring the store-scoped subscribe path.- newsletter_subscriber&.destroy- end- end- end+ # Deprecation alias for Spree::CustomerMethods, renamed from Spree::UserMethods in 6.0.+ # True constant alias — the underlying module, its associations, and prefix (cust)+ # are all Spree::CustomerMethods. Remove in Spree 6.1.+ UserMethods = CustomerMethods+ Spree::Deprecation.warn('Spree::UserMethods is deprecated and will be removed in Spree 6.1. Use Spree::CustomerMethods instead.')enddiff --git a/spree/core/app/models/concerns/spree/user_payment_source.rb b/spree/core/app/models/concerns/spree/user_payment_source.rbindex eb7b69ad07..40a01927c5 100644--- a/spree/core/app/models/concerns/spree/user_payment_source.rb+++ b/spree/core/app/models/concerns/spree/user_payment_source.rb@@ -3,7 +3,7 @@ module Spreeextend ActiveSupport::Concernincluded do- has_many :credit_cards, class_name: 'Spree::CreditCard', foreign_key: :user_id, dependent: :destroy+ has_many :credit_cards, class_name: 'Spree::CreditCard', foreign_key: :customer_id, dependent: :destroyhas_many :payment_setup_sessions, class_name: 'Spree::PaymentSetupSession', foreign_key: :customer_id, dependent: :destroydef default_credit_carddiff --git a/spree/core/app/models/spree/ability.rb b/spree/core/app/models/spree/ability.rbindex 601730c794..0ca5c80ba9 100644--- a/spree/core/app/models/spree/ability.rb+++ b/spree/core/app/models/spree/ability.rb@@ -24,7 +24,7 @@ module Spreedef initialize(user, options = {})alias_cancan_delete_action- @user = user || Spree.user_class.new+ @user = user || Spree.customer_class.new@store = options[:store] || Spree::Current.storeapply_permissions_from_setsdiff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rbindex dfc37a6036..e794a80691 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 user_id public_metadata private_metadata)+ EXCLUDED_KEYS_FOR_COMPARISON = %w(id updated_at created_at deleted_at label customer_id public_metadata private_metadata)if defined?(Spree::Security::Addresses)include Spree::Security::Addressesend@@ -42,7 +42,8 @@ module Spreebelongs_to :country, class_name: 'Spree::Country'belongs_to :state, class_name: 'Spree::State', optional: true# we need a safe operator here as Address is added to metafield_enabled_resources in Engine- belongs_to :user, class_name: Spree.user_class&.name, optional: true, touch: true+ belongs_to :customer, class_name: Spree.customer_class&.name, optional: true, touch: true+ include Spree::DeprecatedCustomerAliashas_many :shipments, inverse_of: :address@@ -68,7 +69,7 @@ module Spreevalidate :address_validators, on: [:create, :update]validates :label, uniqueness: { conditions: -> { where(deleted_at: nil) },- scope: :user_id,+ scope: :customer_id,case_sensitive: false,allow_blank: true,allow_nil: true }@@ -97,7 +98,7 @@ module Spreeendself.whitelisted_ransackable_attributes = ADDRESS_FIELDS- self.whitelisted_ransackable_associations = %w[country state user]+ self.whitelisted_ransackable_associations = %w[country state customer]def self.required_fieldsSpree::Address.validators.map do |v|@@ -367,7 +368,7 @@ module Spreeenddef unassign_from_incomplete_orders- orders = Spree::Order.incomplete.where(user_id: user_id)+ orders = Spree::Order.incomplete.where(customer_id: customer_id)orders.where(ship_address_id: id).update_all(ship_address_id: nil, state: 'address', updated_at: Time.current)orders.where(bill_address_id: id).update_all(bill_address_id: nil, state: 'address', updated_at: Time.current)enddiff --git a/spree/core/app/models/spree/admin_user.rb b/spree/core/app/models/spree/admin_user.rbnew file mode 100644index 0000000000..8f3e4fec1d--- /dev/null+++ b/spree/core/app/models/spree/admin_user.rb@@ -0,0 +1,41 @@+# Default staff/admin model.+# Ships in the gem with has_secure_password on the existing spree_admin_users table.+module Spree+ class AdminUser < Spree.base_class+ self.table_name = 'spree_admin_users'++ has_secure_password validations: false++ include Spree::AdminUserMethods++ validates :email, presence: true, uniqueness: { case_sensitive: false }+ validates :password, confirmation: true, length: { maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, allow_blank: true++ attribute :failed_attempts, :integer, default: 0++ # Back-compat with callers and auth strategies that check +valid_password?+.+ # Guards a blank digest (password-less accounts) so it returns false instead+ # of raising BCrypt::Errors::InvalidHash on older Rails/bcrypt versions.+ # @param password [String]+ # @return [Boolean]+ def valid_password?(password)+ return false if password_digest.blank?++ authenticate(password).present?+ end++ # @return [Boolean] whether the account is currently locked out+ def locked?+ locked_at.present? && locked_at > 30.minutes.ago+ end++ def record_failed_attempt!+ increment!(:failed_attempts)+ update!(locked_at: Time.current) if failed_attempts >= 5+ end++ def reset_failed_attempts!+ update!(failed_attempts: 0, locked_at: nil)+ end+ end+enddiff --git a/spree/core/app/models/spree/authentication/strategies/base_strategy.rb b/spree/core/app/models/spree/authentication/strategies/base_strategy.rbindex 6b332ab0ec..2118227d23 100644--- a/spree/core/app/models/spree/authentication/strategies/base_strategy.rb+++ b/spree/core/app/models/spree/authentication/strategies/base_strategy.rb@@ -7,7 +7,7 @@ module Spreedef initialize(params:, request_env:, user_class: nil)@params = params@request_env = request_env- @user_class = user_class || Spree.user_class+ @user_class = user_class || Spree.customer_classend# Returns Result object with user on successdiff --git a/spree/core/app/models/spree/credit_card.rb b/spree/core/app/models/spree/credit_card.rbindex eaa28beafe..d5faa91188 100644--- a/spree/core/app/models/spree/credit_card.rb+++ b/spree/core/app/models/spree/credit_card.rb@@ -13,7 +13,8 @@ module Spreeacts_as_paranoidbelongs_to :payment_method- belongs_to :user, class_name: Spree.user_class.to_s, foreign_key: 'user_id', optional: true+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true+ include Spree::DeprecatedCustomerAliasbelongs_to :gateway_customer, class_name: 'Spree::GatewayCustomer', optional: truehas_many :payments, as: :sourcediff --git a/spree/core/app/models/spree/customer.rb b/spree/core/app/models/spree/customer.rbnew file mode 100644index 0000000000..839d660ded--- /dev/null+++ b/spree/core/app/models/spree/customer.rb@@ -0,0 +1,48 @@+# Default storefront customer model.+#+# Ships in the gem with has_secure_password; apps needing extra columns add their+# own migrations against spree_customers or point Spree.customer_class at a custom+# model that includes Spree::CustomerMethods.+module Spree+ class Customer < Spree.base_class+ self.table_name = 'spree_customers'++ # `validations: false` — password presence is not enforced at the model level+ # (mirrors the previous LegacyUser default); storefront registration owns that+ # requirement, and admin-created customers claim their account via password reset.+ has_secure_password validations: false++ include Spree::CustomerMethods++ validates :email, presence: true, uniqueness: { case_sensitive: false }+ validates :password, confirmation: true, length: { maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, allow_blank: true++ attribute :failed_attempts, :integer, default: 0+ attribute :accepts_email_marketing, :boolean, default: false++ # Back-compat with callers and auth strategies that check +valid_password?+.+ # Guards a blank digest (password-less accounts) so it returns false instead+ # of raising BCrypt::Errors::InvalidHash on older Rails/bcrypt versions.+ # @param password [String]+ # @return [Boolean]+ def valid_password?(password)+ return false if password_digest.blank?++ authenticate(password).present?+ end++ # @return [Boolean] whether the account is currently locked out+ def locked?+ locked_at.present? && locked_at > 30.minutes.ago+ end++ def record_failed_attempt!+ increment!(:failed_attempts)+ update!(locked_at: Time.current) if failed_attempts >= 5+ end++ def reset_failed_attempts!+ update!(failed_attempts: 0, locked_at: nil)+ end+ end+enddiff --git a/spree/core/app/models/spree/customer_group.rb b/spree/core/app/models/spree/customer_group.rbindex cbc0b24899..ead3e027a1 100644--- a/spree/core/app/models/spree/customer_group.rb+++ b/spree/core/app/models/spree/customer_group.rb@@ -9,12 +9,12 @@ module Spree#belongs_to :store, class_name: 'Spree::Store', inverse_of: :customer_groupshas_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', dependent: :destroy- has_many :users, through: :customer_group_users, source: :user, source_type: Spree.user_class.to_s+ has_many :users, through: :customer_group_users, source: :customer, source_type: Spree.customer_class.to_s# `customers` is the public name across the v3 API; declaring it as its# own association (rather than `alias_method`) is what lets `customer_ids=`# exist and what makes the `PrefixedId` auto-decoder in `assign_attributes`# recognise the key — that lookup keys off `reflect_on_association(:customers)`.- has_many :customers, through: :customer_group_users, source: :user, source_type: Spree.user_class.to_s+ has_many :customers, through: :customer_group_users, source: :customer, source_type: Spree.customer_class.to_s## Validations@@ -46,10 +46,10 @@ module Spreereturn 0 if user_ids.empty?# Get existing user IDs to avoid duplicates- existing_user_ids = customer_group_users.where(user_id: user_ids).pluck(:user_id).map(&:to_s).to_set+ existing_user_ids = customer_group_users.where(customer_id: user_ids).pluck(:customer_id).map(&:to_s).to_setnow = Time.current- user_type = Spree.user_class.to_s+ user_type = Spree.customer_class.to_srecords_to_insert = user_ids.filter_map do |user_id|next if existing_user_ids.include?(user_id)@@ -97,7 +97,7 @@ module Spreedef touch_users(user_ids)return if user_ids.blank?- Spree.user_class.where(id: user_ids).touch_all+ Spree.customer_class.where(id: user_ids).touch_allendendenddiff --git a/spree/core/app/models/spree/customer_group_user.rb b/spree/core/app/models/spree/customer_group_user.rbindex 330f7704b8..d25f62bfaf 100644--- a/spree/core/app/models/spree/customer_group_user.rb+++ b/spree/core/app/models/spree/customer_group_user.rb@@ -4,13 +4,16 @@ module Spree# Associations#belongs_to :customer_group, class_name: 'Spree::CustomerGroup'- belongs_to :user, polymorphic: true+ belongs_to :customer, polymorphic: true++ include Spree::DeprecatedCustomerAlias+ alias_attribute :user_type, :customer_type## Validations#validates :customer_group, presence: true- validates :user, presence: true- validates :customer_group_id, uniqueness: { scope: [:user_id, :user_type] }+ validates :customer, presence: true+ validates :customer_group_id, uniqueness: { scope: [:customer_id, :customer_type] }endenddiff --git a/spree/core/app/models/spree/export.rb b/spree/core/app/models/spree/export.rbindex 8aeac50436..e5b09da4b2 100644--- a/spree/core/app/models/spree/export.rb+++ b/spree/core/app/models/spree/export.rb@@ -182,7 +182,7 @@ module Spree# eg. Spree::Exports::Products => Spree::Productdef model_classif type == 'Spree::Exports::Customers'- Spree.user_class+ Spree.customer_classelse"Spree::#{type.demodulize.singularize}".constantizeenddiff --git a/spree/core/app/models/spree/gateway/custom_payment_source_method.rb b/spree/core/app/models/spree/gateway/custom_payment_source_method.rbindex ed647f5f5f..c548c31360 100644--- a/spree/core/app/models/spree/gateway/custom_payment_source_method.rb+++ b/spree/core/app/models/spree/gateway/custom_payment_source_method.rb@@ -31,7 +31,7 @@ module Spree# simulate a 3rd party payment gateway api to fetch/or create a customerdef find_or_create_customer(user)- gateway_customers.find_or_create_by!(user: user, profile_id: "CUSTOMER-#{user.id}")+ gateway_customers.find_or_create_by!(customer: user, profile_id: "CUSTOMER-#{user.id}")endendenddiff --git a/spree/core/app/models/spree/gateway_customer.rb b/spree/core/app/models/spree/gateway_customer.rbindex f5d79b6c72..666285dd81 100644--- a/spree/core/app/models/spree/gateway_customer.rb+++ b/spree/core/app/models/spree/gateway_customer.rb@@ -3,7 +3,8 @@ module Spreehas_prefix_id :gcusbelongs_to :payment_method, class_name: 'Spree::PaymentMethod'- belongs_to :user, class_name: Spree.user_class.to_s+ belongs_to :customer, class_name: Spree.customer_class.to_s+ include Spree::DeprecatedCustomerAliasvalidates :payment_method, presence: truevalidates :user, presence: truediff --git a/spree/core/app/models/spree/gift_card.rb b/spree/core/app/models/spree/gift_card.rbindex 1afee7da9f..6ece607b93 100644--- a/spree/core/app/models/spree/gift_card.rb+++ b/spree/core/app/models/spree/gift_card.rb@@ -43,13 +43,14 @@ module Spree# Associations#belongs_to :store, class_name: 'Spree::Store'- belongs_to :user, class_name: Spree.user_class.to_s, optional: true+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true+ include Spree::DeprecatedCustomerAliasbelongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: truebelongs_to :batch, class_name: 'Spree::GiftCardBatch', optional: true, foreign_key: :gift_card_batch_idhas_many :store_credits, class_name: 'Spree::StoreCredit', as: :originatorhas_many :orders, inverse_of: :gift_card, class_name: 'Spree::Order'- has_many :users, through: :orders, class_name: Spree.user_class.to_s+ has_many :users, through: :orders, source: :customer## Scopes@@ -62,7 +63,7 @@ module Spree## Ransack#- self.whitelisted_ransackable_attributes = %w[code user_id state gift_card_batch_id created_by_id]+ self.whitelisted_ransackable_attributes = %w[code customer_id user_id state gift_card_batch_id created_by_id]self.whitelisted_ransackable_associations = %w[users orders batch]self.whitelisted_ransackable_scopes = %w[active expired redeemed partially_redeemed]@@ -93,7 +94,7 @@ module Spreeamount - amount_used - amount_authorizedend- delegate :email, to: :user, prefix: true, allow_nil: true+ delegate :email, to: :customer, prefix: true, allow_nil: truedef self.json_api_columns%w[code amount expires_at]diff --git a/spree/core/app/models/spree/import.rb b/spree/core/app/models/spree/import.rbindex 0294802dc4..88ebb14b37 100644--- a/spree/core/app/models/spree/import.rb+++ b/spree/core/app/models/spree/import.rb@@ -239,7 +239,7 @@ module Spree# @return [Class]def model_classif type == 'Spree::Imports::Customers'- Spree.user_class+ Spree.customer_classelse"Spree::#{type.demodulize.singularize}".safe_constantizeend@@ -454,7 +454,7 @@ module Spree# eg. Spree::Imports::Orders => Spree::Orderdef model_class- return Spree.user_class if to_s == 'Spree::Imports::Customers'+ return Spree.customer_class if to_s == 'Spree::Imports::Customers'klass = "Spree::#{to_s.demodulize.singularize}".safe_constantizediff --git a/spree/core/app/models/spree/legacy_user.rb b/spree/core/app/models/spree/legacy_user.rbindex 850e8ff5b4..60eaa17cb7 100644--- a/spree/core/app/models/spree/legacy_user.rb+++ b/spree/core/app/models/spree/legacy_user.rb@@ -5,7 +5,7 @@ module Spreeclass LegacyUser < Spree.base_classinclude Spree::UserAddressinclude Spree::UserPaymentSource- include Spree::UserMethods+ include Spree::CustomerMethodsself.table_name = 'spree_users'@@ -17,7 +17,7 @@ module Spreebefore_save :encrypt_password, if: :password# Simple password validation for testing purposes- # In production, Spree.user_class should be overridden with a proper auth solution (e.g., Devise)+ # In production, Spree.customer_class should be overridden with a proper auth solution (e.g., Devise)def valid_password?(check_password)return false if encrypted_password.blank?diff --git a/spree/core/app/models/spree/newsletter_subscriber.rb b/spree/core/app/models/spree/newsletter_subscriber.rbindex cd0982586d..d5ec1633d1 100644--- a/spree/core/app/models/spree/newsletter_subscriber.rb+++ b/spree/core/app/models/spree/newsletter_subscriber.rb@@ -16,9 +16,11 @@ module Spree## Associations#- belongs_to :user, optional: true, class_name: Spree.user_class&.name+ belongs_to :customer, optional: true, class_name: Spree.customer_class&.namebelongs_to :store, class_name: 'Spree::Store', required: true+ include Spree::DeprecatedCustomerAlias+## Validations#@@ -46,7 +48,7 @@ module Spreeself.whitelisted_ransackable_scopes = %w[verified unverified]def accepts_email_marketing- return user.accepts_email_marketing if user.present?+ return customer.accepts_email_marketing if customer.present?verified?end@@ -59,12 +61,12 @@ module SpreeSpree::CSV::NewsletterSubscriberPresenter.new(self).callend- def self.subscribe(email:, user: nil, store: nil, redirect_url: nil)+ def self.subscribe(email:, customer: nil, store: nil, redirect_url: nil)store ||= Spree::Current.storeSpree::Newsletter::Subscribe.new(email: email,- current_user: user,+ current_user: customer,current_store: store,redirect_url: redirect_url).calldiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 2d08a35a86..5e808c42da 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -112,7 +112,7 @@ module Spreego_to_state :completeend- self.whitelisted_ransackable_associations = %w[shipments user created_by approver canceler promotions bill_address ship_address line_items store channel tags]+ self.whitelisted_ransackable_associations = %w[shipments customer created_by approver canceler promotions bill_address ship_address line_items store channel tags]self.whitelisted_ransackable_attributes = %w[completed_at email number state status payment_state shipment_statetotal item_total item_count considered_risky channel_id currency@@ -143,12 +143,11 @@ module Spreeself.tag_list = tagsend- ASSOCIATED_USER_ATTRIBUTES = [:user_id, :email, :bill_address_id, :ship_address_id]+ ASSOCIATED_USER_ATTRIBUTES = [:customer_id, :email, :bill_address_id, :ship_address_id]- # 6.0 forward-compat: User→Customer rename. Column stays user_id in 5.x.- alias_attribute :customer_id, :user_id+ include Spree::DeprecatedCustomerAlias- belongs_to :user, class_name: "::#{Spree.user_class}", optional: true, autosave: true+ belongs_to :customer, class_name: "::#{Spree.customer_class}", optional: true, autosave: truebelongs_to :created_by, class_name: "::#{Spree.admin_user_class}", optional: truebelongs_to :approver, class_name: "::#{Spree.admin_user_class}", optional: truebelongs_to :canceler, class_name: "::#{Spree.admin_user_class}", optional: true@@ -553,7 +552,7 @@ module Spree# Associates the specified user with the order.# Delegates to {Spree::Cart::Associate} service.#- # @param user [Spree.user_class] the user to associate with the order+ # @param user [Spree.customer_class] the user to associate with the order# @param override_email [Boolean] whether to override the order email with the user's email# @return [Spree::ServiceModule::Result]def associate_user!(user, override_email = true)@@ -927,7 +926,7 @@ module Spree# Cancels the order and records the canceler.# Delegates to {Spree::Orders::Cancel} service.#- # @param user [Spree.user_class, nil] the user who canceled the order+ # @param user [Spree.customer_class, nil] the user who canceled the order# @param canceled_at [Time, nil] the time of cancellation (defaults to current time)# @return [Spree::ServiceModule::Result]def canceled_by(user, canceled_at = nil)@@ -937,7 +936,7 @@ module Spree# Approves the order and records the approver.# Delegates to {Spree::Orders::Approve} service.#- # @param user [Spree.user_class, nil] the user who approved the order+ # @param user [Spree.customer_class, nil] the user who approved the order# @return [Spree::ServiceModule::Result]def approved_by(user = nil)Spree.order_approve_service.call(order: self, approver: user)diff --git a/spree/core/app/models/spree/order/checkout.rb b/spree/core/app/models/spree/order/checkout.rbindex 276763ef00..904e80947c 100644--- a/spree/core/app/models/spree/order/checkout.rb+++ b/spree/core/app/models/spree/order/checkout.rb@@ -135,7 +135,7 @@ module Spreedef subscribe_to_newsletterreturn unless accept_marketing?- Spree::NewsletterSubscriber.subscribe(email: email, user: user, store: store)+ Spree::NewsletterSubscriber.subscribe(email: email, customer: customer, store: store)enddef self.go_to_state(name, options = {})diff --git a/spree/core/app/models/spree/payment_session.rb b/spree/core/app/models/spree/payment_session.rbindex d6f52b7312..cd73f157c8 100644--- a/spree/core/app/models/spree/payment_session.rb+++ b/spree/core/app/models/spree/payment_session.rb@@ -12,7 +12,7 @@ module Spreebelongs_to :order, class_name: 'Spree::Order'belongs_to :payment_method, class_name: 'Spree::PaymentMethod'- belongs_to :customer, class_name: Spree.user_class.to_s, optional: true+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: truehas_one :payment, class_name: 'Spree::Payment',foreign_key: :response_code,diff --git a/spree/core/app/models/spree/payment_setup_session.rb b/spree/core/app/models/spree/payment_setup_session.rbindex 9b2f333405..33ac8de864 100644--- a/spree/core/app/models/spree/payment_setup_session.rb+++ b/spree/core/app/models/spree/payment_setup_session.rb@@ -10,7 +10,7 @@ module Spreepublishes_lifecycle_events- belongs_to :customer, class_name: Spree.user_class.to_s, optional: true+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: truebelongs_to :payment_method, class_name: 'Spree::PaymentMethod'belongs_to :payment_source, polymorphic: true, optional: truediff --git a/spree/core/app/models/spree/payment_source.rb b/spree/core/app/models/spree/payment_source.rbindex 0860acbcfe..4e468e5a9b 100644--- a/spree/core/app/models/spree/payment_source.rb+++ b/spree/core/app/models/spree/payment_source.rb@@ -11,7 +11,8 @@ module Spree# Associations#belongs_to :payment_method, class_name: 'Spree::PaymentMethod'- belongs_to :user, class_name: Spree.user_class.to_s, optional: true+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true+ include Spree::DeprecatedCustomerAlias## Validations@@ -26,9 +27,9 @@ module Spree# Returns the gateway customer for the user.# @return [Spree::GatewayCustomer]def gateway_customer- return if user.blank?+ return if customer.blank?- payment_method.gateway_customers.find_by(user: user)+ payment_method.gateway_customers.find_by(customer: customer)endendenddiff --git a/spree/core/app/models/spree/permission_sets/default_customer.rb b/spree/core/app/models/spree/permission_sets/default_customer.rbindex 5cbabd4f8b..40715ad1a2 100644--- a/spree/core/app/models/spree/permission_sets/default_customer.rb+++ b/spree/core/app/models/spree/permission_sets/default_customer.rb@@ -47,8 +47,8 @@ module Spreeend# User account management - available to all users (including guests for their own record)- can :create, Spree.user_class- can [:show, :update, :destroy], Spree.user_class, id: user.id+ can :create, Spree.customer_class+ can [:show, :update, :destroy], Spree.customer_class, id: user.id# Address management - only for persisted users with matching user_idcan :manage, Spree::Address, user_id: user.id if user.persisted?diff --git a/spree/core/app/models/spree/permission_sets/user_display.rb b/spree/core/app/models/spree/permission_sets/user_display.rbindex 1aa3911e25..dc376642b5 100644--- a/spree/core/app/models/spree/permission_sets/user_display.rb+++ b/spree/core/app/models/spree/permission_sets/user_display.rb@@ -10,7 +10,7 @@ module Spreemodule PermissionSetsclass UserDisplay < Basedef activate!- can [:read, :admin, :index], Spree.user_class+ can [:read, :admin, :index], Spree.customer_classcan [:read, :admin], Spree::Addresscan [:read, :admin], Spree::CreditCardenddiff --git a/spree/core/app/models/spree/permission_sets/user_management.rb b/spree/core/app/models/spree/permission_sets/user_management.rbindex f59df27d78..b96f600417 100644--- a/spree/core/app/models/spree/permission_sets/user_management.rb+++ b/spree/core/app/models/spree/permission_sets/user_management.rb@@ -10,7 +10,7 @@ module Spreemodule PermissionSetsclass UserManagement < Basedef activate!- can :manage, Spree.user_class+ can :manage, Spree.customer_classcan :manage, Spree::Addresscan :manage, Spree::CreditCardcan [:read, :admin], Spree::Metafielddiff --git a/spree/core/app/models/spree/price_rules/user_rule.rb b/spree/core/app/models/spree/price_rules/user_rule.rbindex 72953c17b9..26020092cc 100644--- a/spree/core/app/models/spree/price_rules/user_rule.rb+++ b/spree/core/app/models/spree/price_rules/user_rule.rb@@ -3,16 +3,16 @@ module Spreeclass UserRule < Spree::PriceRule# Stored as raw IDs. Accepts prefixed IDs (the user class's prefix,# e.g. `usr_…`) from API callers and decodes them on write. Resolves- # `Spree.user_class` lazily — the user class is configured at boot,+ # `Spree.customer_class` lazily — the user class is configured at boot,# and class-body evaluation runs before that on cold loads.preference :user_ids, :array, default: [], parse_on_set: ->(values) {- normalize_id_preference(klass: Spree.user_class).call(values)+ normalize_id_preference(klass: Spree.customer_class).call(values)}def usersreturn [] if preferred_user_ids.blank?- Spree.user_class.where(id: preferred_user_ids)+ Spree.customer_class.where(id: preferred_user_ids)enddef applicable?(context)diff --git a/spree/core/app/models/spree/promotion/rules/user.rb b/spree/core/app/models/spree/promotion/rules/user.rbindex 87e569d349..0e8133b9f2 100644--- a/spree/core/app/models/spree/promotion/rules/user.rb+++ b/spree/core/app/models/spree/promotion/rules/user.rb@@ -8,7 +8,7 @@ module Spreehas_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser',foreign_key: :promotion_rule_id,dependent: :destroy- has_many :users, through: :promotion_rule_users, class_name: "::#{Spree.user_class}"+ has_many :users, through: :promotion_rule_users, source: :customer, class_name: "::#{Spree.customer_class}"# Customers, not admin users — the rule keys off `Spree::Order#user_id`.# The data layer keeps the `users` association (legacy column name);@@ -46,7 +46,7 @@ module Spreeenddef eligible_user_ids- @eligible_user_ids ||= promotion_rule_users.pluck(:user_id)+ @eligible_user_ids ||= promotion_rule_users.pluck(:customer_id)enddef eligible?(order, _options = {})diff --git a/spree/core/app/models/spree/promotion_rule_user.rb b/spree/core/app/models/spree/promotion_rule_user.rbindex 9bb8bf9d5b..6bfc3939e5 100644--- a/spree/core/app/models/spree/promotion_rule_user.rb+++ b/spree/core/app/models/spree/promotion_rule_user.rb@@ -1,7 +1,8 @@module Spreeclass PromotionRuleUser < Spree.base_classbelongs_to :promotion_rule, class_name: 'Spree::PromotionRule'- belongs_to :user, class_name: "::#{Spree.user_class}"+ belongs_to :customer, class_name: "::#{Spree.customer_class}"+ include Spree::DeprecatedCustomerAliasvalidates :user, :promotion_rule, presence: truevalidates :user_id, uniqueness: { scope: :promotion_rule_id }, allow_nil: truediff --git a/spree/core/app/models/spree/role.rb b/spree/core/app/models/spree/role.rbindex 21c7d2b728..a413ec2532 100644--- a/spree/core/app/models/spree/role.rb+++ b/spree/core/app/models/spree/role.rb@@ -10,7 +10,7 @@ module Spree# Associations#has_many :role_users, class_name: 'Spree::RoleUser', dependent: :destroy- has_many :users, through: :role_users, source: :user, source_type: Spree.user_class.to_s+ has_many :users, through: :role_users, source: :user, source_type: Spree.customer_class.to_shas_many :admin_users, through: :role_users, source: :user, source_type: Spree.admin_user_class.to_shas_many :invitations, class_name: 'Spree::Invitation', dependent: :destroydiff --git a/spree/core/app/models/spree/state_change.rb b/spree/core/app/models/spree/state_change.rbindex a73f831308..71869dda72 100644--- a/spree/core/app/models/spree/state_change.rb+++ b/spree/core/app/models/spree/state_change.rb@@ -2,7 +2,7 @@ module Spreeclass StateChange < Spree.base_classhas_prefix_id :sc- belongs_to :user, class_name: "::#{Spree.user_class}", optional: true+ belongs_to :user, class_name: "::#{Spree.customer_class}", optional: truebelongs_to :stateful, polymorphic: truedef <=>(other)diff --git a/spree/core/app/models/spree/store_credit.rb b/spree/core/app/models/spree/store_credit.rbindex adbce9e7d9..214681c87e 100644--- a/spree/core/app/models/spree/store_credit.rb+++ b/spree/core/app/models/spree/store_credit.rb@@ -19,7 +19,8 @@ module SpreeALLOCATION_ACTION = 'allocation'.freezebelongs_to :store, class_name: 'Spree::Store'- belongs_to :user, class_name: "::#{Spree.user_class}", foreign_key: 'user_id'+ belongs_to :customer, class_name: "::#{Spree.customer_class}"+ include Spree::DeprecatedCustomerAliasbelongs_to :category, class_name: 'Spree::StoreCreditCategory', optional: truebelongs_to :created_by, class_name: Spree.admin_user_class.to_s, foreign_key: 'created_by_id', optional: truebelongs_to :credit_type, class_name: 'Spree::StoreCreditType', foreign_key: 'type_id', optional: true@@ -58,8 +59,8 @@ module Spreeself[:amount] = Spree::LocalizedNumber.parse(amount)end- self.whitelisted_ransackable_attributes = %w[user_id created_by_id amount currency type_id]- self.whitelisted_ransackable_associations = %w[type user created_by]+ self.whitelisted_ransackable_attributes = %w[customer_id user_id created_by_id amount currency type_id]+ self.whitelisted_ransackable_associations = %w[type customer created_by]def amount_remainingamount - amount_used - amount_authorizeddiff --git a/spree/core/app/models/spree/user_identity.rb b/spree/core/app/models/spree/user_identity.rbindex 31a6aa375c..a68183280c 100644--- a/spree/core/app/models/spree/user_identity.rb+++ b/spree/core/app/models/spree/user_identity.rb@@ -21,7 +21,7 @@ module Spree# Find or create user from OAuth datadef self.find_or_create_from_oauth(provider:, uid:, info:, tokens: {}, user_class: nil)- user_class ||= Spree.user_class+ user_class ||= Spree.customer_classuser_type = user_class.nameidentity = find_by(provider: provider, uid: uid, user_type: user_type)@@ -57,7 +57,7 @@ module Spreeenddef self.create_user_from_oauth(provider:, uid:, info:, tokens: {}, user_class: nil)- user_class ||= Spree.user_class+ user_class ||= Spree.customer_classtransaction douser = user_class.create!(diff --git a/spree/core/app/models/spree/wishlist.rb b/spree/core/app/models/spree/wishlist.rbindex 8bf0241c01..b158302d2b 100644--- a/spree/core/app/models/spree/wishlist.rb+++ b/spree/core/app/models/spree/wishlist.rb@@ -12,7 +12,8 @@ module Spreehas_secure_tokenend- belongs_to :user, class_name: "::#{Spree.user_class}", touch: true+ belongs_to :customer, class_name: "::#{Spree.customer_class}", touch: true+ include Spree::DeprecatedCustomerAliasbelongs_to :store, class_name: 'Spree::Store'has_many :wished_items, class_name: 'Spree::WishedItem', dependent: :destroydiff --git a/spree/core/app/services/spree/account/create.rb b/spree/core/app/services/spree/account/create.rbindex 674c4834f5..a5193f6b2d 100644--- a/spree/core/app/services/spree/account/create.rb+++ b/spree/core/app/services/spree/account/create.rb@@ -4,7 +4,7 @@ module Spreeprepend Spree::ServiceModule::Basedef call(user_params: {})- user = Spree.user_class.new(user_params)+ user = Spree.customer_class.new(user_params)if user.savesuccess(user)diff --git a/spree/core/app/services/spree/imports/row_processors/customer.rb b/spree/core/app/services/spree/imports/row_processors/customer.rbindex 48ae2fee0d..83c50d7819 100644--- a/spree/core/app/services/spree/imports/row_processors/customer.rb+++ b/spree/core/app/services/spree/imports/row_processors/customer.rb@@ -16,7 +16,7 @@ module Spreeemail = attributes['email'].to_s.strip.downcaseraise ArgumentError, 'Email is required' if email.blank?- Spree.user_class.find_or_initialize_by(email: email)+ Spree.customer_class.find_or_initialize_by(email: email)enddef assign_user_attributes(user)diff --git a/spree/core/app/services/spree/newsletter/subscribe.rb b/spree/core/app/services/spree/newsletter/subscribe.rbindex b425237321..f4ea0b0b7f 100644--- a/spree/core/app/services/spree/newsletter/subscribe.rb+++ b/spree/core/app/services/spree/newsletter/subscribe.rb@@ -59,7 +59,7 @@ module Spreeenddef known_user- @known_user ||= current_user || Spree.user_class.find_by(email: email)+ @known_user ||= current_user || Spree.customer_class.find_by(email: email)endendenddiff --git a/spree/core/app/services/spree/orders/create.rb b/spree/core/app/services/spree/orders/create.rbindex f64b621809..f4074b9496 100644--- a/spree/core/app/services/spree/orders/create.rb+++ b/spree/core/app/services/spree/orders/create.rb@@ -14,7 +14,7 @@ module Spreeattr_reader :discount_application_errors# @param store [Spree::Store]- # @param user [Object, nil] resolved customer (Spree.user_class instance)+ # @param user [Object, nil] resolved customer (Spree.customer_class instance)# @param params [Hash] order params (see admin API docs)# @return [Spree::ServiceModule::Result]def call(store:, user: nil, params: {})diff --git a/spree/core/app/services/spree/orders/create_user_account.rb b/spree/core/app/services/spree/orders/create_user_account.rbindex af49acfe35..0472a40232 100644--- a/spree/core/app/services/spree/orders/create_user_account.rb+++ b/spree/core/app/services/spree/orders/create_user_account.rb@@ -6,10 +6,10 @@ module Spreeprepend ::Spree::ServiceModule::Basedef call(order:, accepts_email_marketing: false)- existing_user = Spree.user_class.find_by(email: order.email)+ existing_user = Spree.customer_class.find_by(email: order.email)if existing_user.present?- order.update_columns(user_id: existing_user.id, updated_at: Time.current)- order.user = existing_user+ order.update_columns(customer_id: existing_user.id, updated_at: Time.current)+ order.customer = existing_userreturn success(existing_user)end@@ -21,8 +21,8 @@ module Spree# assign newly created user to the order# using update_columns to avoid running validations/callbacks- order.update_columns(user_id: user.id, updated_at: Time.current)- order.user = user+ order.update_columns(customer_id: user.id, updated_at: Time.current)+ order.customer = user# send welcome emailuser.send_welcome_email if user.respond_to?(:send_welcome_email)@@ -40,7 +40,7 @@ module Spree# we need to generate a password for the userpassword = SecureRandom.base58(16)- user = Spree.user_class.new+ user = Spree.customer_class.newuser.email = order.emailuser.first_name = firstname if user.respond_to?(:first_name)user.last_name = lastname if user.respond_to?(:last_name)@@ -56,7 +56,7 @@ module Spreedef assign_bill_address(order, user)if order.bill_address.present?- order.bill_address.update_columns(user_id: user.id, updated_at: Time.current)+ order.bill_address.update_columns(customer_id: user.id, updated_at: Time.current)user.update_columns(bill_address_id: order.bill_address_id, updated_at: Time.current) unless user.bill_address_id.present?end@@ -64,7 +64,7 @@ module Spreedef assign_ship_address(order, user)if order.ship_address.present?- order.ship_address.update_columns(user_id: user.id, updated_at: Time.current)+ order.ship_address.update_columns(customer_id: user.id, updated_at: Time.current)user.update_columns(ship_address_id: order.ship_address_id, updated_at: Time.current) unless user.ship_address_id.present?enddiff --git a/spree/core/app/services/spree/payments/create.rb b/spree/core/app/services/spree/payments/create.rbindex 75c38c7ebd..ccb1a9e655 100644--- a/spree/core/app/services/spree/payments/create.rb+++ b/spree/core/app/services/spree/payments/create.rb@@ -31,7 +31,7 @@ module Spreeif payment_method&.source_required?if order.user.present? && params[:source_id].present?- source = payment_method.payment_source_class.find_by(id: params[:source_id], user: order.user)+ source = payment_method.payment_source_class.find_by(id: params[:source_id], customer: order.customer)return failure(nil, :source_not_found) if source.nil?elsediff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 929c6b55ea..9a83d76246 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -289,6 +289,14 @@ en:content_type: has not allowed content typetype:inclusion: is not included in the list of allowed types+ spree/customer:+ attributes:+ bill_address_id:+ belongs_to_other_user: belongs to other user+ deprecated_in_completed_order: deprecated in completed order+ ship_address_id:+ belongs_to_other_user: belongs to other user+ deprecated_in_completed_order: deprecated in completed orderspree/legacy_user:attributes:bill_address_id:diff --git a/spree/core/lib/generators/spree/authentication/custom/custom_generator.rb b/spree/core/lib/generators/spree/authentication/custom/custom_generator.rbindex c0a439e278..e42eb27684 100644--- a/spree/core/lib/generators/spree/authentication/custom/custom_generator.rb+++ b/spree/core/lib/generators/spree/authentication/custom/custom_generator.rb@@ -22,14 +22,14 @@ module Spreeend\n}end- user_class_file = Rails.root.join('app', 'models', "#{Spree.user_class.name.underscore}.rb")+ user_class_file = Rails.root.join('app', 'models', "#{Spree.customer_class.name.underscore}.rb")if File.exist?(user_class_file)- inject_into_file user_class_file, after: "class #{Spree.user_class.name} < ApplicationRecord\n" do+ inject_into_file user_class_file, after: "class #{Spree.customer_class.name} < ApplicationRecord\n" do<<-RUBY# Spree modulesinclude Spree::UserAddress- include Spree::UserMethods+ include Spree::CustomerMethodsinclude Spree::UserPaymentSourceRUBYend@@ -39,7 +39,7 @@ module Spreesay <<~RUBY# Spree modulesinclude Spree::UserAddress- include Spree::UserMethods+ include Spree::CustomerMethodsinclude Spree::UserPaymentSourceRUBYenddiff --git a/spree/core/lib/generators/spree/authentication/devise/devise_generator.rb b/spree/core/lib/generators/spree/authentication/devise/devise_generator.rbindex 4a05c50f9e..e3bef17fa6 100644--- a/spree/core/lib/generators/spree/authentication/devise/devise_generator.rb+++ b/spree/core/lib/generators/spree/authentication/devise/devise_generator.rb@@ -22,14 +22,14 @@ module Spreeend\n}end- user_class_file = Rails.root.join('app', 'models', "#{Spree.user_class.name.underscore}.rb")+ user_class_file = Rails.root.join('app', 'models', "#{Spree.customer_class.name.underscore}.rb")if File.exist?(user_class_file)- inject_into_file user_class_file, after: "class #{Spree.user_class.name} < ApplicationRecord\n" do+ inject_into_file user_class_file, after: "class #{Spree.customer_class.name} < ApplicationRecord\n" do<<-RUBY# Spree modulesinclude Spree::UserAddress- include Spree::UserMethods+ include Spree::CustomerMethodsinclude Spree::UserPaymentSourceRUBYend@@ -41,14 +41,14 @@ module Spreesay <<~RUBY# Spree modulesinclude Spree::UserAddress- include Spree::UserMethods+ include Spree::CustomerMethodsinclude Spree::UserPaymentSourceRUBYsay "Please replace < ApplicationRecord with < Spree.base_class in #{user_class_file}"end- if Spree.admin_user_class != Spree.user_class+ if Spree.admin_user_class != Spree.customer_classadmin_user_class_file = Rails.root.join('app', 'models', "#{Spree.admin_user_class.name.underscore}.rb")if File.exist?(admin_user_class_file)diff --git a/spree/core/lib/generators/spree/authentication/devise/templates/authentication_helpers.rb.tt b/spree/core/lib/generators/spree/authentication/devise/templates/authentication_helpers.rb.ttindex 331cb30d22..75a3d06e96 100644--- a/spree/core/lib/generators/spree/authentication/devise/templates/authentication_helpers.rb.tt+++ b/spree/core/lib/generators/spree/authentication/devise/templates/authentication_helpers.rb.tt@@ -14,27 +14,27 @@ module Spreeenddef spree_current_user- send("current_#{Spree.user_class.model_name.singular_route_key}")+ send("current_#{Spree.customer_class.model_name.singular_route_key}")enddef spree_login_path(opts = {})- new_session_path(Spree.user_class.model_name.singular_route_key, opts)+ new_session_path(Spree.customer_class.model_name.singular_route_key, opts)enddef spree_signup_path(opts = {})- new_registration_path(Spree.user_class.model_name.singular_route_key, opts)+ new_registration_path(Spree.customer_class.model_name.singular_route_key, opts)enddef spree_logout_path(opts = {})- destroy_session_path(Spree.user_class.model_name.singular_route_key, opts)+ destroy_session_path(Spree.customer_class.model_name.singular_route_key, opts)enddef spree_forgot_password_path(opts = {})- new_password_path(Spree.user_class.model_name.singular_route_key, opts)+ new_password_path(Spree.customer_class.model_name.singular_route_key, opts)enddef spree_edit_password_path(opts = {})- edit_registration_path(Spree.user_class.model_name.singular_route_key, opts)+ edit_registration_path(Spree.customer_class.model_name.singular_route_key, opts)enddef spree_admin_login_path(opts = {})diff --git a/spree/core/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.tt b/spree/core/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.ttindex 64811a48df..f628d84cb2 100644--- a/spree/core/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.tt+++ b/spree/core/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.tt@@ -2,6 +2,7 @@ class CreateSpreeAdminUsers < ActiveRecord::Migration<%= migration_version %>def changecreate_table :spree_admin_users do |t|t.string :encrypted_password, limit: 128+ t.string :password_digestt.string :emailt.string :remember_tokent.string :persistence_tokendiff --git a/spree/core/lib/generators/spree/model/model_generator.rb b/spree/core/lib/generators/spree/model/model_generator.rbindex 2021c7a2cb..b12198e411 100644--- a/spree/core/lib/generators/spree/model/model_generator.rb+++ b/spree/core/lib/generators/spree/model/model_generator.rb@@ -52,7 +52,7 @@ module Spree"spree_#{super.delete_prefix('spree_')}"end- # Resolution: explicit class hint in attribute spec → Spree.user_class+ # Resolution: explicit class hint in attribute spec → Spree.customer_class# for user-named columns → Spree.admin_user_class for admin-user-named# columns → Spree::<CamelCasedName> default. The Rails attribute parser# splits on `:` so explicit hints can only be unqualified names; users@@ -63,7 +63,7 @@ module Spreecase attribute.namewhen 'user', 'user_id'- '"::#{Spree.user_class}"'+ '"::#{Spree.customer_class}"'when 'admin_user', 'admin_user_id', 'created_by', 'created_by_id','approver', 'approver_id', 'canceler', 'canceler_id''"::#{Spree.admin_user_class}"'diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex edd223b31a..8296caa59e 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -39,7 +39,7 @@ require 'sqids'StateMachines::Machine.ignore_method_conflicts = truemodule Spree- mattr_accessor :base_class, :user_class, :admin_user_class,+ mattr_accessor :base_class, :customer_class, :admin_user_class,:private_storage_service_name, :public_storage_service_name,:cdn_host, :root_domain, :searcher_class, :events_adapter_class, :queues,:google_places_api_key@@ -53,14 +53,26 @@ module Spreeendend- def self.user_class(constantize: true)- if @@user_class.is_a?(Class)- raise 'Spree.user_class MUST be a String or Symbol object, not a Class object.'- elsif @@user_class.is_a?(String) || @@user_class.is_a?(Symbol)- constantize ? @@user_class.to_s.constantize : @@user_class.to_s+ def self.customer_class(constantize: true)+ if @@customer_class.is_a?(Class)+ raise 'Spree.customer_class MUST be a String or Symbol object, not a Class object.'+ elsif @@customer_class.is_a?(String) || @@customer_class.is_a?(Symbol)+ constantize ? @@customer_class.to_s.constantize : @@customer_class.to_sendend+ # @deprecated Spree.user_class was renamed to Spree.customer_class in 6.0; removed in 6.1.+ def self.user_class(constantize: true)+ Spree::Deprecation.warn('Spree.user_class is deprecated and will be removed in Spree 6.1. Use Spree.customer_class instead.') if defined?(Spree::Deprecation)+ customer_class(constantize: constantize)+ end++ # @deprecated Spree.user_class= was renamed to Spree.customer_class= in 6.0; removed in 6.1.+ def self.user_class=(value)+ Spree::Deprecation.warn('Spree.user_class= is deprecated and will be removed in Spree 6.1. Use Spree.customer_class= instead.') if defined?(Spree::Deprecation)+ self.customer_class = value+ end+def self.admin_user_class(constantize: true)if @@admin_user_class.is_a?(Class)raise 'Spree.admin_user_class MUST be a String or Symbol object, not a Class object.'diff --git a/spree/core/lib/spree/core/controller_helpers/auth.rb b/spree/core/lib/spree/core/controller_helpers/auth.rbindex 611efe4c7b..08e1b28315 100644--- a/spree/core/lib/spree/core/controller_helpers/auth.rb+++ b/spree/core/lib/spree/core/controller_helpers/auth.rb@@ -31,7 +31,7 @@ module Spreeenddef store_location_session_key- "#{Spree.user_class.model_name.singular_route_key.to_sym}_return_to"+ "#{Spree.customer_class.model_name.singular_route_key.to_sym}_return_to"end# proxy method to *possible* spree_current_user methoddiff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex 845abf8e9d..451d520b6d 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -132,8 +132,8 @@ module Spreeend# Promotion rules need to be evaluated on after initialize otherwise- # Spree.user_class would be nil and users might experience errors related- # to malformed model associations (Spree.user_class is only defined on+ # Spree.customer_class would be nil and users might experience errors related+ # to malformed model associations (Spree.customer_class is only defined on# the app initializer)config.after_initialize doRails.application.config.spree.calculators.shipping_methods = [@@ -302,7 +302,7 @@ module SpreeRails.application.config.spree.taggable_types = ['Spree::Product','Spree::Order',- Spree.user_class.to_s+ Spree.customer_class.to_s]Rails.application.config.spree.metafields.types = [@@ -343,7 +343,7 @@ module SpreeSpree::Category,Spree::Taxonomy,Spree::Variant,- Spree.user_class+ Spree.customer_class]Rails.application.config.spree.analytics_events = {diff --git a/spree/core/lib/spree/core/previews/preview_data.rb b/spree/core/lib/spree/core/previews/preview_data.rbindex 41cce0aff7..936d65d85a 100644--- a/spree/core/lib/spree/core/previews/preview_data.rb+++ b/spree/core/lib/spree/core/previews/preview_data.rb@@ -25,8 +25,8 @@ module Spree# A customer for previews of customer-facing account emails. Falls back to# an unsaved instance when the database has no users.def customer- Spree.user_class.first ||- Spree.user_class.new(email: '[email protected]').tap do |user|+ Spree.customer_class.first ||+ Spree.customer_class.new(email: '[email protected]').tap do |user|user.first_name = 'Alex' if user.respond_to?(:first_name=)endenddiff --git a/spree/core/lib/tasks/core.rake b/spree/core/lib/tasks/core.rakeindex 14807d1da0..01020b3941 100644--- a/spree/core/lib/tasks/core.rake+++ b/spree/core/lib/tasks/core.rake@@ -36,7 +36,7 @@ namespace :core dodesc 'Migrate newsletter subscribers'task migrate_newsletter_subscribers: :environment do |_t, _args|- Spree.user_class.where(accepts_email_marketing: true).in_batches(of: 500) do |user_batch|+ Spree.customer_class.where(accepts_email_marketing: true).in_batches(of: 500) do |user_batch|subscriber_attributes = user_batch.pluck(:id, :email, :updated_at).map do |id, email, updated_at|{email: Spree::NewsletterSubscriber.new(email: email).email, # normalized emaildiff --git a/spree/emails/app/subscribers/spree/customer_email_subscriber.rb b/spree/emails/app/subscribers/spree/customer_email_subscriber.rbindex ba51f24677..e64c05de4e 100644--- a/spree/emails/app/subscribers/spree/customer_email_subscriber.rb+++ b/spree/emails/app/subscribers/spree/customer_email_subscriber.rb@@ -5,7 +5,7 @@ module Spreesubscribes_to 'customer.password_reset_requested'def handle(event)- user = Spree.user_class.find_by(email: event.payload['email'])+ user = Spree.customer_class.find_by(email: event.payload['email'])return unless userstore = find_store(event)diff --git a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb b/spree/lib/generators/spree/install/templates/config/initializers/spree.rbindex 18a9e935f8..b2bb3cfb41 100644--- a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb+++ b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb@@ -133,5 +133,5 @@ end# Search provider# Spree.search_provider = 'Spree::SearchProvider::Meilisearch'-Spree.user_class = <%= (options[:user_class].blank? ? 'Spree::LegacyUser' : options[:user_class]).inspect %>-Spree.admin_user_class = <%= (options[:admin_user_class].blank? ? (options[:user_class].blank? ? 'Spree::LegacyAdminUser' : options[:user_class]) : options[:admin_user_class]).inspect %>+Spree.customer_class = <%= (options[:user_class].blank? ? 'Spree::Customer' : options[:user_class]).inspect %>+Spree.admin_user_class = <%= (options[:admin_user_class].blank? ? (options[:user_class].blank? ? 'Spree::AdminUser' : options[:user_class]) : options[:admin_user_class]).inspect %>