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 and Market promotion rules (#14239)

Damian Legawiecaf65170f9519
diff --git a/packages/admin-sdk/src/types/generated/PromotionRule.ts b/packages/admin-sdk/src/types/generated/PromotionRule.ts
index 16a708cb96..0cf1ec951b 100644
--- a/packages/admin-sdk/src/types/generated/PromotionRule.ts
+++ b/packages/admin-sdk/src/types/generated/PromotionRule.ts
@@ -1,7 +1,7 @@
// Typelizer digest 216b085a4b19c589b137ef282f9f50aa
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
-import type {Product, Category, Customer, CustomerGroup, Country} from '@/types'
+import type {Product, Category, Customer, CustomerGroup, Country, Channel, Market} from '@/types'
interface PromotionRule {
id: string;
@@ -20,6 +20,8 @@ interface PromotionRule {
customers?: Array<Customer>;
customer_groups?: Array<CustomerGroup>;
countries?: Array<Country>;
+ channels?: Array<Channel>;
+ markets?: Array<Market>;
}
export default PromotionRule;
diff --git a/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx b/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx
index d6aec180f1..46b365f74d 100644
--- a/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx
+++ b/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx
@@ -787,6 +787,8 @@ function RuleSummary({ draft }: { draft: PromotionRuleFormDraft }) {
const customers = nameList(draft.customers, customerLabel)
const groups = nameList(draft.customer_groups)
const countries = nameList(draft.countries)
+ const channels = nameList(draft.channels)
+ const markets = nameList(draft.markets)
if (products) parts.push(products)
else if (draft.product_ids?.length)
@@ -808,6 +810,8 @@ function RuleSummary({ draft }: { draft: PromotionRuleFormDraft }) {
if (groups) parts.push(groups)
if (countries) parts.push(countries)
+ if (channels) parts.push(channels)
+ if (markets) parts.push(markets)
// Fallback for preference-only rules (Currency, ItemTotal, FirstOrder,
// OneUsePerUser, UserLoggedIn, OptionValue, …) — these don't carry
@@ -827,6 +831,8 @@ const RULE_PREFS_SHOWN_ELSEWHERE = new Set([
'country_isos', // surfaced via `countries` records
'country_id',
'country_iso',
+ 'channel_ids', // surfaced via `channels` records
+ 'market_ids', // surfaced via `markets` records
])
function formatPreferencesSummary(draft: PromotionRuleFormDraft): string | null {
diff --git a/packages/dashboard/src/components/spree/promotion-editors/register.ts b/packages/dashboard/src/components/spree/promotion-editors/register.ts
index c65e2e20c2..6715deaab0 100644
--- a/packages/dashboard/src/components/spree/promotion-editors/register.ts
+++ b/packages/dashboard/src/components/spree/promotion-editors/register.ts
@@ -1,8 +1,10 @@
import { registerSlot } from '@spree/dashboard-core'
import { AdjustmentActionEditor } from './action-adjustment'
import { CategoryRuleEditor } from './rule-category'
+import { ChannelRuleEditor } from './rule-channel'
import { CountryRuleEditor } from './rule-country'
import { CustomerGroupRuleEditor } from './rule-customer-group'
+import { MarketRuleEditor } from './rule-market'
import { ProductRuleEditor } from './rule-product'
import { UserRuleEditor } from './rule-user'
import { actionFormSlot, ruleFormSlot } from './types'
@@ -46,6 +48,16 @@ registerSlot(ruleFormSlot('country'), {
component: CountryRuleEditor,
})
+registerSlot(ruleFormSlot('channel'), {
+ id: 'builtin',
+ component: ChannelRuleEditor,
+})
+
+registerSlot(ruleFormSlot('market'), {
+ id: 'builtin',
+ component: MarketRuleEditor,
+})
+
// Both adjustment actions wrap a calculator and share the same editor.
registerSlot(actionFormSlot('create_adjustment'), {
id: 'builtin',
diff --git a/packages/dashboard/src/components/spree/promotion-editors/rule-channel.tsx b/packages/dashboard/src/components/spree/promotion-editors/rule-channel.tsx
new file mode 100644
index 0000000000..64391efd32
--- /dev/null
+++ b/packages/dashboard/src/components/spree/promotion-editors/rule-channel.tsx
@@ -0,0 +1,47 @@
+import type { Channel } from '@spree/admin-sdk'
+import { ResourceMultiAutocomplete, useTranslation } from '@spree/dashboard-core'
+import { Field, FieldGroup, FieldLabel } from '@spree/dashboard-ui'
+import { useState } from 'react'
+import { channelAutocompleteProps } from '@/hooks/use-channels'
+import { EditorShell } from './editor-shell'
+import type { PromotionRuleEditorContext } from './types'
+
+/**
+ * Multi-select channel picker for the promotion Channel 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 }: PromotionRuleEditorContext) {
+ const { t } = useTranslation()
+ 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.promotions.rules.channel.label')}</FieldLabel>
+ <ResourceMultiAutocomplete
+ {...channelAutocompleteProps('promotion-rule-channels')}
+ value={channelIds}
+ onChange={setChannelIds}
+ onResolvedOptionsChange={setChannels}
+ />
+ </Field>
+ </FieldGroup>
+ </EditorShell>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/promotion-editors/rule-market.tsx b/packages/dashboard/src/components/spree/promotion-editors/rule-market.tsx
new file mode 100644
index 0000000000..5c451e885a
--- /dev/null
+++ b/packages/dashboard/src/components/spree/promotion-editors/rule-market.tsx
@@ -0,0 +1,48 @@
+import type { Market } from '@spree/admin-sdk'
+import { MarketMultiCombobox, useTranslation } from '@spree/dashboard-core'
+import { Field, FieldGroup, FieldLabel } from '@spree/dashboard-ui'
+import { useMemo, useState } from 'react'
+import { useAllMarkets } from '@/hooks/use-markets'
+import { EditorShell } from './editor-shell'
+import type { PromotionRuleEditorContext } from './types'
+
+/**
+ * Multi-select market picker for the promotion Market rule. Seeds from
+ * `draft.markets` (the serializer embed) because `preferences.market_ids`
+ * holds raw integer IDs server-side while the embed exposes the prefixed
+ * `mkt_…` form the picker round-trips.
+ */
+export function MarketRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
+ const { t } = useTranslation()
+ const { markets } = useAllMarkets()
+
+ const [marketIds, setMarketIds] = useState<string[]>(() => (draft.markets ?? []).map((m) => m.id))
+
+ const selectedMarkets = useMemo<Market[]>(
+ () =>
+ marketIds
+ .map((id) => markets.find((m) => m.id === id))
+ .filter((m): m is Market => Boolean(m)),
+ [marketIds, markets],
+ )
+
+ function handleSave() {
+ onSave({
+ ...draft,
+ preferences: { ...draft.preferences, market_ids: marketIds },
+ markets: selectedMarkets,
+ })
+ onClose()
+ }
+
+ return (
+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>
+ <FieldGroup>
+ <Field>
+ <FieldLabel>{t('admin.promotions.rules.market.label')}</FieldLabel>
+ <MarketMultiCombobox markets={markets} value={marketIds} onValueChange={setMarketIds} />
+ </Field>
+ </FieldGroup>
+ </EditorShell>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/promotion-editors/types.ts b/packages/dashboard/src/components/spree/promotion-editors/types.ts
index 1c7e72bb88..64ba84a0e1 100644
--- a/packages/dashboard/src/components/spree/promotion-editors/types.ts
+++ b/packages/dashboard/src/components/spree/promotion-editors/types.ts
@@ -1,8 +1,10 @@
import type {
Category,
+ Channel,
Country,
Customer,
CustomerGroup,
+ Market,
PreferenceField,
Product,
PromotionAction,
@@ -40,6 +42,8 @@ export interface PromotionRuleFormDraft extends PromotionRuleDraft {
customers?: Customer[]
customer_groups?: CustomerGroup[]
countries?: Country[]
+ channels?: Channel[]
+ markets?: Market[]
}
/** Mirrors `PromotionRuleFormDraft` for actions. */
@@ -186,6 +190,8 @@ export function ruleDraftFromRule(rule: PromotionRule): PromotionRuleFormDraft {
customers: rule.customers,
customer_groups: rule.customer_groups,
countries: rule.countries,
+ channels: rule.channels,
+ markets: rule.markets,
}
}
@@ -225,6 +231,8 @@ export function ruleDraftToPayload(draft: PromotionRuleFormDraft): PromotionRule
customers: ______,
customer_groups: _______,
countries: ________,
+ channels: _________,
+ markets: __________,
...rest
} = draft
return rest
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 6eda1095a7..f413b17015 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -767,6 +767,12 @@
"search_placeholder": "بحث عن الدول…",
"empty": "لا توجد بلدان متطابقة"
},
+ "channel": {
+ "label": "القنوات"
+ },
+ "market": {
+ "label": "الأسواق"
+ },
"product": {
"label": "منتجات",
"search_placeholder": "البحث عن المنتجات بالاسم…",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index efd7f02728..13c818260f 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -710,6 +710,12 @@
"search_placeholder": "Länder suchen…",
"empty": "Keine passenden Länder"
},
+ "channel": {
+ "label": "Kanäle"
+ },
+ "market": {
+ "label": "Märkte"
+ },
"product": {
"label": "Produkte",
"search_placeholder": "Produkte nach Namen suchen…",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index b31b9776b5..963add5ec0 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -767,6 +767,12 @@
"search_placeholder": "Search countries…",
"empty": "No countries match"
},
+ "channel": {
+ "label": "Channels"
+ },
+ "market": {
+ "label": "Markets"
+ },
"product": {
"label": "Products",
"search_placeholder": "Search products by name…",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index c011649feb..2a7a9711c1 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -710,6 +710,12 @@
"search_placeholder": "Rechercher des pays…",
"empty": "Aucun pays ne correspond"
},
+ "channel": {
+ "label": "Canaux"
+ },
+ "market": {
+ "label": "Marchés"
+ },
"product": {
"label": "Produits",
"search_placeholder": "Rechercher des produits par nom…",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 06d7f7c237..5deff001e0 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -710,6 +710,12 @@
"search_placeholder": "Szukaj krajów…",
"empty": "Brak pasujących krajów"
},
+ "channel": {
+ "label": "Kanały"
+ },
+ "market": {
+ "label": "Rynki"
+ },
"product": {
"label": "Produkty",
"search_placeholder": "Szukaj produktów po nazwie…",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 8baedad198..0369330c84 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -767,6 +767,12 @@
"search_placeholder": "搜索国家/地区…",
"empty": "没有匹配的国家/地区"
},
+ "channel": {
+ "label": "渠道"
+ },
+ "market": {
+ "label": "市场"
+ },
"product": {
"label": "商品",
"search_placeholder": "按名称搜索商品…",
diff --git a/spree/admin/app/helpers/spree/admin/base_helper.rb b/spree/admin/app/helpers/spree/admin/base_helper.rb
index 8d475eb1a5..4a43cc7656 100644
--- a/spree/admin/app/helpers/spree/admin/base_helper.rb
+++ b/spree/admin/app/helpers/spree/admin/base_helper.rb
@@ -365,6 +365,11 @@ module Spree
return Spree.t(:none) if market_ids.empty?
Spree::Market.where(id: market_ids).pluck(:name).join(', ')
+ when :channel_ids
+ channel_ids = Array(value).reject(&:blank?).map(&:to_i)
+ return Spree.t(:none) if channel_ids.empty?
+
+ Spree::Channel.where(id: channel_ids).pluck(:name).join(', ')
when :user_ids
user_ids = Array(value).reject(&:blank?).map(&:to_i)
return Spree.t(:none) if user_ids.empty?
diff --git a/spree/admin/app/views/spree/admin/promotion_rules/forms/_channel.html.erb b/spree/admin/app/views/spree/admin/promotion_rules/forms/_channel.html.erb
new file mode 100644
index 0000000000..ff766844a5
--- /dev/null
+++ b/spree/admin/app/views/spree/admin/promotion_rules/forms/_channel.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/admin/app/views/spree/admin/promotion_rules/forms/_market.html.erb b/spree/admin/app/views/spree/admin/promotion_rules/forms/_market.html.erb
new file mode 100644
index 0000000000..659bbf4a30
--- /dev/null
+++ b/spree/admin/app/views/spree/admin/promotion_rules/forms/_market.html.erb
@@ -0,0 +1,7 @@
+<div class="form-group">
+ <%= f.label :preferred_market_ids, Spree.t(:markets) %>
+ <%= f.select :preferred_market_ids,
+ current_store.markets.order(:name).pluck(:name, :id),
+ { selected: f.object.preferred_market_ids },
+ { multiple: true, data: { controller: 'autocomplete-select' } } %>
+</div>
diff --git a/spree/admin/spec/controllers/spree/admin/promotion_rules_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/promotion_rules_controller_spec.rb
index 543be95143..19c6f9d74a 100644
--- a/spree/admin/spec/controllers/spree/admin/promotion_rules_controller_spec.rb
+++ b/spree/admin/spec/controllers/spree/admin/promotion_rules_controller_spec.rb
@@ -28,6 +28,20 @@ RSpec.describe Spree::Admin::PromotionRulesController, type: :controller do
expect(assigns(:promotion_rule).class).to eq(rule_type.constantize)
end
end
+
+ context 'when the channel rule type is provided' do
+ it 'renders the channel form successfully' do
+ get :new, params: { promotion_id: promotion.to_param, promotion_rule: { type: 'Spree::Promotion::Rules::Channel' } }
+ expect(response).to be_successful
+ end
+ end
+
+ context 'when the market rule type is provided' do
+ it 'renders the market form successfully' do
+ get :new, params: { promotion_id: promotion.to_param, promotion_rule: { type: 'Spree::Promotion::Rules::Market' } }
+ expect(response).to be_successful
+ end
+ end
end
describe 'POST #create' do
@@ -79,6 +93,36 @@ RSpec.describe Spree::Admin::PromotionRulesController, type: :controller do
expect(assigns(:promotion_rule).preferred_country_iso).to eq('US')
end
end
+
+ context 'with a channel rule' do
+ let(:channel) { create(:channel, store: store) }
+ let(:rule_params) do
+ {
+ type: 'Spree::Promotion::Rules::Channel',
+ preferred_channel_ids: [channel.id]
+ }
+ end
+
+ it 'creates the rule and stores the selected channel IDs' do
+ post :create, params: { promotion_id: promotion.to_param, promotion_rule: rule_params }
+ expect(assigns(:promotion_rule).preferred_channel_ids.map(&:to_s)).to eq([channel.id.to_s])
+ end
+ end
+
+ context 'with a market rule' do
+ let(:market) { create(:market, store: store) }
+ let(:rule_params) do
+ {
+ type: 'Spree::Promotion::Rules::Market',
+ preferred_market_ids: [market.id]
+ }
+ end
+
+ it 'creates the rule and stores the selected market IDs' do
+ post :create, params: { promotion_id: promotion.to_param, promotion_rule: rule_params }
+ expect(assigns(:promotion_rule).preferred_market_ids.map(&:to_s)).to eq([market.id.to_s])
+ end
+ end
end
describe 'GET #edit' do
diff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb
index 69fa408e3e..49adce8164 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_rule_serializer.rb
@@ -78,6 +78,14 @@ module Spree
many :countries,
resource: proc { Spree.api.admin_country_serializer },
if: proc { |rule| rule.respond_to?(:countries) }
+
+ many :channels,
+ resource: Spree.api.admin_channel_serializer,
+ if: proc { |rule| rule.respond_to?(:channels) }
+
+ many :markets,
+ resource: Spree.api.admin_market_serializer,
+ if: proc { |rule| rule.respond_to?(:markets) }
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/promotion_rules_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/promotion_rules_controller_spec.rb
index f213cadc1a..9309d2c831 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/promotion_rules_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/promotion_rules_controller_spec.rb
@@ -20,6 +20,36 @@ RSpec.describe Spree::Api::V3::Admin::PromotionRulesController, type: :controlle
expect(promotion.reload.promotion_rules.map(&:type)).to include('Spree::Promotion::Rules::FirstOrder')
end
+ it 'creates a channel rule, storing the selected channel IDs in preferences' do
+ channel = create(:channel, store: store)
+
+ post :create, params: {
+ promotion_id: promotion.prefixed_id,
+ type: 'channel',
+ preferences: { channel_ids: [channel.prefixed_id] }
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ rule = promotion.reload.promotion_rules.find { |r| r.is_a?(Spree::Promotion::Rules::Channel) }
+ expect(rule).to be_present
+ expect(rule.preferred_channel_ids.map(&:to_s)).to eq([channel.id.to_s])
+ end
+
+ it 'creates a market rule, storing the selected market IDs in preferences' do
+ market = create(:market, store: store)
+
+ post :create, params: {
+ promotion_id: promotion.prefixed_id,
+ type: 'market',
+ preferences: { market_ids: [market.prefixed_id] }
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ rule = promotion.reload.promotion_rules.find { |r| r.is_a?(Spree::Promotion::Rules::Market) }
+ expect(rule).to be_present
+ expect(rule.preferred_market_ids.map(&:to_s)).to eq([market.id.to_s])
+ end
+
it "404s for a promotion that belongs to another store" do
foreign_promotion = create(:promotion, stores: [create(:store)])
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb
index d9dce510a8..500a8f64e4 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/promotion_rule_serializer_spec.rb
@@ -38,4 +38,30 @@ RSpec.describe Spree::Api::V3::Admin::PromotionRuleSerializer do
expect(payload['preferences']['currency']).to eq('USD')
end
end
+
+ describe 'channel rule embeds' do
+ let(:channel) { create(:channel, store: store) }
+ let(:rule) do
+ build(:promotion_rule_channel, promotion: promotion, channel_ids: [channel.id]).tap(&:save!)
+ end
+
+ subject(:payload) { described_class.new(rule, params: base_params).to_h }
+
+ it 'embeds the selected channels with prefixed IDs' do
+ expect(payload['channels'].map { |c| c['id'] }).to contain_exactly(channel.prefixed_id)
+ end
+ end
+
+ describe 'market rule embeds' do
+ let(:market) { create(:market, store: store) }
+ let(:rule) do
+ build(:promotion_rule_market, promotion: promotion, market_ids: [market.id]).tap(&:save!)
+ end
+
+ subject(:payload) { described_class.new(rule, params: base_params).to_h }
+
+ it 'embeds the selected markets with prefixed IDs' do
+ expect(payload['markets'].map { |m| m['id'] }).to contain_exactly(market.prefixed_id)
+ end
+ end
end
diff --git a/spree/core/app/models/spree/promotion/rules/channel.rb b/spree/core/app/models/spree/promotion/rules/channel.rb
new file mode 100644
index 0000000000..dd84344282
--- /dev/null
+++ b/spree/core/app/models/spree/promotion/rules/channel.rb
@@ -0,0 +1,37 @@
+# A rule to limit a promotion based on the order's channel.
+module Spree
+ class Promotion
+ module Rules
+ class Channel < PromotionRule
+ # Stored as raw IDs. Accepts prefixed IDs (`ch_…`) from API
+ # callers and decodes them on write so eligibility checks compare
+ # against the order's raw `channel_id` directly. Scope confines the
+ # existence check to the promotion'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.promotion&.store&.channels || Spree::Channel.none }
+ )
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def channels
+ return Spree::Channel.none if preferred_channel_ids.blank?
+
+ promotion.store.channels.where(id: preferred_channel_ids)
+ end
+
+ def eligible?(order, _options = {})
+ return false if preferred_channel_ids.empty?
+ return true if preferred_channel_ids.map(&:to_s).include?(order.channel_id.to_s)
+
+ eligibility_errors.add(:base, eligibility_error_message(:no_matching_channel))
+ false
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/promotion/rules/market.rb b/spree/core/app/models/spree/promotion/rules/market.rb
new file mode 100644
index 0000000000..06c2fe503d
--- /dev/null
+++ b/spree/core/app/models/spree/promotion/rules/market.rb
@@ -0,0 +1,37 @@
+# A rule to limit a promotion based on the order's market.
+module Spree
+ class Promotion
+ module Rules
+ class Market < PromotionRule
+ # Stored as raw IDs. Accepts prefixed IDs (`mkt_…`) from API
+ # callers and decodes them on write so eligibility checks compare
+ # against the order's raw `market_id` directly. Scope confines the
+ # existence check to the promotion's store so cross-store market
+ # IDs can't sneak in.
+ preference :market_ids, :array, default: [],
+ parse_on_set: normalize_id_preference(
+ klass: Spree::Market,
+ scope: ->(rule) { rule.promotion&.store&.markets || Spree::Market.none }
+ )
+
+ def applicable?(promotable)
+ promotable.is_a?(Spree::Order)
+ end
+
+ def markets
+ return Spree::Market.none if preferred_market_ids.blank?
+
+ promotion.store.markets.where(id: preferred_market_ids)
+ end
+
+ def eligible?(order, _options = {})
+ return false if preferred_market_ids.empty?
+ return true if preferred_market_ids.map(&:to_s).include?(order.market_id.to_s)
+
+ eligibility_errors.add(:base, eligibility_error_message(:no_matching_market))
+ false
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 54b011681d..bea439d23c 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -735,6 +735,7 @@ en:
category: Category
change: Change
channel: Sales channel
+ channel_ids: Sales channels
channels: Sales channels
charged: Charged
checkout: Checkout
@@ -878,6 +879,8 @@ en:
missing_product: This coupon code can't be applied because you don't have all of the necessary products in your cart.
missing_taxon: You need to add a product from all applicable categories before applying this coupon code.
no_applicable_products: You need to add an applicable product before applying this coupon code.
+ no_matching_channel: This coupon code is not eligible for this sales channel.
+ no_matching_market: This coupon code is not eligible in your market.
no_matching_taxons: You need to add a product from an applicable category before applying this coupon code.
no_user_or_email_specified: You need to login or provide your email before applying this coupon code.
no_user_specified: You need to login before applying this coupon code.
@@ -1230,6 +1233,9 @@ en:
category:
description: Order includes products in specified categories
name: Categories
+ channel:
+ description: Limit to orders placed through specified channel(s)
+ name: Channel(s)
country:
description: Limit to orders with shipping address in a specific country
name: Country
@@ -1251,6 +1257,9 @@ en:
item_total:
description: Order total meets these criteria
name: Item total
+ market:
+ description: Limit to orders placed in specified market(s)
+ name: Market(s)
one_use_per_user:
description: Only One Use Per User
name: One Use Per User
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 5708376900..5d09a3e696 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -179,6 +179,8 @@ module Spree
Rails.application.config.spree.promotions.rules.concat [
Spree::Promotion::Rules::Currency,
Spree::Promotion::Rules::Country,
+ Spree::Promotion::Rules::Channel,
+ Spree::Promotion::Rules::Market,
Spree::Promotion::Rules::ItemTotal,
Spree::Promotion::Rules::Product,
Spree::Promotion::Rules::User,
diff --git a/spree/core/lib/spree/testing_support/factories/promotion_rule_factory.rb b/spree/core/lib/spree/testing_support/factories/promotion_rule_factory.rb
index 974d3f210d..be758f3baf 100644
--- a/spree/core/lib/spree/testing_support/factories/promotion_rule_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/promotion_rule_factory.rb
@@ -30,4 +30,28 @@ FactoryBot.define do
customer_group_ids { [] }
end
end
+
+ factory :promotion_rule_channel, class: Spree::Promotion::Rules::Channel do
+ association :promotion
+
+ 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
+
+ factory :promotion_rule_market, class: Spree::Promotion::Rules::Market do
+ association :promotion
+
+ after(:build) do |rule, evaluator|
+ rule.preferred_market_ids = evaluator.market_ids if evaluator.respond_to?(:market_ids)
+ end
+
+ transient do
+ market_ids { [] }
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/promotion/rules/channel_spec.rb b/spree/core/spec/models/spree/promotion/rules/channel_spec.rb
new file mode 100644
index 0000000000..813c8bb9f5
--- /dev/null
+++ b/spree/core/spec/models/spree/promotion/rules/channel_spec.rb
@@ -0,0 +1,81 @@
+require 'spec_helper'
+
+describe Spree::Promotion::Rules::Channel, type: :model do
+ let(:store) { @default_store }
+ let(:promotion) { create(:promotion, store: store) }
+ let(:rule) { described_class.new(promotion: promotion) }
+ let(:channel) { create(:channel, store: store) }
+ let(:other_channel) { create(:channel, store: store) }
+
+ describe '#applicable?' do
+ it 'returns true for orders' do
+ expect(rule.applicable?(build(:order))).to be true
+ end
+
+ it 'returns false for non-orders' do
+ expect(rule.applicable?('not an order')).to be false
+ end
+ end
+
+ describe '#eligible?' do
+ context 'when no channels are configured' do
+ before { rule.preferred_channel_ids = [] }
+
+ it 'is not eligible' do
+ expect(rule).not_to be_eligible(build(:order, store: store))
+ end
+ end
+
+ context "when the order's channel is in the configured list" do
+ before { rule.preferred_channel_ids = [channel.id] }
+
+ it 'is eligible' do
+ expect(rule).to be_eligible(build(:order, store: store, channel: channel))
+ end
+ end
+
+ context "when the order's channel is not in the configured list" do
+ before { rule.preferred_channel_ids = [channel.id] }
+
+ it 'is not eligible' do
+ expect(rule).not_to be_eligible(build(:order, store: store, channel: other_channel))
+ end
+ end
+
+ context 'when the order matches one of multiple configured channels' do
+ before { rule.preferred_channel_ids = [channel.id, other_channel.id] }
+
+ it 'is eligible' do
+ expect(rule).to be_eligible(build(:order, store: store, channel: other_channel))
+ end
+ end
+
+ context 'when configured with prefixed IDs' do
+ before { rule.preferred_channel_ids = [channel.prefixed_id] }
+
+ it 'decodes them and matches' do
+ expect(rule).to be_eligible(build(:order, store: store, channel: channel))
+ end
+ end
+ end
+
+ describe '#channels' do
+ it 'returns the configured channels scoped to the store' do
+ rule.preferred_channel_ids = [channel.id]
+ expect(rule.channels).to contain_exactly(channel)
+ end
+
+ it 'returns none when unconfigured' do
+ expect(rule.channels).to be_empty
+ end
+ end
+
+ context 'when configured with a channel from another store' do
+ let(:other_store) { create(:store) }
+ let(:foreign_channel) { create(:channel, store: other_store) }
+
+ it 'rejects the foreign ID' do
+ expect { rule.preferred_channel_ids = [foreign_channel.id] }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/promotion/rules/market_spec.rb b/spree/core/spec/models/spree/promotion/rules/market_spec.rb
new file mode 100644
index 0000000000..92ffca4059
--- /dev/null
+++ b/spree/core/spec/models/spree/promotion/rules/market_spec.rb
@@ -0,0 +1,81 @@
+require 'spec_helper'
+
+describe Spree::Promotion::Rules::Market, type: :model do
+ let(:store) { @default_store }
+ let(:promotion) { create(:promotion, store: store) }
+ let(:rule) { described_class.new(promotion: promotion) }
+ let(:market) { create(:market, store: store) }
+ let(:other_market) { create(:market, store: store) }
+
+ describe '#applicable?' do
+ it 'returns true for orders' do
+ expect(rule.applicable?(build(:order))).to be true
+ end
+
+ it 'returns false for non-orders' do
+ expect(rule.applicable?('not an order')).to be false
+ end
+ end
+
+ describe '#eligible?' do
+ context 'when no markets are configured' do
+ before { rule.preferred_market_ids = [] }
+
+ it 'is not eligible' do
+ expect(rule).not_to be_eligible(build(:order, store: store))
+ end
+ end
+
+ context "when the order's market is in the configured list" do
+ before { rule.preferred_market_ids = [market.id] }
+
+ it 'is eligible' do
+ expect(rule).to be_eligible(build(:order, store: store, market: market))
+ end
+ end
+
+ context "when the order's market is not in the configured list" do
+ before { rule.preferred_market_ids = [market.id] }
+
+ it 'is not eligible' do
+ expect(rule).not_to be_eligible(build(:order, store: store, market: other_market))
+ end
+ end
+
+ context 'when the order matches one of multiple configured markets' do
+ before { rule.preferred_market_ids = [market.id, other_market.id] }
+
+ it 'is eligible' do
+ expect(rule).to be_eligible(build(:order, store: store, market: other_market))
+ end
+ end
+
+ context 'when configured with prefixed IDs' do
+ before { rule.preferred_market_ids = [market.prefixed_id] }
+
+ it 'decodes them and matches' do
+ expect(rule).to be_eligible(build(:order, store: store, market: market))
+ end
+ end
+ end
+
+ describe '#markets' do
+ it 'returns the configured markets scoped to the store' do
+ rule.preferred_market_ids = [market.id]
+ expect(rule.markets).to contain_exactly(market)
+ end
+
+ it 'returns none when unconfigured' do
+ expect(rule.markets).to be_empty
+ end
+ end
+
+ context 'when configured with a market from another store' do
+ let(:other_store) { create(:store) }
+ let(:foreign_market) { create(:market, store: other_store) }
+
+ it 'rejects the foreign ID' do
+ expect { rule.preferred_market_ids = [foreign_market.id] }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+ end
+end