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
Fix Option Value promotion rule configuration in dashboard (#14549)
Damian Legawiec5a11190f05cc
diff --git a/packages/admin-sdk/src/types/generated/PromotionRule.ts b/packages/admin-sdk/src/types/generated/PromotionRule.tsindex eb9fc21a43..07da5afd81 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 2abc4070a19a02daecd2c482e72d9e88+// Typelizer digest b95459445f23419cfaf82c940e4c4428//// DO NOT MODIFY: This file was automatically generated by Typelizer.-import type {Product, Category, Customer, CustomerGroup, Country, Channel, Market} from '@/types'+import type {Product, Category, Customer, CustomerGroup, Country, Channel, Market, OptionValue} from '@/types'interface PromotionRule {id: string;@@ -15,6 +15,7 @@ interface PromotionRule {product_ids: Array<string> | null;category_ids: Array<string> | null;customer_ids: Array<string> | null;+ option_value_ids: Array<string> | null;products?: Array<Product>;categories?: Array<Category>;customers?: Array<Customer>;@@ -22,6 +23,7 @@ interface PromotionRule {countries?: Array<Country>;channels?: Array<Channel>;markets?: Array<Market>;+ option_values?: Array<OptionValue>;}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.tsxindex 69812a3823..f61ac70ecf 100644--- a/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx+++ b/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx@@ -61,6 +61,7 @@ import {TableRow,Textarea,} from '@spree/dashboard-ui'+import { optionValueLabel } from '../../../hooks/use-option-types'import {usePromotionActionTypes,usePromotionCouponCodes,@@ -809,6 +810,7 @@ function RuleSummary({ draft }: { draft: PromotionRuleFormDraft }) {const countries = nameList(draft.countries)const channels = nameList(draft.channels)const markets = nameList(draft.markets)+ const optionValues = nameList(draft.option_values, optionValueLabel)if (products) parts.push(products)else if (draft.product_ids?.length)@@ -832,6 +834,7 @@ function RuleSummary({ draft }: { draft: PromotionRuleFormDraft }) {if (countries) parts.push(countries)if (channels) parts.push(channels)if (markets) parts.push(markets)+ if (optionValues) parts.push(optionValues)// Fallback for preference-only rules (Currency, ItemTotal, FirstOrder,// OneUsePerUser, UserLoggedIn, OptionValue, …) — these don't carry@@ -853,6 +856,7 @@ const RULE_PREFS_SHOWN_ELSEWHERE = new Set(['country_code','channel_ids', // surfaced via `channels` records'market_ids', // surfaced via `markets` records+ 'eligible_values', // surfaced via `option_values` 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.tsindex 9d1b361f1c..6b9c9a28bd 100644--- a/packages/dashboard/src/components/spree/promotion-editors/register.ts+++ b/packages/dashboard/src/components/spree/promotion-editors/register.ts@@ -6,6 +6,7 @@ import { ChannelRuleEditor } from './rule-channel'import { CountryRuleEditor } from './rule-country'import { CustomerGroupRuleEditor } from './rule-customer-group'import { MarketRuleEditor } from './rule-market'+import { OptionValueRuleEditor } from './rule-option-value'import { ProductRuleEditor } from './rule-product'import { UserRuleEditor } from './rule-user'import { actionFormSlot, ruleFormSlot } from './types'@@ -59,6 +60,11 @@ registerSlot(ruleFormSlot('market'), {component: MarketRuleEditor,})+registerSlot(ruleFormSlot('option_value'), {+ id: 'builtin',+ component: OptionValueRuleEditor,+})+// 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-option-value.tsx b/packages/dashboard/src/components/spree/promotion-editors/rule-option-value.tsxnew file mode 100644index 0000000000..046a0ef447--- /dev/null+++ b/packages/dashboard/src/components/spree/promotion-editors/rule-option-value.tsx@@ -0,0 +1,62 @@+import type { OptionValue } from '@spree/admin-sdk'+import { ResourceMultiAutocomplete, useTranslation } from '@spree/dashboard-core'+import { Field, FieldGroup, FieldLabel } from '@spree/dashboard-ui'+import { useMemo, useState } from 'react'+import {+ filterOptionValues,+ optionValueLabel,+ useOptionTypes,+} from '../../../hooks/use-option-types'+import { EditorShell } from './editor-shell'+import type { PromotionRuleEditorContext } from './types'++export function OptionValueRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {+ const { t } = useTranslation()+ const { data: optionTypesData } = useOptionTypes()+ const allOptionValues = useMemo(+ () => optionTypesData?.data.flatMap((optionType) => optionType.option_values ?? []) ?? [],+ [optionTypesData],+ )++ const [optionValueIds, setOptionValueIds] = useState<string[]>(() =>+ (draft.option_values ?? []).map((optionValue) => optionValue.id),+ )+ const [optionValues, setOptionValues] = useState<OptionValue[]>(draft.option_values ?? [])++ function handleSave() {+ onSave({+ ...draft,+ preferences: { ...draft.preferences, eligible_values: optionValueIds },+ option_values: optionValues,+ })+ onClose()+ }++ return (+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>+ <FieldGroup>+ <Field>+ <FieldLabel>{t('admin.promotions.rules.option_value.label')}</FieldLabel>+ <ResourceMultiAutocomplete+ queryKey="promotion-rule-option-values"+ initialItems={allOptionValues}+ value={optionValueIds}+ onChange={setOptionValueIds}+ onResolvedOptionsChange={setOptionValues}+ search={(query) =>+ Promise.resolve({ data: filterOptionValues(allOptionValues, query) })+ }+ hydrate={(ids) =>+ Promise.resolve({+ data: allOptionValues.filter((optionValue) => ids.includes(optionValue.id)),+ })+ }+ getOptionLabel={optionValueLabel}+ placeholder={t('admin.promotions.rules.option_value.search_placeholder')}+ emptyText={t('admin.promotions.rules.option_value.empty')}+ />+ </Field>+ </FieldGroup>+ </EditorShell>+ )+}diff --git a/packages/dashboard/src/components/spree/promotion-editors/types.ts b/packages/dashboard/src/components/spree/promotion-editors/types.tsindex 64ba84a0e1..7b6c7a69ac 100644--- a/packages/dashboard/src/components/spree/promotion-editors/types.ts+++ b/packages/dashboard/src/components/spree/promotion-editors/types.ts@@ -5,6 +5,7 @@ import type {Customer,CustomerGroup,Market,+ OptionValue,PreferenceField,Product,PromotionAction,@@ -44,6 +45,7 @@ export interface PromotionRuleFormDraft extends PromotionRuleDraft {countries?: Country[]channels?: Channel[]markets?: Market[]+ option_values?: OptionValue[]}/** Mirrors `PromotionRuleFormDraft` for actions. */@@ -192,6 +194,7 @@ export function ruleDraftFromRule(rule: PromotionRule): PromotionRuleFormDraft {countries: rule.countries,channels: rule.channels,markets: rule.markets,+ option_values: rule.option_values,}}@@ -233,6 +236,7 @@ export function ruleDraftToPayload(draft: PromotionRuleFormDraft): PromotionRulecountries: ________,channels: _________,markets: __________,+ option_values: ___________,...rest} = draftreturn restdiff --git a/packages/dashboard/src/hooks/use-option-types.ts b/packages/dashboard/src/hooks/use-option-types.tsindex 102dc93cee..a5e5ad496e 100644--- a/packages/dashboard/src/hooks/use-option-types.ts+++ b/packages/dashboard/src/hooks/use-option-types.ts@@ -1,4 +1,9 @@-import type { OptionType, OptionTypeCreateParams, OptionTypeUpdateParams } from '@spree/admin-sdk'+import type {+ OptionType,+ OptionTypeCreateParams,+ OptionTypeUpdateParams,+ OptionValue,+} from '@spree/admin-sdk'import {adminClient,useResourceKey,@@ -8,6 +13,22 @@ import {import { useQuery, useQueryClient } from '@tanstack/react-query'import i18n from 'i18next'+/** Human-readable label for an option value, including its option type. */+export function optionValueLabel(optionValue: OptionValue): string {+ const typeLabel = optionValue.option_type_label ?? optionValue.option_type_name+ const valueLabel = optionValue.label ?? optionValue.name+ return typeLabel ? `${typeLabel}: ${valueLabel}` : valueLabel+}++/** Client-side filter for option-value pickers backed by a preloaded catalog. */+export function filterOptionValues(optionValues: OptionValue[], query: string): OptionValue[] {+ const normalized = query.trim().toLowerCase()+ if (!normalized) return optionValues+ return optionValues.filter((optionValue) =>+ optionValueLabel(optionValue).toLowerCase().includes(normalized),+ )+}+interface UseOptionTypesParams {page?: numberlimit?: numberdiff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 0ddc67b7eb..b979ed5552 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -4293,6 +4293,11 @@"market": {"label": "الأسواق"},+ "option_value": {+ "empty": "لا توجد قيم خيارات مطابقة",+ "label": "قيم الخيارات",+ "search_placeholder": "البحث عن قيم الخيارات…"+ },"product": {"empty": "لا توجد منتجات متطابقة","label": "منتجات",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex c044170965..50b5fe4cb0 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -4271,6 +4271,11 @@"market": {"label": "Märkte"},+ "option_value": {+ "empty": "Keine passenden Optionswerte",+ "label": "Optionswerte",+ "search_placeholder": "Optionswerte suchen…"+ },"product": {"empty": "Keine passenden Produkte","label": "Produkte",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 7aa996474c..f0ccc9961a 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -4271,6 +4271,11 @@"market": {"label": "Markets"},+ "option_value": {+ "empty": "No option values match",+ "label": "Option values",+ "search_placeholder": "Search option values…"+ },"product": {"empty": "No products match","label": "Products",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex e07c7d0e51..8ad8f57a66 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -4271,6 +4271,11 @@"market": {"label": "Marchés"},+ "option_value": {+ "empty": "Aucune valeur d'option correspondante",+ "label": "Valeurs d'option",+ "search_placeholder": "Rechercher des valeurs d'option…"+ },"product": {"empty": "Aucun produit ne correspond","label": "Produits",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 9a1cdeac62..e57fba2619 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -4325,6 +4325,11 @@"market": {"label": "Rynki"},+ "option_value": {+ "empty": "Brak pasujących wartości opcji",+ "label": "Wartości opcji",+ "search_placeholder": "Szukaj wartości opcji…"+ },"product": {"empty": "Brak pasujących produktów","label": "Produkty",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 3953657579..be58560c0a 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -4262,6 +4262,11 @@"market": {"label": "市场"},+ "option_value": {+ "empty": "没有匹配的选项值",+ "label": "选项值",+ "search_placeholder": "搜索选项值…"+ },"product": {"empty": "没有匹配的商品","label": "商品",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.rbindex d2518ccdf0..550e534811 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@@ -15,7 +15,8 @@ module Spreelabel: :string,product_ids: 'Array<string> | null',category_ids: 'Array<string> | null',- customer_ids: 'Array<string> | null'+ customer_ids: 'Array<string> | null',+ option_value_ids: 'Array<string> | null'attributes created_at: :iso8601, updated_at: :iso8601@@ -52,6 +53,10 @@ module Spreerule.users.map(&:prefixed_id) if rule.respond_to?(:users)end+ attribute :option_value_ids do |rule|+ rule.option_values.map(&:prefixed_id) if rule.respond_to?(:option_values)+ end+# Embed the related records so promotion-row summaries can render# names + extra info without a separate fetch. Rules that don't# carry a given collection (e.g. an ItemTotal rule has no@@ -85,6 +90,10 @@ module Spreemany :markets,resource: Spree.api.admin_market_serializer,if: proc { |rule| rule.respond_to?(:markets) }++ many :option_values,+ resource: proc { Spree.api.admin_option_value_serializer },+ if: proc { |rule| rule.respond_to?(:option_values) }endendenddiff --git a/spree/core/app/models/spree/promotion/rules/option_value.rb b/spree/core/app/models/spree/promotion/rules/option_value.rbindex 43dba11d24..896c261470 100644--- a/spree/core/app/models/spree/promotion/rules/option_value.rb+++ b/spree/core/app/models/spree/promotion/rules/option_value.rb@@ -4,33 +4,56 @@ module Spreeclass OptionValue < Spree::PromotionRuleMATCH_POLICIES = %w(any)preference :match_policy, :string, default: MATCH_POLICIES.first- preference :eligible_values, :array, default: [], parse_on_set: lambda { |values|- values.flat_map { |v| v.to_s.split(',').compact_blank.map(&:strip) }- }+ # Stored as raw Spree::OptionValue ids. Accepts prefixed IDs (`optval_…`)+ # from API callers and decodes them on write so eligibility checks compare+ # against stable option-value rows, not join-table ids that shift when+ # variants are reconfigured.+ preference :eligible_values, :array, default: [],+ parse_on_set: normalize_id_preference(klass: Spree::OptionValue)+ # @param promotable [Object]+ # @return [Boolean]def applicable?(promotable)promotable.is_a?(Spree::Order) || promotable.is_a?(Spree::Cart)end+ # @return [ActiveRecord::Relation<Spree::OptionValue>]+ def option_values+ return Spree::OptionValue.none if preferred_eligible_values.blank?++ Spree::OptionValue.where(id: preferred_eligible_values)+ end++ # @param promotable [Spree::Order, Spree::Cart]+ # @param _options [Hash]+ # @return [Boolean]def eligible?(promotable, _options = {})- return false if eligible_option_value_variant_ids.empty?+ return false if eligible_option_value_ids.empty?case preferred_match_policywhen 'any'- Spree::OptionValueVariant.where(id: eligible_option_value_variant_ids, variant_id: promotable.variant_ids).exists?+ Spree::OptionValueVariant.where(+ option_value_id: eligible_option_value_ids,+ variant_id: promotable.variant_ids+ ).exists?endend+ # @param line_item [Spree::LineItem]+ # @return [Boolean]def actionable?(line_item)- return false if eligible_option_value_variant_ids.empty?+ return false if eligible_option_value_ids.empty?- Spree::OptionValueVariant.where(id: eligible_option_value_variant_ids, variant_id: line_item.variant_id).exists?+ Spree::OptionValueVariant.where(+ option_value_id: eligible_option_value_ids,+ variant_id: line_item.variant_id+ ).exists?endprivate- def eligible_option_value_variant_ids- @eligible_option_value_variant_ids ||= preferred_eligible_values.map(&:to_s)+ def eligible_option_value_ids+ @eligible_option_value_ids ||= preferred_eligible_values.map(&:to_s)endendenddiff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.ymlindex 1a74e0deb3..ff3ce7c1e9 100644--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml@@ -275,6 +275,21 @@ steps:with one statement scoped to the rows still missing a code, so aninterrupted run picks up where it stopped.+ - id: migrate_promotion_option_value_rules+ name: "Rewrite Option Value promotion rules to stable option value ids"+ task: "spree:upgrade:migrate_promotion_option_value_rules"+ notes: |+ Spree 6.0 stores Option Value promotion rules against Spree::OptionValue+ ids. Upgrades from 5.6 may still carry join-row ids from+ spree_option_value_variants in the eligible_values preference — those+ rows shift whenever variants are reconfigured, so a saved rule can start+ matching different SKUs without warning.++ Rewrites each rule's eligible_values array in place, mapping legacy+ join-row ids to their option_value_id and leaving rows that already+ name an option value untouched. Idempotent — re-running is a no-op once+ every value resolves to an option value id.+- id: migrate_adjustments_to_typed_rowsname: "Convert adjustments to typed rows"task: "spree:migrate_adjustments_to_typed_rows"diff --git a/spree/core/lib/tasks/migrate_promotion_option_value_rules.rake b/spree/core/lib/tasks/migrate_promotion_option_value_rules.rakenew file mode 100644index 0000000000..5d5f5a8311--- /dev/null+++ b/spree/core/lib/tasks/migrate_promotion_option_value_rules.rake@@ -0,0 +1,124 @@+# frozen_string_literal: true++# 5.6 → 6.0: rewrite Option Value promotion rules that still store+# Spree::OptionValueVariant join-row ids into stable Spree::OptionValue ids.+module Spree+ # Rewrites legacy join-row ids in Option Value promotion rules. Ambiguous or+ # unresolvable ids are reported and left untouched so operators can review+ # affected rules before continuing.+ class PromotionOptionValueRulesMigrator+ Issue = Data.define(:rule_id, :raw_id, :kind)++ # @return [Integer] number of rules rewritten+ attr_reader :converted++ # @return [Array<Issue>] ids that could not be mapped+ attr_reader :issues++ # @param skip_failed [Boolean] when true, report issues but do not abort+ def initialize(skip_failed: false)+ @skip_failed = skip_failed+ @converted = 0+ @issues = []+ end++ # @return [void]+ def call+ total = Spree::Promotion::Rules::OptionValue.count++ Spree::Promotion::Rules::OptionValue.find_each do |rule|+ migrate_rule(rule)+ end++ report(total)+ end++ private++ # @param rule [Spree::Promotion::Rules::OptionValue]+ # @return [void]+ def migrate_rule(rule)+ raw = Array(rule.preferred_eligible_values).map(&:to_s).compact_blank+ return if raw.empty?++ mapped = []+ rule_issues = []++ raw.each do |raw_id|+ resolution = resolve_id(raw_id)+ case resolution+ in :ambiguous+ rule_issues << Issue.new(rule_id: rule.id, raw_id: raw_id, kind: :ambiguous)+ in :unresolved+ rule_issues << Issue.new(rule_id: rule.id, raw_id: raw_id, kind: :unresolved)+ in String+ mapped << resolution+ end+ end++ if rule_issues.any?+ @issues.concat(rule_issues)+ return+ end++ mapped.uniq!+ return if mapped == raw++ rule.update!(preferred_eligible_values: mapped)+ @converted += 1+ end++ # @param raw_id [String]+ # @return [String, :ambiguous, :unresolved]+ def resolve_id(raw_id)+ join_row = Spree::OptionValueVariant.find_by(id: raw_id)+ option_value = Spree::OptionValue.exists?(raw_id)++ if join_row && option_value+ :ambiguous+ elsif join_row+ join_row.option_value_id.to_s+ elsif option_value+ raw_id+ else+ :unresolved+ end+ end++ # @param total [Integer]+ # @return [void]+ def report(total)+ puts "Option Value promotion rules: #{@converted}/#{total} converted to option value ids"++ return if @issues.empty?++ puts " #{@issues.size} eligible value id(s) could not be migrated:"+ @issues.each do |issue|+ puts " rule ##{issue.rule_id} id #{issue.raw_id}: #{issue.kind}"+ end++ if @skip_failed+ report_skip_notice+ return+ end++ abort ' Re-run after fixing affected rules, or pass SKIP_FAILED_ROWS=true to continue without converting them.'+ end++ # @return [void]+ def report_skip_notice+ puts ' Continuing anyway (SKIP_FAILED_ROWS=true).'+ end+ end+end++namespace :spree do+ namespace :upgrade do+ desc 'Rewrite Option Value promotion rules from join-row ids to option value ids'+ task migrate_promotion_option_value_rules: :environment do+ Spree::PromotionOptionValueRulesMigrator.new(+ skip_failed: ENV['SKIP_FAILED_ROWS'] == 'true'+ ).call+ end+ end+enddiff --git a/spree/core/spec/lib/tasks/migrate_promotion_option_value_rules_spec.rb b/spree/core/spec/lib/tasks/migrate_promotion_option_value_rules_spec.rbnew file mode 100644index 0000000000..55eba6b15d--- /dev/null+++ b/spree/core/spec/lib/tasks/migrate_promotion_option_value_rules_spec.rb@@ -0,0 +1,135 @@+require 'spec_helper'+require 'rake'++Rake::Task.define_task(:environment)+load Spree::Core::Engine.root.join('lib', 'tasks', 'migrate_promotion_option_value_rules.rake')++describe 'spree:upgrade:migrate_promotion_option_value_rules' do+ subject { Rake::Task[task_name] }++ let(:task_name) { 'spree:upgrade:migrate_promotion_option_value_rules' }++ before { subject.reenable }++ it 'rewrites join-row ids to option value ids' do+ create_list(:option_value, 3)+ option_value = create(:option_value, name: 'Medium', presentation: 'Medium')+ variant = create(:variant, option_values: [option_value])+ join_row = Spree::OptionValueVariant.find_by!(variant: variant, option_value: option_value)++ rule = create(:promotion_rule_option_value)+ rule.update_columns(+ preferences: rule.preferences.merge(eligible_values: [join_row.id.to_s])+ )++ allow(Spree::OptionValue).to receive(:exists?).and_call_original+ allow(Spree::OptionValue).to receive(:exists?).with(join_row.id.to_s).and_return(false)++ subject.invoke++ expect(rule.reload.preferred_eligible_values).to eq([option_value.id.to_s])+ end++ it 'leaves rules that already store option value ids untouched' do+ option_value = create(:option_value)+ rule = create(:promotion_rule_option_value, preferred_eligible_values: [option_value.id.to_s])++ subject.invoke++ expect(rule.reload.preferred_eligible_values).to eq([option_value.id.to_s])+ end++ it 'aborts when an eligible value id cannot be resolved' do+ rule = create(:promotion_rule_option_value)+ rule.update_columns(+ preferences: rule.preferences.merge(eligible_values: ['999999999'])+ )++ expect { subject.invoke }.to raise_error(SystemExit)+ expect(rule.reload.preferred_eligible_values).to eq(['999999999'])+ end++ it 'aborts when an id matches both a join row and an option value' do+ option_value = create(:option_value, name: 'Small', presentation: 'Small')+ variant = create(:variant, option_values: [option_value])+ join_row = Spree::OptionValueVariant.find_by!(variant: variant, option_value: option_value)++ rule = create(:promotion_rule_option_value)+ rule.update_columns(+ preferences: rule.preferences.merge(eligible_values: [join_row.id.to_s])+ )++ allow(Spree::OptionValue).to receive(:exists?).and_call_original+ allow(Spree::OptionValue).to receive(:exists?).with(join_row.id.to_s).and_return(true)+ allow(Spree::OptionValue).to receive(:exists?).with(join_row.id).and_return(true)++ expect { subject.invoke }.to raise_error(SystemExit)+ expect(rule.reload.preferred_eligible_values).to eq([join_row.id.to_s])+ end++ it 'continues without aborting when SKIP_FAILED_ROWS is set' do+ option_value = create(:option_value, name: 'Large', presentation: 'Large')+ variant = create(:variant, option_values: [option_value])+ join_row = Spree::OptionValueVariant.find_by!(variant: variant, option_value: option_value)++ convertible_rule = create(:promotion_rule_option_value)+ convertible_rule.update_columns(+ preferences: convertible_rule.preferences.merge(eligible_values: [join_row.id.to_s])+ )++ allow(Spree::OptionValue).to receive(:exists?).and_call_original+ allow(Spree::OptionValue).to receive(:exists?).with(join_row.id.to_s).and_return(false)++ bad_rule = create(:promotion_rule_option_value)+ bad_rule.update_columns(+ preferences: bad_rule.preferences.merge(eligible_values: ['999999999'])+ )++ old = ENV['SKIP_FAILED_ROWS']+ ENV['SKIP_FAILED_ROWS'] = 'true'+ begin+ expect { subject.invoke }.not_to raise_error++ expect(convertible_rule.reload.preferred_eligible_values).to eq([option_value.id.to_s])+ expect(bad_rule.reload.preferred_eligible_values).to eq(['999999999'])+ ensure+ if old.nil?+ ENV.delete('SKIP_FAILED_ROWS')+ else+ ENV['SKIP_FAILED_ROWS'] = old+ end+ end+ end+end++describe Spree::PromotionOptionValueRulesMigrator do+ subject(:migrator) { described_class.new(skip_failed: skip_failed) }++ let(:skip_failed) { false }++ describe '#call' do+ it 'returns the number of converted rules via #converted' do+ option_value = create(:option_value)+ variant = create(:variant, option_values: [option_value])+ join_row = Spree::OptionValueVariant.find_by!(variant: variant, option_value: option_value)++ rule = create(:promotion_rule_option_value)+ rule.update_columns(+ preferences: rule.preferences.merge(eligible_values: [join_row.id.to_s])+ )++ allow(Spree::OptionValue).to receive(:exists?).and_call_original+ allow(Spree::OptionValue).to receive(:exists?).with(join_row.id.to_s).and_return(false)++ migrator.call++ expect(migrator.issues).to be_empty+ expect(rule.reload.preferred_eligible_values).to eq([option_value.id.to_s])+ if join_row.id.to_s == option_value.id.to_s+ expect(migrator.converted).to eq(0)+ else+ expect(migrator.converted).to eq(1)+ end+ end+ end+enddiff --git a/spree/core/spec/models/spree/promotion/rules/option_value_spec.rb b/spree/core/spec/models/spree/promotion/rules/option_value_spec.rbindex 1a16596f1c..acdaf87018 100644--- a/spree/core/spec/models/spree/promotion/rules/option_value_spec.rb+++ b/spree/core/spec/models/spree/promotion/rules/option_value_spec.rb@@ -4,16 +4,17 @@ describe Spree::Promotion::Rules::OptionValue dolet(:rule) { described_class.new }describe 'setting eligible values' do- let(:option_value_variant_ids) do- [- 'abc-123',- 'def-123, def-456,ghj-789 , '- ]+ let(:option_value) { create(:option_value) }++ it 'accepts prefixed option value ids' do+ rule.preferred_eligible_values = [option_value.prefixed_id]+ expect(rule.preferred_eligible_values).to eq([option_value.id.to_s])end- it 'parses ids' do- rule.preferred_eligible_values = option_value_variant_ids- expect(rule.preferred_eligible_values).to eq(['abc-123', 'def-123', 'def-456', 'ghj-789'])+ it 'rejects unknown ids' do+ expect {+ rule.preferred_eligible_values = ['optval_missing']+ }.to raise_error(ActiveRecord::RecordNotFound)endend@@ -42,15 +43,17 @@ describe Spree::Promotion::Rules::OptionValue docontext 'when there are any applicable line items' dobefore do- rule.preferred_eligible_values = [variant.option_value_variant_ids.first, 1233542]+ rule.preferred_eligible_values = [variant.option_values.first.id]endit { is_expected.to be true }endcontext 'when there are no applicable line items' do+ let(:other_option_value) { create(:option_value) }+before do- rule.preferred_eligible_values = [123235234, 4531236]+ rule.preferred_eligible_values = [other_option_value.id]endit { is_expected.to be false }@@ -73,53 +76,32 @@ describe Spree::Promotion::Rules::OptionValue do))end- let(:option_value_medium) do- create(- :option_value,- name: 'Medium',- presentation: 'M'- )- endbefore doline_item.variant.option_values << option_value_blue- rule.preferred_eligible_values = option_value_variant_ids+ rule.preferred_eligible_values = eligible_option_value_idsend- context 'when the line item has the correct product' do- let(:product_id) { line_item.product.id }+ context 'when the line item variant carries a matching option value' do+ let(:eligible_option_value_ids) { [option_value_blue.id] }- context 'when all of the option values match' do- let(:option_value_variant_ids) do- [- line_item.variant.option_value_variants.reload.find_by(option_value: option_value_blue).id- ]- end-- it { is_expected.to be true }- end+ it { is_expected.to be true }+ end- context 'when not all of the option values match' do- let(:option_value_variant_ids) do- [- line_item.variant.option_value_variants.reload.find_by(option_value: option_value_blue).id,- 12356342- ]- end+ context 'when the line item variant does not carry a matching option value' do+ let(:eligible_option_value_ids) { [create(:option_value).id] }- it { is_expected.to be true }- end+ it { is_expected.to be false }end+ end- context "when the line item's product doesn't match" do- let(:option_value_variant_ids) do- [- 12312423,- 45823843- ]- end+ describe '#option_values' do+ let(:option_value) { create(:option_value) }- it { is_expected.to be false }+ before { rule.preferred_eligible_values = [option_value.id] }++ it 'returns the configured option values' do+ expect(rule.option_values).to contain_exactly(option_value)endendend