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 channel-based price rule filtering (#14236)

Damian Legawiec343d46a77a01
diff --git a/packages/admin-sdk/src/types/generated/PriceRule.ts b/packages/admin-sdk/src/types/generated/PriceRule.ts
index 45900afcd8..0aca60d22b 100644
--- a/packages/admin-sdk/src/types/generated/PriceRule.ts
+++ b/packages/admin-sdk/src/types/generated/PriceRule.ts
@@ -1,7 +1,7 @@
// Typelizer digest cbc9397d33f0e796562f7f1ef7586420
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
-import type {Market, CustomerGroup, Customer} from '@/types'
+import type {Market, CustomerGroup, Channel, Customer} from '@/types'
interface PriceRule {
id: string;
@@ -15,6 +15,7 @@ interface PriceRule {
description: string | null;
markets?: Array<Market>;
customer_groups?: Array<CustomerGroup>;
+ channels?: Array<Channel>;
customers?: Array<Customer>;
}
diff --git a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
index 580259ff7a..fe6821a138 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
@@ -624,6 +624,12 @@ const RULE_EMBEDS = [
pick: (d: PriceRuleFormDraft) => d.markets,
label: (m: { name?: string | null; id: string }) => m.name ?? m.id,
},
+ {
+ prefKey: 'channel_ids',
+ pick: (d: PriceRuleFormDraft) => d.channels,
+ label: (c: { name?: string | null; code?: string | null; id: string }) =>
+ c.name ?? c.code ?? c.id,
+ },
] as const
const PREFS_SHOWN_VIA_EMBED: ReadonlySet<string> = new Set(RULE_EMBEDS.map((e) => e.prefKey))
diff --git a/packages/dashboard/src/components/spree/price-list-editors/register.ts b/packages/dashboard/src/components/spree/price-list-editors/register.ts
index c0caccc466..0db63ede61 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/register.ts
+++ b/packages/dashboard/src/components/spree/price-list-editors/register.ts
@@ -1,4 +1,5 @@
import { registerSlot } from '@spree/dashboard-core'
+import { ChannelRuleEditor } from './rule-channel'
import { CustomerRuleEditor } from './rule-customer'
import { CustomerGroupRuleEditor } from './rule-customer-group'
import { MarketRuleEditor } from './rule-market'
@@ -33,3 +34,8 @@ registerSlot(ruleFormSlot('market_rule'), {
id: 'builtin',
component: MarketRuleEditor,
})
+
+registerSlot(ruleFormSlot('channel_rule'), {
+ id: 'builtin',
+ component: ChannelRuleEditor,
+})
diff --git a/packages/dashboard/src/components/spree/price-list-editors/rule-channel.tsx b/packages/dashboard/src/components/spree/price-list-editors/rule-channel.tsx
new file mode 100644
index 0000000000..7bbacdc5a2
--- /dev/null
+++ b/packages/dashboard/src/components/spree/price-list-editors/rule-channel.tsx
@@ -0,0 +1,54 @@
+import type { Channel } from '@spree/admin-sdk'
+import { ResourceMultiAutocomplete } from '@spree/dashboard-core'
+import { Field, FieldGroup, FieldLabel } from '@spree/dashboard-ui'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { EditorShell } from '@/components/spree/promotion-editors/editor-shell'
+import { channelAutocompleteProps } from '@/hooks/use-channels'
+import type { PriceRuleEditorContext } from './types'
+
+/**
+ * Multi-select channel picker for the Channel price rule. Seeds from
+ * `draft.channels` (the serializer embed, prefixed `ch_…` IDs) because
+ * `preferences.channel_ids` holds raw integer IDs server-side. Writes the
+ * selected ids back to `preferences.channel_ids` and the resolved records to
+ * `draft.channels` for the rule summary.
+ */
+export function ChannelRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {
+ const { t } = useTranslation()
+ // Seed from `draft.channels` (the embed) — `preferences.channel_ids`
+ // holds raw integer IDs server-side while the embed carries the prefixed
+ // `ch_…` IDs the picker round-trips.
+ const [channelIds, setChannelIds] = useState<string[]>(() =>
+ (draft.channels ?? []).map((c) => c.id),
+ )
+ const [channels, setChannels] = useState<Channel[]>(draft.channels ?? [])
+
+ function handleSave() {
+ onSave({
+ ...draft,
+ preferences: { ...draft.preferences, channel_ids: channelIds },
+ channels,
+ })
+ onClose()
+ }
+
+ return (
+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>
+ <FieldGroup>
+ <Field>
+ <FieldLabel>{t('admin.fields.price_rule.channels.label')}</FieldLabel>
+ <ResourceMultiAutocomplete
+ {...channelAutocompleteProps('price-rule-channels')}
+ value={channelIds}
+ onChange={setChannelIds}
+ onResolvedOptionsChange={setChannels}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t('admin.fields.price_rule.channels.help')}
+ </p>
+ </Field>
+ </FieldGroup>
+ </EditorShell>
+ )
+}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 3ce3e4c4a6..6eda1095a7 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -341,6 +341,10 @@
"markets": {
"label": "الأسواق",
"help": "اتركه فارغًا لتطبيق هذه القاعدة في كل سوق."
+ },
+ "channels": {
+ "label": "قنوات البيع",
+ "help": "اتركه فارغًا لتطبيق هذه القاعدة على كل قناة بيع."
}
},
"stock_location": {
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 2f5f0aaee7..efd7f02728 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -293,6 +293,10 @@
"markets": {
"label": "Märkte",
"help": "Leer lassen, um diese Regel in jedem Markt anzuwenden."
+ },
+ "channels": {
+ "label": "Vertriebskanäle",
+ "help": "Leer lassen, um diese Regel auf jeden Vertriebskanal anzuwenden."
}
},
"stock_location": {
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index f4706af5f8..b31b9776b5 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -344,6 +344,10 @@
"markets": {
"label": "Markets",
"help": "Leave empty to apply this rule in every market."
+ },
+ "channels": {
+ "label": "Sales channels",
+ "help": "Leave empty to apply this rule on every sales channel."
}
},
"stock_location": {
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index e13e490ec1..c011649feb 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -293,6 +293,10 @@
"markets": {
"label": "Marchés",
"help": "Laissez vide pour appliquer cette règle sur tous les marchés."
+ },
+ "channels": {
+ "label": "Canaux de vente",
+ "help": "Laissez vide pour appliquer cette règle à tous les canaux de vente."
}
},
"stock_location": {
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 8e68c9da10..06d7f7c237 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -293,6 +293,10 @@
"markets": {
"label": "Rynki",
"help": "Pozostaw puste, aby zastosować tę regułę na każdym rynku."
+ },
+ "channels": {
+ "label": "Kanały sprzedaży",
+ "help": "Pozostaw puste, aby zastosować tę regułę do każdego kanału sprzedaży."
}
},
"stock_location": {
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 73b69a223a..8baedad198 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -341,6 +341,10 @@
"markets": {
"label": "市场",
"help": "留空则此规则适用于所有市场。"
+ },
+ "channels": {
+ "label": "销售渠道",
+ "help": "留空则此规则适用于所有销售渠道。"
}
},
"stock_location": {
diff --git a/packages/dashboard/src/schemas/price-list.ts b/packages/dashboard/src/schemas/price-list.ts
index 0b9ba66f87..1b27bd2787 100644
--- a/packages/dashboard/src/schemas/price-list.ts
+++ b/packages/dashboard/src/schemas/price-list.ts
@@ -1,4 +1,5 @@
import type {
+ Channel,
Customer,
CustomerGroup,
Market,
@@ -41,6 +42,7 @@ export interface PriceRuleFormDraft {
customers?: Customer[]
customer_groups?: CustomerGroup[]
markets?: Market[]
+ channels?: Channel[]
}
const priceRuleDraftSchema: z.ZodType<PriceRuleFormDraft> = z.object({
@@ -54,6 +56,7 @@ const priceRuleDraftSchema: z.ZodType<PriceRuleFormDraft> = z.object({
customers: z.array(z.any()).optional(),
customer_groups: z.array(z.any()).optional(),
markets: z.array(z.any()).optional(),
+ channels: z.array(z.any()).optional(),
}) as unknown as z.ZodType<PriceRuleFormDraft>
export const priceListFormSchema = z
@@ -130,6 +133,7 @@ export function ruleDraftFromRule(rule: PriceRule): PriceRuleFormDraft {
customers: rule.customers ?? undefined,
customer_groups: rule.customer_groups ?? undefined,
markets: rule.markets ?? undefined,
+ channels: rule.channels ?? undefined,
}
}
diff --git a/spree/admin/app/views/spree/admin/price_rules/forms/_channel_rule.html.erb b/spree/admin/app/views/spree/admin/price_rules/forms/_channel_rule.html.erb
new file mode 100644
index 0000000000..ff766844a5
--- /dev/null
+++ b/spree/admin/app/views/spree/admin/price_rules/forms/_channel_rule.html.erb
@@ -0,0 +1,7 @@
+<div class="form-group">
+ <%= f.label :preferred_channel_ids, Spree.t(:channels) %>
+ <%= f.select :preferred_channel_ids,
+ current_store.channels.order(:name).pluck(:name, :id),
+ { selected: f.object.preferred_channel_ids },
+ { multiple: true, data: { controller: 'autocomplete-select' } } %>
+</div>
diff --git a/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb
index bd0aa8cdfa..7eae5078c0 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/price_rule_serializer.rb
@@ -44,6 +44,10 @@ module Spree
resource: Spree.api.admin_customer_group_serializer,
if: proc { |rule| rule.respond_to?(:customer_groups) }
+ many :channels,
+ resource: Spree.api.admin_channel_serializer,
+ if: proc { |rule| rule.respond_to?(:channels) }
+
many :users,
key: :customers,
resource: Spree.api.admin_customer_serializer,
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/price_rule_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/price_rule_serializer_spec.rb
index eb2ce60c00..bd54e5cd21 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/price_rule_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/price_rule_serializer_spec.rb
@@ -70,15 +70,37 @@ RSpec.describe Spree::Api::V3::Admin::PriceRuleSerializer do
end
end
+ describe 'channel rule' do
+ let(:channel) { create(:channel, store: store) }
+ let(:rule) do
+ r = Spree::PriceRules::ChannelRule.create!(price_list: price_list)
+ r.preferred_channel_ids = [channel.id]
+ r.save!
+ r
+ end
+
+ it 'embeds the related channels' do
+ ids = payload['channels'].map { |c| c['id'] }
+ expect(ids).to contain_exactly(channel.prefixed_id)
+ end
+
+ it 'does not embed unrelated associations' do
+ expect(payload).not_to have_key('markets')
+ expect(payload).not_to have_key('customer_groups')
+ expect(payload).not_to have_key('customers')
+ end
+ end
+
describe 'rule without embedded associations' do
let(:rule) do
Spree::PriceRules::VolumeRule.create!(price_list: price_list, preferred_min_quantity: 5)
end
- it 'omits all three embed keys' do
+ it 'omits all embed keys' do
expect(payload).not_to have_key('markets')
expect(payload).not_to have_key('customer_groups')
expect(payload).not_to have_key('customers')
+ expect(payload).not_to have_key('channels')
end
end
diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rb
index a945a2bd11..3e2c36e213 100644
--- a/spree/core/app/models/spree/current.rb
+++ b/spree/core/app/models/spree/current.rb
@@ -72,7 +72,8 @@ module Spree
currency: currency,
store: store,
zone: zone,
- market: market
+ market: market,
+ channel: channel
)
end
end
diff --git a/spree/core/app/models/spree/price_rules/channel_rule.rb b/spree/core/app/models/spree/price_rules/channel_rule.rb
new file mode 100644
index 0000000000..f9a5a9030e
--- /dev/null
+++ b/spree/core/app/models/spree/price_rules/channel_rule.rb
@@ -0,0 +1,36 @@
+module Spree
+ module PriceRules
+ class ChannelRule < Spree::PriceRule
+ # Stored as raw IDs. Accepts prefixed IDs (`ch_…`) from API
+ # callers and decodes them on write so eligibility checks compare
+ # against raw `channel_id` rows directly. Scope confines the
+ # existence check to the price-list's store so cross-store channel
+ # IDs can't sneak in.
+ preference :channel_ids, :array, default: [],
+ parse_on_set: normalize_id_preference(
+ klass: Spree::Channel,
+ scope: ->(rule) { rule.store.channels }
+ )
+
+ def channels
+ return [] if preferred_channel_ids.blank?
+
+ store.channels.where(id: preferred_channel_ids)
+ end
+
+ def applicable?(context)
+ # An empty preference means the rule is unrestricted, so it applies
+ # regardless of (and even without) a channel in the context.
+ return true if preferred_channel_ids.empty?
+ return false unless context.channel
+
+ # Compare as strings to support both integer and UUID primary keys
+ preferred_channel_ids.map(&:to_s).include?(context.channel.id.to_s)
+ end
+
+ def self.description
+ Spree.t('price_rules.channel_rule.description')
+ end
+ end
+ end
+end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 09694c4547..54b011681d 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1189,6 +1189,8 @@ en:
price_lists: Price Lists
price_range: Price Range
price_rules:
+ channel_rule:
+ description: Apply pricing based on the sales channel
customer_group_rule:
description: Apply pricing to specific customer groups
price_sack: Price Sack
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 0dab70a661..5708376900 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -201,7 +201,8 @@ module Spree
Spree::PriceRules::UserRule,
Spree::PriceRules::CustomerGroupRule,
Spree::PriceRules::VolumeRule,
- Spree::PriceRules::MarketRule
+ Spree::PriceRules::MarketRule,
+ Spree::PriceRules::ChannelRule
]
Rails.application.config.spree.promotions.actions = [
diff --git a/spree/core/lib/spree/core/pricing/context.rb b/spree/core/lib/spree/core/pricing/context.rb
index e8d7dc568f..a4dac72b24 100644
--- a/spree/core/lib/spree/core/pricing/context.rb
+++ b/spree/core/lib/spree/core/pricing/context.rb
@@ -1,7 +1,7 @@
module Spree
module Pricing
class Context
- attr_reader :variant, :currency, :store, :zone, :market, :user, :quantity, :date, :order
+ attr_reader :variant, :currency, :store, :zone, :market, :channel, :user, :quantity, :date, :order
# Initializes the context
# @param variant [Spree::Variant]
@@ -9,16 +9,18 @@ module Spree
# @param store [Spree::Store]
# @param zone [Spree::Zone]
# @param market [Spree::Market]
+ # @param channel [Spree::Channel]
# @param user [Spree::User]
# @param quantity [Integer]
# @param date [Time]
# @param order [Spree::Order]
- def initialize(variant: nil, currency:, store: nil, zone: nil, market: nil, user: nil, quantity: nil, date: nil, order: nil)
+ def initialize(variant: nil, currency:, store: nil, zone: nil, market: nil, channel: nil, user: nil, quantity: nil, date: nil, order: nil)
@variant = variant
@currency = currency
@store = store || Spree::Current.store
@zone = zone || Spree::Current.zone
@market = market || Spree::Current.market
+ @channel = channel || Spree::Current.channel
@user = user
@quantity = quantity
@date = date || Time.current
@@ -39,6 +41,7 @@ module Spree
currency: order.currency,
store: order.store,
zone: order.tax_zone || Spree::Zone.default_tax,
+ channel: order.channel,
user: order.user,
quantity: quantity || order.line_items.find_by(variant: variant)&.quantity,
order: order
@@ -56,6 +59,7 @@ module Spree
store&.id,
zone&.id,
market&.id,
+ channel&.id,
user&.id,
quantity,
date&.to_i
diff --git a/spree/core/lib/spree/testing_support/factories/price_rule_factory.rb b/spree/core/lib/spree/testing_support/factories/price_rule_factory.rb
index 4e09f8ee99..8e2a12507c 100644
--- a/spree/core/lib/spree/testing_support/factories/price_rule_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/price_rule_factory.rb
@@ -55,5 +55,15 @@ FactoryBot.define do
market_ids { [] }
end
end
+
+ factory :channel_price_rule, class: Spree::PriceRules::ChannelRule do
+ after(:build) do |rule, evaluator|
+ rule.preferred_channel_ids = evaluator.channel_ids if evaluator.respond_to?(:channel_ids)
+ end
+
+ transient do
+ channel_ids { [] }
+ end
+ end
end
end
diff --git a/spree/core/spec/lib/spree/core/pricing/context_spec.rb b/spree/core/spec/lib/spree/core/pricing/context_spec.rb
index e492d70156..4395a4b054 100644
--- a/spree/core/spec/lib/spree/core/pricing/context_spec.rb
+++ b/spree/core/spec/lib/spree/core/pricing/context_spec.rb
@@ -8,6 +8,7 @@ module Spree
let(:store) { @default_store }
let(:zone) { create(:zone) }
let(:market) { create(:market, store: store) }
+ let(:channel) { create(:channel, store: store) }
let(:user) { create(:user) }
let(:quantity) { 5 }
let(:date) { Time.zone.parse('2024-01-15 12:00:00') }
@@ -23,6 +24,7 @@ module Spree
store: store,
zone: zone,
market: market,
+ channel: channel,
user: user,
quantity: quantity,
date: date
@@ -35,6 +37,7 @@ module Spree
expect(subject.store).to eq(store)
expect(subject.zone).to eq(zone)
expect(subject.market).to eq(market)
+ expect(subject.channel).to eq(channel)
expect(subject.user).to eq(user)
expect(subject.quantity).to eq(quantity)
expect(subject.date).to eq(date)
@@ -231,6 +234,7 @@ module Spree
store: store,
zone: zone,
market: market,
+ channel: channel,
user: user,
quantity: quantity,
date: specific_date
@@ -246,6 +250,7 @@ module Spree
store.id,
zone.id,
market.id,
+ channel.id,
user.id,
quantity,
specific_date.to_i
@@ -271,6 +276,7 @@ module Spree
]
expected_parts << Spree::Current.zone.id if Spree::Current.zone
expected_parts << Spree::Current.market.id if Spree::Current.market
+ expected_parts << Spree::Current.channel.id if Spree::Current.channel
expected_parts << Time.current.to_i
expect(subject.cache_key).to eq(expected_parts.join('/'))
@@ -299,6 +305,7 @@ module Spree
]
expected_parts << Spree::Current.zone.id if Spree::Current.zone
expected_parts << Spree::Current.market.id if Spree::Current.market
+ expected_parts << Spree::Current.channel.id if Spree::Current.channel
expected_parts << user.id
expected_parts << quantity
expected_parts << Time.current.to_i
diff --git a/spree/core/spec/models/spree/price_rules/channel_rule_spec.rb b/spree/core/spec/models/spree/price_rules/channel_rule_spec.rb
new file mode 100644
index 0000000000..adc4d4353b
--- /dev/null
+++ b/spree/core/spec/models/spree/price_rules/channel_rule_spec.rb
@@ -0,0 +1,92 @@
+require 'spec_helper'
+
+describe Spree::PriceRules::ChannelRule, type: :model do
+ let(:price_list) { create(:price_list) }
+ let(:rule) { create(:channel_price_rule, price_list: price_list) }
+ # Channels are store-scoped via `parse_on_set: normalize_id_preference(scope: …)`,
+ # so all channels referenced here live in the same store as the rule.
+ let(:channel) { create(:channel, store: price_list.store) }
+ let(:variant) { create(:variant) }
+
+ describe '#applicable?' do
+ context 'when channel_ids preference is empty' do
+ before { rule.preferred_channel_ids = [] }
+
+ it 'returns true for any channel' do
+ context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', channel: channel)
+ expect(rule.applicable?(context)).to be true
+ end
+
+ it 'returns true even when the context has no channel' do
+ # An unrestricted rule applies everywhere, including channel-less
+ # contexts. Stub the fallback so no channel is inferred.
+ allow(Spree::Current).to receive(:channel).and_return(nil)
+ context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', channel: nil)
+ expect(rule.applicable?(context)).to be true
+ end
+ end
+
+ context 'when channel_ids preference is set' do
+ before { rule.preferred_channel_ids = [channel.id] }
+
+ it 'returns true when context channel matches' do
+ context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', channel: channel)
+ expect(rule.applicable?(context)).to be true
+ end
+
+ it 'returns false when context channel does not match' do
+ other_channel = create(:channel, store: price_list.store)
+ context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', channel: other_channel)
+ expect(rule.applicable?(context)).to be false
+ end
+
+ it 'returns false when context has no channel' do
+ # `Spree::Pricing::Context` falls back to `Spree::Current.channel`
+ # when none is passed, so stub the fallback to truly mimic the
+ # no-channel case.
+ allow(Spree::Current).to receive(:channel).and_return(nil)
+ context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', channel: nil)
+ expect(rule.applicable?(context)).to be false
+ end
+ end
+ end
+
+ describe '#preferred_channel_ids=' do
+ it 'decodes prefixed channel IDs to raw IDs' do
+ rule.preferred_channel_ids = [channel.prefixed_id]
+ expect(rule.preferred_channel_ids).to eq([channel.id.to_s])
+ end
+
+ it 'accepts a comma-separated string' do
+ other_channel = create(:channel, store: price_list.store)
+ rule.preferred_channel_ids = "#{channel.prefixed_id},#{other_channel.prefixed_id}"
+ expect(rule.preferred_channel_ids).to contain_exactly(channel.id.to_s, other_channel.id.to_s)
+ end
+
+ it 'raises when given an unknown prefixed ID' do
+ expect { rule.preferred_channel_ids = ['ch_doesnotexist'] }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+
+ it 'rejects a channel that belongs to another store' do
+ other_store = create(:store)
+ cross_store_channel = create(:channel, store: other_store)
+ expect {
+ rule.preferred_channel_ids = [cross_store_channel.prefixed_id]
+ }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+ end
+
+ describe '#channels' do
+ let(:other_channel) { create(:channel, store: price_list.store) }
+
+ it 'returns the channels matching the preferred IDs' do
+ rule.preferred_channel_ids = [channel.id, other_channel.id]
+ expect(rule.channels).to contain_exactly(channel, other_channel)
+ end
+
+ it 'returns empty when no channels are set' do
+ rule.preferred_channel_ids = []
+ expect(rule.channels).to be_empty
+ end
+ end
+end