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
Bug fixes for channels (#14124)
Damian Legawiecac679502f944
diff --git a/.claude/settings.local.json b/.claude/settings.local.jsonindex df3a85bcec..d61220f216 100644--- a/.claude/settings.local.json+++ b/.claude/settings.local.json@@ -10,7 +10,8 @@"WebFetch","WebSearch","Task",- "mcp__*"+ "mcp__*",+ "Read(//private/tmp/**)"],"deny": ["Bash(sudo *)",diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 18d80085c9..6fca3d86dd 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -582,7 +582,11 @@ export interface CustomerGroupCreateParams {export interface ChannelCreateParams {name: string- code: string+ /**+ * URL-safe slug. Optional — the backend derives it from +name+ when omitted+ * (e.g. "Point of Sale" → "point-of-sale").+ */+ code?: stringactive?: booleandefault?: boolean/**diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 470edf170d..90d07a2ff2 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -185,8 +185,8 @@"name": { "placeholder": "e.g. POS, Wholesale, Meta Shop" },"code": {"label": "Code",- "placeholder": "e.g. pos",- "help": "Stable identifier used by API clients via the X-Spree-Channel header and for order attribution. Lowercase letters, numbers, hyphens, underscores."+ "placeholder": "Auto-derived from name",+ "help": "Stable identifier used by API clients via the X-Spree-Channel header and for order attribution. Leave blank to auto-derive from the name. Lowercase letters, numbers, hyphens, underscores."},"active": {"label": "Active",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsxindex 1985552928..d3b69fb9f0 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx@@ -115,7 +115,7 @@ function ChannelsPage() {{key: 'delete',destructive: true,- visible: permissions.can('destroy', Subject.Channel),+ visible: permissions.can('destroy', Subject.Channel) && !channel.default,disabled: deleteMutation.isPending,onSelect: () => handleDelete(channel),},diff --git a/packages/dashboard/src/schemas/channel.ts b/packages/dashboard/src/schemas/channel.tsindex 6c8365e071..d2c8ea438e 100644--- a/packages/dashboard/src/schemas/channel.ts+++ b/packages/dashboard/src/schemas/channel.ts@@ -2,9 +2,7 @@ import type { ChannelCreateParams, ChannelUpdateParams } from '@spree/admin-sdk'import { requiredMessage } from '@spree/dashboard-ui'import { z } from 'zod/v4'-// Concrete +Spree::OrderRouting::Strategy::Base+ subclass names. The empty-// string clears the channel-level override → falls back to the store-level-// preference.+// Empty string clears the channel-level override → falls back to store.export const ORDER_ROUTING_STRATEGY_VALUES = ['','Spree::OrderRouting::Strategy::Rules',@@ -18,10 +16,10 @@ export const channelFormSchema = z.object({name: z.string().min(1, { error: requiredMessage('name') }),code: z.string()- .min(1, { error: requiredMessage('code') })- .regex(/^[a-z0-9_-]+$/i, {+ .regex(/^[a-z0-9_-]*$/i, {error: 'Lowercase letters, numbers, hyphens, underscores only',- }),+ })+ .optional(),active: z.boolean(),default: z.boolean(),preferred_order_routing_strategy: z.string(),@@ -42,10 +40,9 @@ export function channelValuesToParams(): ChannelCreateParams & ChannelUpdateParams {return {name: v.name,- code: v.code,+ ...(v.code ? { code: v.code } : {}),active: v.active,default: v.default,- // Empty string clears the channel-level override → falls back to store.preferred_order_routing_strategy: v.preferred_order_routing_strategy || null,}}diff --git a/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb b/spree/admin/app/views/spree/admin/products/form/_publishing.html.erbindex 5f38ec913e..4421a3d96a 100644--- a/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb+++ b/spree/admin/app/views/spree/admin/products/form/_publishing.html.erb@@ -53,6 +53,7 @@<%= f.fields_for :product_publications, publication, child_index: index do |pf| %><%= pf.hidden_field :id if publication.persisted? %><%= pf.hidden_field :channel_id, value: channel.id %>+ <% checked_by_default = publication.persisted? || (@product.new_record? && channel.default?) %><label class="flex items-center gap-3 rounded border px-3 py-2 cursor-pointer hover:bg-gray-50 text-sm"><%# The +_destroy+ hidden field defaults to 1 (= destroy/skip);the checkbox flips it to 0 (= keep/upsert) when checked.@@ -60,7 +61,7 @@emitting its own competing hidden field. %><%= pf.hidden_field :_destroy, value: '1', id: nil %><%= pf.check_box :_destroy,- { checked: publication.persisted?,+ { checked: checked_by_default,class: 'form-check-input m-0',include_hidden: false },'0', '1' %>diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rbindex ad0be7c44d..cfcfcb9923 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin_authentication.rb@@ -5,7 +5,6 @@ module Spreeextend ActiveSupport::Concernincluded do- before_action :authenticate_admin!after_action :set_no_store_cacheenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/base_controller.rbindex 78ea9b5eb7..1e81e59cd9 100644--- a/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/base_controller.rb@@ -5,6 +5,8 @@ module Spreeclass BaseController < Spree::Api::V3::BaseControllerinclude Spree::Api::V3::AdminAuthenticationinclude Spree::Api::V3::ScopedAuthorization++ before_action :authenticate_admin!endendenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rbindex 892231c94a..15d364717e 100644--- a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb@@ -11,6 +11,10 @@ module Spreeprotected+ def authenticate_request!+ authenticate_admin!+ end+# Render error from ServiceModule::Result, extracting ActiveModel::Errors# from the ResultError wrapper to get proper validation_error responses.def render_result_error(result)diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rbindex 5047b5be43..0dddb25129 100644--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb@@ -4,6 +4,9 @@ module Spreeclass ResourceController < BaseControllerinclude Spree::Api::V3::ParamsNormalizer+ # Must run before +set_resource+: +scope+'s +accessible_by+ depends on+ # the post-authentication +current_ability+.+ before_action :authenticate_request!before_action :set_parentbefore_action :set_resource, only: [:show, :update, :destroy]@@ -76,6 +79,10 @@ module Spreeprotected+ def authenticate_request!+ raise NotImplementedError, "#{self.class} must implement authenticate_request!"+ end+# No-op HTTP caching methods. Include Spree::Api::V3::HttpCaching# in specific controllers to enable HTTP caching for their actions.def cache_collection(_collection, **_options)diff --git a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rbindex 8e6ff7c8d5..bfb96e2256 100644--- a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb@@ -29,7 +29,7 @@ module Spreedef filters_cache_keyproducts_table = Spree::Product.table_name- stats = current_store.products.active(current_currency)+ stats = current_store.products.available(Time.current, current_currency).pick(Arel.sql("MAX(#{products_table}.updated_at)"), Arel.sql("COUNT(DISTINCT #{products_table}.id)"))max_updated = stats&.first&.to_iproduct_count = stats&.last || 0@@ -50,7 +50,7 @@ module Spreeenddef filters_scope- scope = current_store.products.active(current_currency)+ scope = current_store.products.available(Time.current, current_currency)scope = scope.in_category(category) if category.present?scope.accessible_by(current_ability, :show)enddiff --git a/spree/api/app/controllers/spree/api/v3/store/products_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products_controller.rbindex f9bb4aa34c..32a0bedf26 100644--- a/spree/api/app/controllers/spree/api/v3/store/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/products_controller.rb@@ -29,7 +29,7 @@ module Spreeenddef scope- super.active(Spree::Current.currency)+ super.available(Time.current, Spree::Current.currency)end# these scopes are not automatically picked by ar_lazy_preload gem and we need to explicitly include themdiff --git a/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/store/resource_controller.rbindex 0e179ac3ee..35989571c7 100644--- a/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb@@ -8,8 +8,11 @@ module Spreeclass ResourceController < Spree::Api::V3::ResourceControllerinclude Spree::Api::V3::ChannelResolution- # Require publishable API key for all Store API requests- before_action :authenticate_api_key!+ protected++ def authenticate_request!+ authenticate_api_key!+ endendendenddiff --git a/spree/api/spec/controllers/concerns/spree/api/v3/admin_authentication_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/admin_authentication_spec.rbnew file mode 100644index 0000000000..0b01fb6da9--- /dev/null+++ b/spree/api/spec/controllers/concerns/spree/api/v3/admin_authentication_spec.rb@@ -0,0 +1,129 @@+require 'spec_helper'++# Covers AdminAuthentication using TaxCategoriesController as a representative+# Admin::ResourceController — the mechanic applies to every admin endpoint.+RSpec.describe Spree::Api::V3::Admin::TaxCategoriesController, type: :controller do+ render_views++ include_context 'API v3 Admin'++ let!(:tax_category) { create(:tax_category, name: 'Standard') }++ describe 'secret API key authentication' do+ context 'with a valid key' do+ before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }++ it 'authenticates and resolves to the ApiKeyAbility' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ expect(controller.send(:current_api_key)).to eq(secret_api_key)+ expect(controller.send(:current_ability)).to be_a(Spree::ApiKeyAbility)+ end+ end++ context 'with no key and no JWT' do+ it 'returns 401' do+ get :index, as: :json++ expect(response).to have_http_status(:unauthorized)+ end+ end++ context 'with an unknown key' do+ before { request.headers['X-Spree-Api-Key'] = 'sk_does_not_exist' }++ it 'returns 401' do+ get :index, as: :json++ expect(response).to have_http_status(:unauthorized)+ end+ end++ context 'when the key belongs to a different store' do+ let(:other_store) { create(:store, default: false, code: 'other') }+ let(:foreign_key) { create(:api_key, :secret, store: other_store) }++ before { request.headers['X-Spree-Api-Key'] = foreign_key.plaintext_token }++ it 'returns 401 (cross-store keys are rejected)' do+ get :index, as: :json++ expect(response).to have_http_status(:unauthorized)+ end+ end+ end++ # Regression: +set_resource+ ran before +authenticate_admin!+, so+ # +current_ability+ was the unauthenticated +Spree::Ability+ and+ # +scope.accessible_by+ returned no rows → 404 on show/update/destroy.+ describe 'auth ordering — +authenticate_request!+ runs before +set_resource+' do+ before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }++ it 'GET show returns 200 (not 404)' do+ get :show, params: { id: tax_category.prefixed_id }, as: :json+ expect(response).to have_http_status(:ok)+ end++ it 'PATCH update returns 200 (not 404)' do+ patch :update, params: { id: tax_category.prefixed_id, name: 'Reduced' }, as: :json+ expect(response).to have_http_status(:ok)+ expect(tax_category.reload.name).to eq('Reduced')+ end++ it 'DELETE destroy returns 204 (not 404)' do+ delete :destroy, params: { id: tax_category.prefixed_id }, as: :json+ expect(response).to have_http_status(:no_content)+ end++ it 'declares +authenticate_request!+ before +set_resource+ in the callback chain' do+ callbacks = described_class._process_action_callbacks+ .select { |c| c.kind == :before }+ .map(&:filter)+ auth_index = callbacks.index(:authenticate_request!)+ set_resource_index = callbacks.index(:set_resource)++ expect(auth_index).to be < set_resource_index+ end+ end++ describe 'touch throttling for secret keys' do+ before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }++ context 'when last_used_at is nil' do+ before { secret_api_key.update_column(:last_used_at, nil) }++ it 'enqueues MarkAsUsed' do+ expect { get :index, as: :json }+ .to have_enqueued_job(Spree::ApiKeys::MarkAsUsed).with(secret_api_key.id, instance_of(ActiveSupport::TimeWithZone))+ end+ end++ context 'when last_used_at is older than 1 hour' do+ before { secret_api_key.update_column(:last_used_at, 2.hours.ago) }++ it 'enqueues MarkAsUsed' do+ expect { get :index, as: :json }+ .to have_enqueued_job(Spree::ApiKeys::MarkAsUsed).with(secret_api_key.id, instance_of(ActiveSupport::TimeWithZone))+ end+ end++ context 'when last_used_at is within the last hour' do+ before { secret_api_key.update_column(:last_used_at, 30.minutes.ago) }++ it 'does not enqueue MarkAsUsed' do+ expect { get :index, as: :json }.not_to have_enqueued_job(Spree::ApiKeys::MarkAsUsed)+ end+ end+ end++ describe 'response headers' do+ before { request.headers['X-Spree-Api-Key'] = secret_api_key.plaintext_token }++ it 'sets Cache-Control: private, no-store on admin responses' do+ get :index, as: :json++ expect(response.headers['Cache-Control']).to eq('private, no-store')+ end+ end+enddiff --git a/spree/api/spec/controllers/concerns/spree/api/v3/channel_resolution_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/channel_resolution_spec.rbindex d9bc6a0ed5..dccb117bec 100644--- a/spree/api/spec/controllers/concerns/spree/api/v3/channel_resolution_spec.rb+++ b/spree/api/spec/controllers/concerns/spree/api/v3/channel_resolution_spec.rb@@ -27,6 +27,14 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller doexpect(resolved_channel).to eq(pos_channel)end+ it 'resolves channel when the header arrives as ASCII-8BIT bytes' do+ request.headers['x-spree-channel'] = String.new('pos').force_encoding(Encoding::ASCII_8BIT)+ get :index++ expect(response).to have_http_status(:ok)+ expect(resolved_channel).to eq(pos_channel)+ end+it 'resolves channel from X-Spree-Channel header by prefixed ID' dorequest.headers['x-spree-channel'] = pos_channel.prefixed_idget :indexdiff --git a/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rbindex 19affe53d5..0d4bcc1791 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb@@ -228,4 +228,23 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller doexpect(channel.reload.preferred_order_routing_strategy).to be_blankendend++ describe 'DELETE #destroy' do+ it 'destroys a non-default channel' do+ expect { delete :destroy, params: { id: channel.prefixed_id }, as: :json }+ .to change(Spree::Channel, :count).by(-1)++ expect(response).to have_http_status(:no_content)+ end++ it 'refuses to delete the default channel with 422' do+ default_channel = store.default_channel++ expect { delete :destroy, params: { id: default_channel.prefixed_id }, as: :json }+ .not_to change(Spree::Channel, :count)++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('validation_error')+ end+ endenddiff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rbindex e1ec1658ac..82afd5a852 100644--- a/spree/core/app/models/spree/channel.rb+++ b/spree/core/app/models/spree/channel.rb@@ -23,7 +23,8 @@ module Spreeattribute :active, :boolean, default: true- normalizes :code, with: ->(value) { value.to_s.parameterize.presence }+ # HTTP headers arrive as ASCII-8BIT; +parameterize+ raises on those.+ normalizes :code, with: ->(value) { value.to_s.dup.force_encoding(Encoding::UTF_8).parameterize.presence }before_validation :backfill_code_from_name, if: -> { code.blank? && name.present? }before_validation :promote_first_channel_to_default@@ -36,6 +37,7 @@ module Spree# before save so MySQL — which can't enforce a partial unique index — also# arrives at a single default without relying on DB constraints.before_save :demote_other_defaults, if: -> { default? && will_save_change_to_default? }+ before_destroy :ensure_not_defaultafter_create :ensure_default_order_routing_rulesscope :active, -> { where(active: true) }@@ -109,8 +111,21 @@ module Spreecountend+ # @return [Boolean]+ def can_be_deleted?+ !default?+ end+private+ def ensure_not_default+ return if can_be_deleted?+ return if destroyed_by_association.present?++ errors.add(:base, Spree.t('errors.messages.cannot_delete_default_channel'))+ throw :abort+ end+def backfill_code_from_nameself.code = nameenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 9adff733f9..7befcbe9e3 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1136,6 +1136,7 @@ en:errors:messages:blank: can't be blank+ cannot_delete_default_channel: Default channel cannot be deleted. Promote another channel to default first.cannot_remove_icon: Cannot remove imagechannel_store_mismatch: must belong to the same storecould_not_create_taxon: Could not create taxondiff --git a/spree/core/spec/lib/tasks/publications_spec.rb b/spree/core/spec/lib/tasks/publications_spec.rbindex 9aa0a77e3a..866277d338 100644--- a/spree/core/spec/lib/tasks/publications_spec.rb+++ b/spree/core/spec/lib/tasks/publications_spec.rb@@ -80,7 +80,7 @@ describe 'spree:upgrade:populate_publications' dobefore dodowngrade!(product, default_store)# Strip channels off +other_store+ to simulate the warning path.- other_store.channels.destroy_all+ other_store.channels.delete_allSpree::StoreProduct.create!(product: product, store: other_store)enddiff --git a/spree/core/spec/models/spree/channel_spec.rb b/spree/core/spec/models/spree/channel_spec.rbindex 145ab7fb3a..5f08517549 100644--- a/spree/core/spec/models/spree/channel_spec.rb+++ b/spree/core/spec/models/spree/channel_spec.rb@@ -28,6 +28,11 @@ RSpec.describe Spree::Channel, type: :model doexpect(channel.code).to eq('my-channel')end+ it 'normalizes ASCII-8BIT codes without raising' do+ ascii8 = String.new('pos').force_encoding(Encoding::ASCII_8BIT)+ expect { described_class.find_by(code: ascii8) }.not_to raise_error+ end+it 'requires code unique within a store' dodescribed_class.create!(store: store, name: 'POS', code: 'pos')duplicate = described_class.new(store: store, name: 'POS 2', code: 'pos')@@ -54,7 +59,7 @@ RSpec.describe Spree::Channel, type: :model dodescribe '.active scope' doit 'filters active channels only' do- fresh_store = create(:store).tap { |s| s.channels.destroy_all }+ fresh_store = create(:store).tap { |s| s.channels.delete_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)@@ -84,6 +89,30 @@ RSpec.describe Spree::Channel, type: :model doendend+ describe '#can_be_deleted?' do+ let(:fresh_store) { create(:store).tap { |s| s.channels.delete_all } }+ let!(:default_channel) { described_class.create!(store: fresh_store, name: 'Default', code: 'online', default: true) }+ let!(:secondary) { described_class.create!(store: fresh_store, name: 'POS', code: 'pos') }++ it 'is true for non-default channels' do+ expect(secondary.can_be_deleted?).to be true+ end++ it 'is false for the default channel' do+ expect(default_channel.can_be_deleted?).to be false+ end++ it 'blocks +destroy+ on the default channel and surfaces an error' do+ expect(default_channel.destroy).to be false+ expect(default_channel.errors[:base]).to include(/cannot be deleted/i)+ expect(described_class.find_by(id: default_channel.id)).to eq(default_channel)+ end++ it 'allows destroying non-default channels' do+ expect { secondary.destroy! }.to change(described_class, :count).by(-1)+ end+ end+describe '#ensure_default_order_routing_rules' doit 'creates the three built-in rules in priority order on create' doexpect { described_class.create!(store: store, name: 'POS', code: 'pos') }diff --git a/spree/core/spec/models/spree/product_publication_spec.rb b/spree/core/spec/models/spree/product_publication_spec.rbindex d2cab16a2c..deecfe39b5 100644--- a/spree/core/spec/models/spree/product_publication_spec.rb+++ b/spree/core/spec/models/spree/product_publication_spec.rb@@ -9,7 +9,8 @@ RSpec.describe Spree::ProductPublication, type: :model dolet(:other_channel) { other_store.default_channel }# A second channel on the *same* store as +product+, so we can build a# second publication against the same product without colliding with the- # default publication the create-callback already attached.+ # default-channel publication the +:product+ factory attached for test+ # convenience.let(:secondary_channel) { create(:channel, store: store, code: 'pos', name: 'POS') }describe 'validations' do