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 ability to manage which channel is the default one

Damian Legawiec36ee5a897087
diff --git a/CLAUDE.md b/CLAUDE.md
index 6a4b1a531c..a3bfd18614 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -463,6 +463,8 @@ pnpm dev # http://localhost:5173 (proxies /api/* to :3000)
3. **Follow `docs/plans/6.0-admin-spa.md`** for the three extension points (table registry, navigation registry, component injection) and the shadcn copy-paste ownership model.
4. **Wrap SDK calls in custom hooks** under `src/hooks/` (e.g. `useOrders`, `useProduct`) — never call `adminClient` directly from components.
+**Translations.** Every user-visible string in `@spree/dashboard` goes through i18next — page titles, headings, table column labels, button labels, empty states, toast messages, confirm dialog copy, select option labels, badges, status text, tooltips, helper text. Never hardcode English (or any language) into JSX, into table column definitions, or into dropdown option arrays. Keys live in `packages/dashboard/src/locales/en.json` (app-specific copy) or `packages/dashboard-core/src/locales/en.json` (cross-cutting: `admin.common.*`, `admin.fields.<attribute>.<facet>`). Reach for `i18n.t(...)` at module load (table definitions) and `useTranslation().t(...)` inside components. **Schemas in `src/schemas/` hold canonical values only — never label strings.** Build `{ value, label }` pairs at render time inside the component by mapping the canonical value list against translation keys. Same goes for the legacy Rails admin: every label/hint goes through `Spree.t` / `I18n.t` against `spree/admin/config/locales/en.yml`; run `bundle exec i18n-tasks normalize` after adding keys.
+
**Forms.** Raw React Hook Form with `<Field>` / `<Input>` / `<FieldError>` blocks. Drive each input explicitly with `form.register(...)` or a `<Controller>` for custom widgets so the form reads top-to-bottom. Wrap RHF's `handleSubmit` with a try/catch that calls `mapSpreeErrorsToForm` (`@/lib/form-errors`) to route 422 responses onto `form.formState.errors`: flat attribute keys become field errors with `aria-invalid` + `<FieldError>`; `:base` and nested keys land on `errors.root.message` so render a destructive banner at the top of the form.
```tsx
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index bd6e404899..18d80085c9 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -584,12 +584,20 @@ export interface ChannelCreateParams {
name: string
code: string
active?: boolean
+ default?: boolean
+ /**
+ * Class name of a +Spree::OrderRouting::Strategy::Base+ subclass, or +null+
+ * to inherit the store-level preference.
+ */
+ preferred_order_routing_strategy?: string | null
}
export interface ChannelUpdateParams {
name?: string
code?: string
active?: boolean
+ default?: boolean
+ preferred_order_routing_strategy?: string | null
}
export interface CustomerGroupUpdateParams {
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 46c3fc3fb8..fb14d11a75 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -191,6 +191,20 @@
"active": {
"label": "Active",
"help": "Inactive sales channels stop accepting orders and aren't matched by the X-Spree-Channel header."
+ },
+ "default": {
+ "label": "Default channel",
+ "help": "Exactly one channel per store is the default. Used as the fallback when no channel is selected and as the auto-publish target for new products."
+ },
+ "order_routing_strategy": {
+ "label": "Order routing strategy",
+ "help": "Overrides the store-level routing strategy for orders attributed to this channel. Leave blank to inherit.",
+ "inherit": "Inherit from store",
+ "options": {
+ "Spree::OrderRouting::Strategy::Rules": "Rules (ordered)",
+ "Spree::OrderRouting::Strategy::Reducer": "Reducer (greedy)",
+ "Spree::OrderRouting::Strategy::Legacy": "Legacy"
+ }
}
},
"invitation_acceptance": {
@@ -658,6 +672,8 @@
}
},
"channels": {
+ "title": "Sales channels",
+ "empty_message": "No sales channels yet",
"add_cta": "New sales channel",
"add_sheet_title": "Add sales channel",
"edit_sheet_title": "Edit sales channel",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx
index 6fd0a0079d..1985552928 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx
@@ -17,6 +17,11 @@ import {
FieldLabel,
Input,
RowActions,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
Sheet,
SheetContent,
SheetDescription,
@@ -44,6 +49,7 @@ import {
type ChannelFormValues,
channelFormSchema,
channelValuesToParams,
+ ORDER_ROUTING_STRATEGY_VALUES,
} from '@/schemas/channel'
import '@/tables/channels'
@@ -242,6 +248,8 @@ function EditChannelSheet({
name: channel.name,
code: channel.code,
active: channel.active,
+ default: channel.default,
+ preferred_order_routing_strategy: channel.preferred_order_routing_strategy ?? '',
})
}
}, [channel, form])
@@ -298,6 +306,14 @@ function EditChannelSheet({
function ChannelFormFields({ form }: { form: UseFormReturn<ChannelFormValues> }) {
const { t } = useTranslation()
const { errors } = form.formState
+
+ const strategyOptions = ORDER_ROUTING_STRATEGY_VALUES.map((value) => ({
+ value,
+ label:
+ value === ''
+ ? t('admin.fields.channel.order_routing_strategy.inherit')
+ : t(`admin.fields.channel.order_routing_strategy.options.${value}`),
+ }))
return (
<FieldGroup>
{errors.root?.message && (
@@ -348,6 +364,57 @@ function ChannelFormFields({ form }: { form: UseFormReturn<ChannelFormValues> })
/>
</div>
</Field>
+
+ <Field>
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col">
+ <FieldLabel htmlFor="default" className="cursor-pointer">
+ {t('admin.fields.channel.default.label')}
+ </FieldLabel>
+ <span className="text-xs text-muted-foreground">
+ {t('admin.fields.channel.default.help')}
+ </span>
+ </div>
+ <Controller
+ name="default"
+ control={form.control}
+ render={({ field }) => (
+ <Switch id="default" checked={!!field.value} onCheckedChange={field.onChange} />
+ )}
+ />
+ </div>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="preferred_order_routing_strategy">
+ {t('admin.fields.channel.order_routing_strategy.label')}
+ </FieldLabel>
+ <Controller
+ name="preferred_order_routing_strategy"
+ control={form.control}
+ render={({ field }) => (
+ <Select
+ items={strategyOptions}
+ value={field.value ?? ''}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger id="preferred_order_routing_strategy" className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {strategyOptions.map((o) => (
+ <SelectItem key={o.value || 'inherit'} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ <span className="text-xs text-muted-foreground">
+ {t('admin.fields.channel.order_routing_strategy.help')}
+ </span>
+ </Field>
</FieldGroup>
)
}
diff --git a/packages/dashboard/src/schemas/channel.ts b/packages/dashboard/src/schemas/channel.ts
index 526d306e57..6c8365e071 100644
--- a/packages/dashboard/src/schemas/channel.ts
+++ b/packages/dashboard/src/schemas/channel.ts
@@ -2,6 +2,18 @@ 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.
+export const ORDER_ROUTING_STRATEGY_VALUES = [
+ '',
+ 'Spree::OrderRouting::Strategy::Rules',
+ 'Spree::OrderRouting::Strategy::Reducer',
+ 'Spree::OrderRouting::Strategy::Legacy',
+] as const
+
+export type OrderRoutingStrategyValue = (typeof ORDER_ROUTING_STRATEGY_VALUES)[number]
+
export const channelFormSchema = z.object({
name: z.string().min(1, { error: requiredMessage('name') }),
code: z
@@ -11,6 +23,8 @@ export const channelFormSchema = z.object({
error: 'Lowercase letters, numbers, hyphens, underscores only',
}),
active: z.boolean(),
+ default: z.boolean(),
+ preferred_order_routing_strategy: z.string(),
})
export type ChannelFormValues = z.infer<typeof channelFormSchema>
@@ -19,6 +33,8 @@ export const CHANNEL_DEFAULTS: ChannelFormValues = {
name: '',
code: '',
active: true,
+ default: false,
+ preferred_order_routing_strategy: '',
}
export function channelValuesToParams(
@@ -28,5 +44,8 @@ export function channelValuesToParams(
name: v.name,
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/packages/dashboard/src/tables/channels.tsx b/packages/dashboard/src/tables/channels.tsx
index 02695d6b05..1bc27c037d 100644
--- a/packages/dashboard/src/tables/channels.tsx
+++ b/packages/dashboard/src/tables/channels.tsx
@@ -1,19 +1,20 @@
import type { Channel } from '@spree/admin-sdk'
import { defineTable } from '@spree/dashboard-core'
import { ActiveBadge, ResourceNameCell } from '@spree/dashboard-ui'
+import i18n from 'i18next'
import { RadioTowerIcon } from 'lucide-react'
defineTable<Channel>('channels', {
- title: 'Channels',
+ title: i18n.t('admin.pages.channels.title'),
searchParam: 'name_cont',
- searchPlaceholder: 'Search by name…',
+ searchPlaceholder: i18n.t('admin.common.search_placeholder'),
defaultSort: { field: 'name', direction: 'asc' },
emptyIcon: <RadioTowerIcon className="size-8 text-muted-foreground" />,
- emptyMessage: 'No channels yet',
+ emptyMessage: i18n.t('admin.pages.channels.empty_message'),
columns: [
{
key: 'name',
- label: 'Name',
+ label: i18n.t('admin.fields.name.label'),
sortable: true,
filterable: true,
default: true,
@@ -28,7 +29,7 @@ defineTable<Channel>('channels', {
},
{
key: 'code',
- label: 'Code',
+ label: i18n.t('admin.fields.channel.code.label'),
sortable: true,
filterable: true,
default: true,
@@ -37,12 +38,27 @@ defineTable<Channel>('channels', {
},
{
key: 'active',
- label: 'Status',
+ label: i18n.t('admin.fields.status.label'),
sortable: false,
filterable: true,
filterType: 'boolean',
default: true,
render: (channel) => <ActiveBadge active={channel.active} />,
},
+ {
+ key: 'default',
+ label: i18n.t('admin.fields.channel.default.label'),
+ sortable: true,
+ filterable: true,
+ filterType: 'boolean',
+ default: true,
+ render: (channel) => (
+ <ActiveBadge
+ active={channel.default}
+ activeLabel={i18n.t('admin.common.yes')}
+ dashWhenInactive
+ />
+ ),
+ },
],
})
diff --git a/packages/sdk/src/zod/generated/Channel.ts b/packages/sdk/src/zod/generated/Channel.ts
index 9e36d75a29..82ccf56ed8 100644
--- a/packages/sdk/src/zod/generated/Channel.ts
+++ b/packages/sdk/src/zod/generated/Channel.ts
@@ -6,6 +6,7 @@ export const ChannelSchema = z.object({
name: z.string(),
code: z.string(),
active: z.boolean(),
+ default: z.boolean(),
});
export type Channel = z.infer<typeof ChannelSchema>;
diff --git a/spree/admin/app/helpers/spree/admin/channels_helper.rb b/spree/admin/app/helpers/spree/admin/channels_helper.rb
new file mode 100644
index 0000000000..fcd0efb3e5
--- /dev/null
+++ b/spree/admin/app/helpers/spree/admin/channels_helper.rb
@@ -0,0 +1,16 @@
+module Spree
+ module Admin
+ module ChannelsHelper
+ # Concrete +Spree::OrderRouting::Strategy::Base+ subclasses presented in
+ # the channel edit form. A blank value clears the channel-level override
+ # and falls back to +Store#preferred_order_routing_strategy+.
+ def channel_order_routing_strategy_options
+ [
+ [Spree.t('admin.channels.order_routing_strategies.rules'), 'Spree::OrderRouting::Strategy::Rules'],
+ [Spree.t('admin.channels.order_routing_strategies.reducer'), 'Spree::OrderRouting::Strategy::Reducer'],
+ [Spree.t('admin.channels.order_routing_strategies.legacy'), 'Spree::OrderRouting::Strategy::Legacy']
+ ]
+ end
+ end
+ end
+end
diff --git a/spree/admin/app/views/spree/admin/channels/_form.html.erb b/spree/admin/app/views/spree/admin/channels/_form.html.erb
index 1417107484..617675c042 100644
--- a/spree/admin/app/views/spree/admin/channels/_form.html.erb
+++ b/spree/admin/app/views/spree/admin/channels/_form.html.erb
@@ -3,5 +3,11 @@
<%= f.spree_text_field :name, autofocus: f.object.new_record?, required: true %>
<%= f.spree_text_field :code, required: true, hint: Spree.t('admin.channels.code_hint') %>
<%= f.spree_check_box :active, label: Spree.t(:active) %>
+ <%= f.spree_check_box :default, label: Spree.t('admin.channels.default'), hint: Spree.t('admin.channels.default_hint') %>
+ <%= f.spree_select :preferred_order_routing_strategy,
+ options_for_select(channel_order_routing_strategy_options, f.object.preferred_order_routing_strategy),
+ { label: Spree.t('admin.channels.order_routing_strategy'),
+ help_bubble: Spree.t('admin.channels.order_routing_strategy_hint'),
+ include_blank: Spree.t('admin.channels.order_routing_strategy_inherit') } %>
</div>
</div>
diff --git a/spree/admin/config/initializers/spree_admin_tables.rb b/spree/admin/config/initializers/spree_admin_tables.rb
index c7c339d48b..9874e9d41d 100644
--- a/spree/admin/config/initializers/spree_admin_tables.rb
+++ b/spree/admin/config/initializers/spree_admin_tables.rb
@@ -1771,6 +1771,13 @@ Rails.application.config.after_initialize do
position: 30,
method: ->(c) { c.active? ? 'active' : 'inactive' }
+ Spree.admin.tables.channels.add :default,
+ label: :default,
+ type: :boolean,
+ sortable: true,
+ default: true,
+ position: 40
+
# ==========================================
# Register Refund Reasons table
# ==========================================
diff --git a/spree/admin/config/locales/en.yml b/spree/admin/config/locales/en.yml
index 6e50051f9a..8f420e79ca 100644
--- a/spree/admin/config/locales/en.yml
+++ b/spree/admin/config/locales/en.yml
@@ -77,6 +77,15 @@ en:
remove_tags: Remove tags
channels:
code_hint: A short, stable identifier (e.g. "online", "pos", "wholesale"). Used by API clients via the X-Spree-Channel header and for order attribution.
+ default: Default channel
+ default_hint: Exactly one channel per store is the default. Used as the fallback when no channel is selected and as the auto-publish target for new products.
+ order_routing_strategies:
+ legacy: Legacy
+ reducer: Reducer (greedy)
+ rules: Rules (ordered)
+ order_routing_strategy: Order routing strategy
+ order_routing_strategy_hint: Overrides the store-level routing strategy for orders attributed to this channel.
+ order_routing_strategy_inherit: Inherit from store
checkout_settings:
checkout_links:
description: Links to these pages will be displayed in the checkout footer.
diff --git a/spree/admin/spec/controllers/spree/admin/channels_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/channels_controller_spec.rb
index 001326946a..fdfc24128e 100644
--- a/spree/admin/spec/controllers/spree/admin/channels_controller_spec.rb
+++ b/spree/admin/spec/controllers/spree/admin/channels_controller_spec.rb
@@ -40,6 +40,17 @@ RSpec.describe Spree::Admin::ChannelsController, type: :controller do
expect(channel).to be_active
expect(response).to redirect_to(spree.edit_admin_channel_path(channel))
end
+
+ it 'promotes the new channel to default and demotes the previous default when default=1' do
+ previous_default = store.default_channel
+ expect(previous_default.default).to be true
+
+ post :create, params: { channel: channel_params.merge(default: '1') }
+
+ new_channel = Spree::Channel.find_by(code: 'wholesale')
+ expect(new_channel.default).to be true
+ expect(previous_default.reload.default).to be false
+ end
end
describe 'GET #edit' do
@@ -62,6 +73,36 @@ RSpec.describe Spree::Admin::ChannelsController, type: :controller do
expect(response).to redirect_to(spree.edit_admin_channel_path(channel))
expect(channel.reload.name).to eq('Point of Sale')
end
+
+ it 'promotes the channel to default and demotes the previous default' do
+ previous_default = store.default_channel
+ expect(channel.default).to be false
+
+ put :update, params: { id: channel.to_param, channel: { default: '1' } }
+
+ expect(response).to redirect_to(spree.edit_admin_channel_path(channel))
+ expect(channel.reload.default).to be true
+ expect(previous_default.reload.default).to be false
+ end
+
+ it 'persists preferred_order_routing_strategy when set to a concrete class' do
+ put :update, params: {
+ id: channel.to_param,
+ channel: { preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Rules' }
+ }
+
+ expect(response).to redirect_to(spree.edit_admin_channel_path(channel))
+ expect(channel.reload.preferred_order_routing_strategy).to eq('Spree::OrderRouting::Strategy::Rules')
+ end
+
+ it 'clears preferred_order_routing_strategy on blank submission (inherits from store)' do
+ channel.update!(preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Rules')
+
+ put :update, params: { id: channel.to_param, channel: { preferred_order_routing_strategy: '' } }
+
+ expect(response).to redirect_to(spree.edit_admin_channel_path(channel))
+ expect(channel.reload.preferred_order_routing_strategy).to be_blank
+ end
end
describe 'DELETE #destroy' do
diff --git a/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
index 7d722a9288..c6205101e1 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
@@ -44,7 +44,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :code, :active, :default, preferences: {})
+ params.permit(:name, :code, :active, :default, :preferred_order_routing_strategy)
end
private
diff --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.rb
index f1856b233d..19affe53d5 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
@@ -164,4 +164,68 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller do
expect(response).to have_http_status(:not_found)
end
end
+
+ describe 'POST #create' do
+ it 'creates a new channel and demotes the previous default when default=true' do
+ previous_default = store.default_channel
+ expect(previous_default).to be_present
+ expect(previous_default.default).to be true
+
+ post :create, params: {
+ name: 'Point of Sale', code: 'pos', active: true, default: true
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ new_channel = Spree::Channel.find_by(code: 'pos')
+ expect(new_channel.default).to be true
+ expect(previous_default.reload.default).to be false
+ end
+
+ it 'leaves the existing default in place when default=false' do
+ previous_default = store.default_channel
+
+ post :create, params: {
+ name: 'Point of Sale', code: 'pos', active: true, default: false
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(Spree::Channel.find_by(code: 'pos').default).to be false
+ expect(previous_default.reload.default).to be true
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'promotes a non-default channel and demotes the previous default' do
+ previous_default = store.default_channel
+ expect(channel.default).to be false
+
+ patch :update, params: { id: channel.prefixed_id, default: true }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(channel.reload.default).to be true
+ expect(previous_default.reload.default).to be false
+ end
+
+ it 'persists preferred_order_routing_strategy' do
+ patch :update, params: {
+ id: channel.prefixed_id,
+ preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Rules'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(channel.reload.preferred_order_routing_strategy).to eq('Spree::OrderRouting::Strategy::Rules')
+ end
+
+ it 'clears the channel-level override when set to null' do
+ channel.update!(preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Rules')
+
+ patch :update, params: {
+ id: channel.prefixed_id,
+ preferred_order_routing_strategy: nil
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(channel.reload.preferred_order_routing_strategy).to be_blank
+ end
+ end
end
diff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rb
index f425460c07..e1ec1658ac 100644
--- a/spree/core/app/models/spree/channel.rb
+++ b/spree/core/app/models/spree/channel.rb
@@ -30,12 +30,12 @@ module Spree
validates :name, :store, presence: true
validates :code, presence: true, uniqueness: { scope: spree_base_uniqueness_scope + [:store_id] }
- # Model-level guard mirroring the partial unique index. Necessary on
- # MySQL (no partial indexes); harmless duplication of the DB constraint
- # on Postgres/SQLite, giving a friendlier validation error.
- validates :default, uniqueness: { scope: spree_base_uniqueness_scope + [:store_id], if: :default? }
- after_save :demote_other_defaults, if: -> { default? && saved_change_to_default? }
+ # Demote any prior default in the same transaction so the partial unique
+ # index ("only one default per store") never sees two TRUE rows. Runs
+ # 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? }
after_create :ensure_default_order_routing_rules
scope :active, -> { where(active: true) }
diff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rb
index 9c29461c62..d18355f463 100644
--- a/spree/core/lib/spree/permitted_attributes.rb
+++ b/spree/core/lib/spree/permitted_attributes.rb
@@ -240,7 +240,7 @@ module Spree
@@shipping_category_attributes = [:name]
- @@channel_attributes = [:name, :code, :active]
+ @@channel_attributes = [:name, :code, :active, :default, :preferred_order_routing_strategy]
@@shipping_method_attributes = [:name, :admin_name, :code, :tracking_url, :tax_category_id, :display_on,
:estimated_transit_business_days_min, :estimated_transit_business_days_max,