Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Feature: Custom Domains (#12315)

Damian Legawiecea5a842deecb
diff --git a/admin/config/routes.rb b/admin/config/routes.rb
index f59753c5e3..c120ad9ae7 100644
--- a/admin/config/routes.rb
+++ b/admin/config/routes.rb
@@ -138,5 +138,10 @@ Spree::Core::Engine.add_routes do
# errors
get '/forbidden', to: 'errors#forbidden', as: :forbidden
+
+ # dashboard
+ resource :dashboard, controller: 'dashboard'
+
+ root to: 'dashboard#show'
end
end
diff --git a/core/app/finders/spree/stores/find_current.rb b/core/app/finders/spree/stores/find_current.rb
index dc56f08052..978985c73a 100644
--- a/core/app/finders/spree/stores/find_current.rb
+++ b/core/app/finders/spree/stores/find_current.rb
@@ -8,6 +8,8 @@ module Spree
def execute
store = by_url(scope) || scope.default
+ return if store.nil?
+
Spree::Current.store = store
store
end
@@ -19,7 +21,7 @@ module Spree
def by_url(scope)
return if url.blank?
- scope.by_url(url).first
+ scope.by_custom_domain(url).or(scope.by_url(url)).first
end
end
end
diff --git a/core/app/models/spree/custom_domain.rb b/core/app/models/spree/custom_domain.rb
new file mode 100644
index 0000000000..5532046ef6
--- /dev/null
+++ b/core/app/models/spree/custom_domain.rb
@@ -0,0 +1,53 @@
+module Spree
+ class CustomDomain < Spree::Base
+ include Spree::SingleStoreResource
+ include Spree::Metadata
+
+ auto_strip_attributes :url
+
+ #
+ # Associations
+ #
+ belongs_to :store, class_name: 'Spree::Store', inverse_of: :custom_domains
+
+ #
+ # Validations
+ #
+ validates :url, presence: true, uniqueness: true, format: {
+ with: %r{[a-z][a-z0-9-]*[a-z0-9]}i
+ }, length: { in: 1..63 }
+ validate :url_is_valid
+
+ #
+ # Callbacks
+ #
+ before_validation :sanitize_url
+ after_save :ensure_has_one_default
+ after_validation :ensure_default, on: :create
+
+ def url_is_valid
+ parts = url.split('.')
+
+ errors.add(:url, 'use domain or subdomain') if (parts[0] != 'www' && parts.size > 3) || (parts[0] == 'www' && parts.size > 4) || parts.size < 2
+ end
+
+ def ensure_default
+ self.default = store.custom_domains.count.zero?
+ end
+
+ def ensure_has_one_default
+ store.custom_domains.where.not(id: id).update_all(default: false) if default?
+ end
+
+ def active?
+ true
+ end
+
+ private
+
+ # remove https:// and http:// from the url
+ def sanitize_url
+ self.url = url&.gsub(%r{https?://}, '')
+ end
+ end
+end
diff --git a/core/app/models/spree/store.rb b/core/app/models/spree/store.rb
index ade49621f0..43b952ed78 100644
--- a/core/app/models/spree/store.rb
+++ b/core/app/models/spree/store.rb
@@ -1,3 +1,5 @@
+require 'uri'
+
module Spree
class Store < Spree.base_class
RESERVED_CODES = %w(
@@ -97,6 +99,9 @@ module Spree
belongs_to :default_country, class_name: 'Spree::Country'
belongs_to :checkout_zone, class_name: 'Spree::Zone'
+ has_many :custom_domains, class_name: 'Spree::CustomDomain', dependent: :destroy
+ has_one :default_custom_domain, -> { where(default: true) }, class_name: 'Spree::CustomDomain'
+
#
# ActionText
#
@@ -145,6 +150,7 @@ module Spree
# Callbacks
before_validation :ensure_default_country
before_validation :set_code, on: :create
+ before_validation :set_url
before_save :ensure_default_exists_and_is_unique
before_save :ensure_supported_currencies, :ensure_supported_locales
after_create :ensure_default_taxonomies_are_created
@@ -160,7 +166,8 @@ module Spree
# Scopes
#
default_scope { order(created_at: :asc) }
- scope :by_url, ->(url) { where('url like ?', "%#{url}%") }
+ scope :by_custom_domain, ->(url) { left_joins(:custom_domains).where("#{Spree::CustomDomain.table_name}.url" => url) }
+ scope :by_url, ->(url) { where("#{table_name}.url like ?", "%#{url}%") }
#
# Delegations
@@ -241,7 +248,6 @@ module Spree
end
def supported_locales_list
- # TODO: add support of multiple supported languages to a single Store
@supported_locales_list ||= (read_attribute(:supported_locales).to_s.split(',') << default_locale).compact.uniq.sort
end
@@ -250,22 +256,29 @@ module Spree
end
def formatted_url
- return if url.blank?
+ @formatted_url ||= Rails.env.development? || Rails.env.test? ? URI::Generic.build(scheme: Rails.application.routes.default_url_options[:protocol] || 'http', host: url.sub(%r{^https?://}, ''), port: Rails.application.routes.default_url_options[:port]).to_s : URI::HTTPS.build(host: url.sub(%r{^https?://}, '')).to_s
+ end
- @formatted_url ||= if url.match(/http:\/\/|https:\/\//)
- url
- else
- Rails.env.development? || Rails.env.test? ? "http://#{url}" : "https://#{url}"
- end
+ def formatted_custom_domain
+ return unless default_custom_domain
+
+ @formatted_custom_domain ||= if Rails.env.development? || Rails.env.test?
+ URI::Generic.build(
+ scheme: Rails.application.routes.default_url_options[:protocol] || 'http',
+ host: default_custom_domain.url,
+ port: Rails.application.routes.default_url_options[:port]
+ ).to_s
+ else
+ URI::HTTPS.build(host: default_custom_domain.url).to_s
+ end
end
def url_or_custom_domain
- # Overwrite this if you have a custom domain
- url
+ default_custom_domain&.url || url
end
def formatted_url_or_custom_domain
- formatted_url
+ formatted_custom_domain || formatted_url
end
def countries_available_for_checkout
@@ -457,5 +470,14 @@ module Spree
# ensure code is unique
self.code = [name.parameterize, rand(9999)].join('-') while Spree::Store.with_deleted.where(code: self.code).exists?
end
+
+ # auto-assign internal URL for stores
+ def set_url
+ return if url_changed?
+ return unless code_changed?
+ return unless Spree.root_domain.present?
+
+ self.url = [code, Spree.root_domain].join('.')
+ end
end
end
diff --git a/core/bin/rails b/core/bin/rails
new file mode 100755
index 0000000000..42c9400685
--- /dev/null
+++ b/core/bin/rails
@@ -0,0 +1,10 @@
+#!/usr/bin/env ruby
+ENGINE_ROOT = File.expand_path('..', __dir__)
+ENGINE_PATH = File.expand_path('../lib/spree/core/engine', __dir__)
+
+# Set up gems listed in the Gemfile.
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __dir__)
+
+require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"])
+require "rails/all"
+require "rails/engine/commands"
diff --git a/core/db/migrate/20250119165904_create_spree_custom_domains.rb b/core/db/migrate/20250119165904_create_spree_custom_domains.rb
new file mode 100644
index 0000000000..fa3659c1c8
--- /dev/null
+++ b/core/db/migrate/20250119165904_create_spree_custom_domains.rb
@@ -0,0 +1,22 @@
+class CreateSpreeCustomDomains < ActiveRecord::Migration[6.1]
+ def change
+ return if table_exists?(:spree_custom_domains)
+
+ create_table :spree_custom_domains do |t|
+ t.references :store, null: false, index: true
+ t.string :url, null: false, index: { unique: true }
+ t.boolean :status, default: false
+ t.boolean :default, default: false, null: false
+
+ if t.respond_to? :jsonb
+ t.jsonb :public_metadata
+ t.jsonb :private_metadata
+ else
+ t.json :public_metadata
+ t.json :private_metadata
+ end
+
+ t.timestamps
+ end
+ end
+end
diff --git a/core/lib/spree/testing_support/factories/custom_domain_factory.rb b/core/lib/spree/testing_support/factories/custom_domain_factory.rb
new file mode 100644
index 0000000000..4c2e1f8bc6
--- /dev/null
+++ b/core/lib/spree/testing_support/factories/custom_domain_factory.rb
@@ -0,0 +1,7 @@
+FactoryBot.define do
+ factory :custom_domain, class: Spree::CustomDomain do
+ url { FFaker::Internet.domain_name }
+ store { create(:store) }
+ default { true }
+ end
+end
diff --git a/core/spec/finders/spree/stores/find_current_spec.rb b/core/spec/finders/spree/stores/find_current_spec.rb
index 4f20a61943..85c3ba4e98 100644
--- a/core/spec/finders/spree/stores/find_current_spec.rb
+++ b/core/spec/finders/spree/stores/find_current_spec.rb
@@ -38,5 +38,12 @@ module Spree
it { expect(subject).to eq(store_2) }
end
+
+ context 'with custom domain' do
+ let(:url) { 'shop.getvendo.com' }
+ let!(:custom_domain) { create(:custom_domain, url: url, store: store_2) }
+
+ it { expect(subject).to eq(store_2) }
+ end
end
end
diff --git a/core/spec/helpers/base_helper_spec.rb b/core/spec/helpers/base_helper_spec.rb
index e43fabcdb4..11ab55f0be 100644
--- a/core/spec/helpers/base_helper_spec.rb
+++ b/core/spec/helpers/base_helper_spec.rb
@@ -7,6 +7,7 @@ describe Spree::BaseHelper, type: :helper do
before do
allow(controller).to receive(:controller_name).and_return('test')
+ allow(Rails.application.routes).to receive(:default_url_options).and_return(protocol: 'http', port: nil)
end
context 'available_countries' do
diff --git a/core/spec/models/spree/custom_domain_spec.rb b/core/spec/models/spree/custom_domain_spec.rb
new file mode 100644
index 0000000000..b12f7ef4a3
--- /dev/null
+++ b/core/spec/models/spree/custom_domain_spec.rb
@@ -0,0 +1,26 @@
+require 'spec_helper'
+
+RSpec.describe Spree::CustomDomain, type: :model do
+ let!(:store) { Spree::Store.default }
+
+ describe 'Validations' do
+ describe '#sanitize_url' do
+ let(:custom_domain) { build(:custom_domain, url: 'https://shop.custom.domain ') }
+
+ it 'removes https:// and http:// from the url' do
+ custom_domain.valid?
+ expect(custom_domain.url).to eq('shop.custom.domain')
+ end
+ end
+
+ describe '#url_is_valid' do
+ it 'is valid with valid url' do
+ expect(build(:custom_domain, url: 'shop.custom.domain')).to be_valid
+ end
+
+ it 'is invalid with wrong number of parts' do
+ expect(build(:custom_domain, url: 'com')).not_to be_valid
+ end
+ end
+ end
+end
diff --git a/core/spec/models/spree/data_feed/google_spec.rb b/core/spec/models/spree/data_feed/google_spec.rb
index 253515eab2..a1d79e957a 100644
--- a/core/spec/models/spree/data_feed/google_spec.rb
+++ b/core/spec/models/spree/data_feed/google_spec.rb
@@ -25,6 +25,10 @@ describe Spree::DataFeed::Google, type: :model do
let(:data_feed) { create(:google_data_feed, store: store, slug: 'test-feed') }
let(:expected_url) { 'http://store.test/api/v2/data_feeds/google/test-feed.rss' }
+ before do
+ allow(Rails.application.routes).to receive(:default_url_options).and_return(protocol: 'http', port: nil)
+ end
+
it 'returns full url to the data feed' do
expect(data_feed.formatted_url).to eq(expected_url)
end
diff --git a/core/spec/models/spree/store_spec.rb b/core/spec/models/spree/store_spec.rb
index 0c4353394d..36074bdfce 100644
--- a/core/spec/models/spree/store_spec.rb
+++ b/core/spec/models/spree/store_spec.rb
@@ -1,6 +1,10 @@
require 'spec_helper'
describe Spree::Store, type: :model do
+ before do
+ allow(Spree).to receive(:root_domain).and_return('mydomain.dev')
+ end
+
context 'Associations' do
subject { create(:store) }
@@ -147,6 +151,28 @@ describe Spree::Store, type: :model do
end
end
+ describe '#set_url' do
+ let(:store) { build(:store, code: 'my_store', url: nil) }
+
+ context 'on create' do
+ it 'sets url' do
+ store.save!
+ expect(store.url).to eq('my_store.mydomain.dev')
+ end
+ end
+
+ context 'on update code change update url' do
+ let!(:store) { create(:store, code: 'my_store', url: 'my_store.mydomain.dev') }
+
+ it 'updates url but keep old one' do
+ expect(store.url).to eq('my_store.mydomain.dev')
+ store.update!(code: 'my_store_2')
+ expect(store.reload.url).to eq('my_store_2.mydomain.dev')
+ expect(Spree::Store.friendly.find('my_store').id).to eq(store.id)
+ end
+ end
+ end
+
describe '#ensure_default_taxonomies_are_created' do
let(:store) { build(:store) }
@@ -780,4 +806,24 @@ describe Spree::Store, type: :model do
end
end
end
+
+ describe '#formatted_url' do
+ let(:store) { create(:store, code: 'mystore', url: nil) }
+
+ it { expect(store.formatted_url).to eq('http://mystore.mydomain.dev:3000') }
+ end
+
+ describe '#formatted_url_or_custom_domain' do
+ let(:store) { create(:store, code: 'mystore', url: nil) }
+
+ context 'without custom domain' do
+ it { expect(store.formatted_url_or_custom_domain).to eq('http://mystore.mydomain.dev:3000') }
+ end
+
+ context 'with custom domain' do
+ let!(:custom_domain) { create(:custom_domain, store: store, url: 'mystore.com') }
+
+ it { expect(store.formatted_url_or_custom_domain).to eq('http://mystore.com:3000') }
+ end
+ end
end