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.

Add Spree::Channel model

Damian Legawiec643a2ff1e8fb
diff --git a/docs/plans/6.0-channels-catalogs-b2b.md b/docs/plans/6.0-channels-catalogs-b2b.md
index 1fbf21f958..a638b6265b 100644
--- a/docs/plans/6.0-channels-catalogs-b2b.md
+++ b/docs/plans/6.0-channels-catalogs-b2b.md
@@ -1,10 +1,10 @@
# Channels, Catalogs & B2B Companies
-**Status:** Draft
-**Target:** Spree 6.0
+**Status:** Draft (Channel itself ships in 5.5 with Order Routing; ProductListing, Catalog, Company tree, pricing integration land in 6.0)
+**Target:** Spree 6.0 (5.5 ships only the `Spree::Channel` model — see `6.0-order-routing.md`)
**Depends on:** ProductType (6.0-product-types.md), PriceList system (existing)
**Author:** Damian + Claude
-**Last updated:** 2026-03-16
+**Last updated:** 2026-05-09
## Summary
@@ -565,8 +565,9 @@ GET /api/v3/store/products # automatically filtered by channel + catalog con
## Constraints on Current Work
+- **`Spree::Channel` itself ships in 5.5** as part of `6.0-order-routing.md`. The model in 5.5 is the minimal shape (store, name, code, active, preferences, metafields) — exactly what's specified in the Channel section below, minus `default_catalog_id` (no `Catalog` yet). 6.0 layers on `default_catalog_id`, `default_stock_location_id`, and the `has_many :product_listings` association without needing migrations against the table — only `add_reference` migrations to add new FKs.
+- **`Order.channel_id` FK ships in 5.5** (the deprecated string column is dropped in the same migration). 6.0 doesn't need to migrate Orders — just adds `company_location_id`.
- **Don't add new features to StoreProduct.** It's being replaced by ProductListing.
-- **Don't use `Order.channel` as a free-text field.** It will become a FK.
- **New store-scoped product queries should use `store.products`** (which will be rerouted through channels).
- **PriceList stays as-is.** Catalog optionally references a PriceList — don't duplicate pricing logic.
diff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rb
new file mode 100644
index 0000000000..3fd16de5bd
--- /dev/null
+++ b/spree/core/app/models/spree/channel.rb
@@ -0,0 +1,34 @@
+module Spree
+ # Lightweight distribution surface within a Store: online storefront, POS,
+ # marketplace integration, wholesale portal. Channels carry order
+ # attribution and the routing-strategy override.
+ #
+ # 5.5 ships only the Channel model + per-channel order routing. The
+ # 6.0-channels-catalogs-b2b plan layers ProductListing, Catalog, B2B
+ # Companies, and per-channel API keys on top of this same model.
+ class Channel < Spree.base_class
+ has_prefix_id :ch
+
+ include Spree::SingleStoreResource
+ include Spree::Metafields
+ include Spree::Metadata
+
+ # Class name of the Spree::OrderRouting::Strategy::Base subclass for this
+ # channel. Empty -> falls back to the Store-level preference.
+ preference :order_routing_strategy, :string, default: nil
+
+ belongs_to :store, class_name: 'Spree::Store'
+
+ has_many :orders, class_name: 'Spree::Order', inverse_of: :channel
+ has_many :order_routing_rules, class_name: 'Spree::OrderRoutingRule', dependent: :destroy
+
+ attribute :active, :boolean, default: true
+
+ validates :name, presence: true
+ validates :code, presence: true, uniqueness: { scope: :store_id }
+
+ scope :active, -> { where(active: true) }
+
+ self.whitelisted_ransackable_attributes = %w[name code active store_id]
+ end
+end
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 3dd45d065e..1ba329bf50 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -104,10 +104,10 @@ module Spree
go_to_state :complete
end
- self.whitelisted_ransackable_associations = %w[shipments user created_by approver canceler promotions bill_address ship_address line_items store]
+ self.whitelisted_ransackable_associations = %w[shipments user created_by approver canceler promotions bill_address ship_address line_items store channel]
self.whitelisted_ransackable_attributes = %w[
completed_at email number state status payment_state shipment_state
- total item_total item_count considered_risky channel
+ total item_total item_count considered_risky channel_id
]
self.whitelisted_ransackable_scopes = %w[complete incomplete refunded partially_refunded search multi_search]
@@ -159,6 +159,7 @@ module Spree
belongs_to :store, class_name: 'Spree::Store'
belongs_to :market, class_name: 'Spree::Market', optional: true
+ belongs_to :channel, class_name: 'Spree::Channel', optional: true
with_options dependent: :destroy do
has_many :state_changes, as: :stateful, class_name: 'Spree::StateChange'
@@ -216,6 +217,7 @@ module Spree
# Needs to happen before save_permalink is called
before_validation :ensure_store_presence
before_validation :ensure_market_presence
+ before_validation :ensure_channel_presence
before_validation :ensure_currency_presence
before_validation :ensure_locale_presence
before_validation :resolve_market_from_currency, if: -> { persisted? && currency_changed? && !skip_market_resolution }
@@ -496,6 +498,10 @@ module Spree
self.market ||= Spree::Current.market || store&.default_market
end
+ def ensure_channel_presence
+ self.channel ||= store&.default_channel
+ end
+
def allow_cancel?
return false if !completed? || canceled?
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 3da8bba78c..c5cb57718e 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -109,6 +109,8 @@ module Spree
has_many :webhook_endpoints, class_name: 'Spree::WebhookEndpoint', dependent: :destroy, inverse_of: :store
has_many :webhook_deliveries, through: :webhook_endpoints, class_name: 'Spree::WebhookDelivery'
+ has_many :channels, class_name: 'Spree::Channel', dependent: :destroy
+
has_many :customer_groups, class_name: 'Spree::CustomerGroup', dependent: :destroy, inverse_of: :store
has_many :api_keys, class_name: 'Spree::ApiKey', dependent: :destroy
@@ -145,6 +147,7 @@ module Spree
before_save :ensure_default_exists_and_is_unique
after_create :ensure_default_market
after_create :create_default_policies
+ after_create :seed_default_channel
#
# Scopes
@@ -177,6 +180,13 @@ module Spree
Spree::Store.default&.supported_locales_list || []
end
+ # The Channel new orders default to when no other context is provided.
+ # 5.5 always seeds an 'online' channel; merchants can rename or add
+ # alongside it in 6.0.
+ def default_channel
+ channels.find_by(code: 'online') || channels.active.first
+ end
+
# @deprecated Use Markets instead. Will be removed in Spree 5.5.
def checkout_zone
Spree::Deprecation.warn('Store#checkout_zone is deprecated and will be removed in Spree 5.5. Use Markets instead.')
@@ -403,6 +413,14 @@ module Spree
end
end
+ # 5.5 ships one Channel per Store ('online'). 6.0 channels admin lets
+ # merchants add POS / wholesale / etc. See docs/plans/6.0-channels-catalogs-b2b.md.
+ def seed_default_channel
+ return if channels.any?
+
+ channels.create!(name: 'Online Store', code: 'online')
+ end
+
def ensure_default_taxonomies_are_created
Spree::Deprecation.warn('Store#ensure_default_taxonomies_are_created is deprecated and will be removed in Spree 5.5. Please remove it from your codebase')
diff --git a/spree/core/db/migrate/20260508204040_create_spree_channels.rb b/spree/core/db/migrate/20260508204040_create_spree_channels.rb
new file mode 100644
index 0000000000..a7bc0cdb11
--- /dev/null
+++ b/spree/core/db/migrate/20260508204040_create_spree_channels.rb
@@ -0,0 +1,14 @@
+class CreateSpreeChannels < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_channels do |t|
+ t.references :store, null: false
+ t.string :name, null: false
+ t.string :code, null: false
+ t.boolean :active, null: false
+ t.text :preferences
+ t.timestamps
+ end
+
+ add_index :spree_channels, [:store_id, :code], unique: true
+ end
+end
diff --git a/spree/core/db/migrate/20260508204043_add_channel_id_to_spree_orders.rb b/spree/core/db/migrate/20260508204043_add_channel_id_to_spree_orders.rb
new file mode 100644
index 0000000000..4adc1a6cb1
--- /dev/null
+++ b/spree/core/db/migrate/20260508204043_add_channel_id_to_spree_orders.rb
@@ -0,0 +1,6 @@
+class AddChannelIdToSpreeOrders < ActiveRecord::Migration[7.2]
+ def change
+ remove_column :spree_orders, :channel, :string, default: 'spree'
+ add_reference :spree_orders, :channel
+ end
+end
diff --git a/spree/core/spec/models/spree/channel_spec.rb b/spree/core/spec/models/spree/channel_spec.rb
new file mode 100644
index 0000000000..ace8cdd0ff
--- /dev/null
+++ b/spree/core/spec/models/spree/channel_spec.rb
@@ -0,0 +1,74 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Channel, type: :model do
+ let(:store) { @default_store }
+
+ describe 'validations' do
+ it 'requires name' do
+ channel = described_class.new(store: store, code: 'pos')
+ expect(channel).not_to be_valid
+ expect(channel.errors[:name]).to be_present
+ end
+
+ it 'requires code' do
+ channel = described_class.new(store: store, name: 'POS')
+ expect(channel).not_to be_valid
+ expect(channel.errors[:code]).to be_present
+ end
+
+ it 'requires code unique within a store' do
+ described_class.create!(store: store, name: 'POS', code: 'pos')
+ duplicate = described_class.new(store: store, name: 'POS 2', code: 'pos')
+
+ expect(duplicate).not_to be_valid
+ expect(duplicate.errors[:code]).to be_present
+ end
+
+ it 'allows the same code across different stores' do
+ described_class.create!(store: store, name: 'POS', code: 'pos')
+ other_store = create(:store)
+ # Auto-seeded 'online' channel is fine; we test the same arbitrary code.
+ cross = described_class.new(store: other_store, name: 'POS', code: 'pos')
+
+ expect(cross).to be_valid
+ end
+ end
+
+ describe 'defaults' do
+ it 'is active by default' do
+ expect(described_class.new(store: store).active).to be true
+ end
+ end
+
+ describe '.active scope' do
+ it 'filters active channels only' do
+ fresh_store = create(:store).tap { |s| s.channels.destroy_all }
+ active = described_class.create!(store: fresh_store, name: 'A', code: 'a', active: true)
+ described_class.create!(store: fresh_store, name: 'B', code: 'b', active: false)
+
+ expect(fresh_store.channels.active).to contain_exactly(active)
+ end
+ end
+
+ describe 'preferences' do
+ it 'falls back to nil order_routing_strategy by default' do
+ channel = described_class.new(store: store, name: 'POS', code: 'pos')
+ expect(channel.preferred_order_routing_strategy).to be_nil
+ end
+
+ it 'persists a custom routing strategy override' do
+ channel = described_class.create!(
+ store: store, name: 'POS', code: 'pos',
+ preferred_order_routing_strategy: 'CustomStrategy'
+ )
+ expect(channel.reload.preferred_order_routing_strategy).to eq('CustomStrategy')
+ end
+ end
+
+ describe 'prefixed_id' do
+ it 'starts with ch_' do
+ channel = described_class.create!(store: store, name: 'POS', code: 'pos')
+ expect(channel.prefixed_id).to start_with('ch_')
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index a2b927675c..7279ead24b 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -1554,11 +1554,22 @@ describe Spree::Order, type: :model do
end
end
- it 'assigns the coordinator returned shipments to its shipments' do
- shipment = build(:shipment)
- allow_any_instance_of(Spree::Stock::Coordinator).to receive(:shipments).and_return([shipment])
- subject.create_proposed_shipments
- expect(subject.shipments).to eq [shipment]
+ end
+
+ describe '#ensure_channel_presence' do
+ let(:store) { create(:store) }
+
+ it 'auto-assigns the store default channel on new orders' do
+ o = build(:order, store: store, channel: nil)
+ o.valid?
+ expect(o.channel).to eq(store.default_channel)
+ end
+
+ it 'preserves an explicitly set channel' do
+ other = store.channels.create!(name: 'POS', code: 'pos')
+ o = build(:order, store: store, channel: other)
+ o.valid?
+ expect(o.channel).to eq(other)
end
end
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index fa15cd1cba..ab04eed3d2 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -173,6 +173,37 @@ describe Spree::Store, type: :model, without_global_store: true do
end
end
end
+
+ describe '#seed_default_channel' do
+ let(:store) { build(:store) }
+
+ it 'creates an "online" channel on save' do
+ expect { store.save! }.to change(Spree::Channel, :count).by(1)
+
+ channel = store.channels.first
+ expect(channel.code).to eq('online')
+ expect(channel.name).to eq('Online Store')
+ expect(channel).to be_active
+ end
+
+ it 'is idempotent' do
+ store.save!
+ expect { store.send(:seed_default_channel) }.not_to change(Spree::Channel, :count)
+ end
+ end
+
+ describe '#default_channel' do
+ let(:store) { create(:store) }
+
+ it 'returns the seeded online channel' do
+ expect(store.default_channel.code).to eq('online')
+ end
+
+ it 'falls back to first active channel when no online channel exists' do
+ store.channels.find_by(code: 'online').update!(code: 'web')
+ expect(store.default_channel.code).to eq('web')
+ end
+ end
end
describe '#ensure_default_market' do