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
Fixed Price Rule management in Admin API/SPA (#14115)
Damian Legawiecded960410ac5
diff --git a/packages/admin-sdk/src/types/generated/PriceRule.ts b/packages/admin-sdk/src/types/generated/PriceRule.tsindex 121d771fcd..45900afcd8 100644--- a/packages/admin-sdk/src/types/generated/PriceRule.ts+++ b/packages/admin-sdk/src/types/generated/PriceRule.ts@@ -1,6 +1,7 @@-// Typelizer digest fd105f817869741dc317ffa9f5f09139+// Typelizer digest cbc9397d33f0e796562f7f1ef7586420//// DO NOT MODIFY: This file was automatically generated by Typelizer.+import type {Market, CustomerGroup, Customer} from '@/types'interface PriceRule {id: string;@@ -12,6 +13,9 @@ interface PriceRule {preference_schema: Array<{ key: string; type: string; default: unknown }>;label: string;description: string | null;+ markets?: Array<Market>;+ customer_groups?: Array<CustomerGroup>;+ customers?: Array<Customer>;}export default PriceRule;diff --git a/packages/dashboard-core/src/components/market-combobox.tsx b/packages/dashboard-core/src/components/market-combobox.tsxnew file mode 100644index 0000000000..166548a5b7--- /dev/null+++ b/packages/dashboard-core/src/components/market-combobox.tsx@@ -0,0 +1,89 @@+import type { Market } from '@spree/admin-sdk'+import {+ Combobox,+ ComboboxChip,+ ComboboxChips,+ ComboboxChipsInput,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxItem,+ ComboboxList,+ ComboboxValue,+ useComboboxAnchor,+} from '@spree/dashboard-ui'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'++/**+ * Searchable multi-select market picker. Value is an array of prefixed+ * market IDs; filters by name client-side against the caller-supplied+ * `markets` list (typically the long-cached `useAllMarkets()` set in+ * `@spree/dashboard`). Mirrors `<CountryMultiCombobox>` so the two+ * pickers feel identical to use.+ */+export function MarketMultiCombobox({+ markets,+ value,+ onValueChange,+ placeholder,+ emptyText,+ disabled = false,+}: {+ markets: Market[]+ /** Selected prefixed market IDs. */+ value: string[]+ onValueChange: (ids: string[]) => void+ placeholder?: string+ emptyText?: string+ disabled?: boolean+}) {+ const { t } = useTranslation()+ const anchorRef = useComboboxAnchor()+ const [inputValue, setInputValue] = useState('')++ // Selected IDs not yet present in `markets` (list still loading) fall+ // back to a stub so chips don't vanish on first render.+ const selected = useMemo<Market[]>(+ () => value.map((id) => markets.find((m) => m.id === id) ?? ({ id, name: id } as Market)),+ [value, markets],+ )++ return (+ <Combobox+ multiple+ items={markets}+ value={selected}+ onValueChange={(next: Market[]) => {+ onValueChange(next.map((m) => m.id))+ setInputValue('')+ }}+ itemToStringLabel={(m: Market | null) => m?.name ?? ''}+ itemToStringValue={(m: Market | null) => m?.id ?? ''}+ isItemEqualToValue={(a: Market, b: Market) => a.id === b.id}+ disabled={disabled}+ >+ <ComboboxChips ref={anchorRef}>+ <ComboboxValue>+ {(selectedMarkets: Market[]) =>+ selectedMarkets.map((m) => <ComboboxChip key={m.id}>{m.name}</ComboboxChip>)+ }+ </ComboboxValue>+ <ComboboxChipsInput+ placeholder={placeholder ?? t('admin.components.market_combobox.search_placeholder')}+ value={inputValue}+ onChange={(e) => setInputValue((e.target as HTMLInputElement).value)}+ />+ </ComboboxChips>+ <ComboboxContent anchor={anchorRef}>+ <ComboboxEmpty>{emptyText ?? t('admin.components.market_combobox.empty')}</ComboboxEmpty>+ <ComboboxList>+ {(market: Market) => (+ <ComboboxItem key={market.id} value={market}>+ {market.name}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ )+}diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.tsindex 0316b8a5f7..17eaa59a9d 100644--- a/packages/dashboard-core/src/index.ts+++ b/packages/dashboard-core/src/index.ts@@ -23,6 +23,7 @@ export * from './components/country-state-fields'export * from './components/currency-select'export * from './components/export-button'export * from './components/locale-select'+export * from './components/market-combobox'export * from './components/nav-main'export * from './components/page-header'export * from './components/page-tabs'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.tsxindex 3757d096dd..a7f4e993f7 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@@ -521,7 +521,9 @@ function RulesCard({{pickerOpen && (<RulePickerSheet- types={types}+ // One rule type per list (backend uniqueness on `type`).+ types={types.filter((tt) => !watchedRules.some((r) => r.type === tt.type))}+ registeredCount={types.length}openonOpenChange={(o) => !o && setPickerOpen(false)}onPicked={(type) => {@@ -606,21 +608,38 @@ function RuleRow({)}-// Preference keys that are surfaced via display embeds elsewhere on the-// draft. We skip them in the schema walk below so the row preview reads-// "VIPs, Wholesale" via the embed instead of "Customer group ids: cg_…".-const PREFS_SHOWN_VIA_EMBED = new Set(['customer_group_ids', 'user_ids'])+// Display embeds the API ships alongside each rule. The preference key+// is skipped in the generic prefs dump below so the row preview reads+// "VIPs, Wholesale" instead of "Customer group ids: cg_…".+const RULE_EMBEDS = [+ {+ prefKey: 'customer_group_ids',+ pick: (d: PriceRuleFormDraft) => d.customer_groups,+ label: (g: { name?: string | null; id: string }) => g.name ?? g.id,+ },+ {+ prefKey: 'user_ids',+ pick: (d: PriceRuleFormDraft) => d.customers,+ label: (c: { email?: string | null; id: string }) => c.email ?? c.id,+ },+ {+ prefKey: 'market_ids',+ pick: (d: PriceRuleFormDraft) => d.markets,+ label: (m: { name?: string | null; id: string }) => m.name ?? m.id,+ },+] as const++const PREFS_SHOWN_VIA_EMBED: ReadonlySet<string> = new Set(RULE_EMBEDS.map((e) => e.prefKey))function RuleSummary({ draft }: { draft: PriceRuleFormDraft }) {const { t } = useTranslation()const parts: string[] = []- // Embeds first — these are the human-readable name lists set by the- // per-rule editors (customer-group autocomplete, customer autocomplete).- const groups = nameList(draft.customer_groups, (g) => g.name ?? g.id, t)- if (groups) parts.push(groups)- const customers = nameList(draft.customers, (c) => c.email ?? c.id, t)- if (customers) parts.push(customers)+ for (const embed of RULE_EMBEDS) {+ const items = embed.pick(draft) as Array<{ id: string }> | undefined+ const rendered = nameList(items, embed.label as (item: { id: string }) => string, t)+ if (rendered) parts.push(rendered)+ }// Fall back to the generic preferences dump for everything else// (Volume Rule's min_quantity, etc.). Skip keys already covered above.@@ -677,16 +696,25 @@ function humanize(key: string): string {function RulePickerSheet({types,+ registeredCount,open,onOpenChange,onPicked,}: {+ /** Types still selectable — already-added types are filtered out upstream. */types: ResourceTypeDefinition[]+ /** Total registered types regardless of selection — lets the empty state+ * distinguish "nothing registered" from "all already used". */+ registeredCount: numberopen: booleanonOpenChange: (open: boolean) => voidonPicked: (type: ResourceTypeDefinition) => void}) {const { t } = useTranslation()+ const emptyKey =+ registeredCount === 0+ ? 'admin.pages.products.price_lists.rule_types_empty'+ : 'admin.pages.products.price_lists.rule_types_all_used'return (<Sheet open={open} onOpenChange={onOpenChange}><SheetContent>@@ -696,9 +724,7 @@ function RulePickerSheet({</SheetHeader><div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4">{types.length === 0 ? (- <p className="text-sm text-muted-foreground">- {t('admin.pages.products.price_lists.rule_types_empty')}- </p>+ <p className="text-sm text-muted-foreground">{t(emptyKey)}</p>) : (types.map((tt) => (<buttondiff --git a/packages/dashboard/src/components/spree/price-list-editors/register.ts b/packages/dashboard/src/components/spree/price-list-editors/register.tsindex a3fd529b35..c0caccc466 100644--- a/packages/dashboard/src/components/spree/price-list-editors/register.ts+++ b/packages/dashboard/src/components/spree/price-list-editors/register.ts@@ -1,6 +1,7 @@import { registerSlot } from '@spree/dashboard-core'import { CustomerRuleEditor } from './rule-customer'import { CustomerGroupRuleEditor } from './rule-customer-group'+import { MarketRuleEditor } from './rule-market'import { ruleFormSlot } from './types'/**@@ -27,3 +28,8 @@ registerSlot(ruleFormSlot('customer_group_rule'), {id: 'builtin',component: CustomerGroupRuleEditor,})++registerSlot(ruleFormSlot('market_rule'), {+ id: 'builtin',+ component: MarketRuleEditor,+})diff --git a/packages/dashboard/src/components/spree/price-list-editors/rule-customer-group.tsx b/packages/dashboard/src/components/spree/price-list-editors/rule-customer-group.tsxindex d413899eed..ac56c21be4 100644--- a/packages/dashboard/src/components/spree/price-list-editors/rule-customer-group.tsx+++ b/packages/dashboard/src/components/spree/price-list-editors/rule-customer-group.tsx@@ -9,12 +9,12 @@ import type { PriceRuleEditorContext } from './types'export function CustomerGroupRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {const { t } = useTranslation()- const [groupIds, setGroupIds] = useState<string[]>(- () => (draft.preferences?.customer_group_ids ?? []) as string[],+ // Seed from `draft.customer_groups` (the embed) — `preferences.customer_group_ids`+ // holds raw integer IDs server-side while the embed carries the prefixed `cg_…`+ // IDs the picker round-trips.+ const [groupIds, setGroupIds] = useState<string[]>(() =>+ (draft.customer_groups ?? []).map((g) => g.id),)- // Display-only embed echoed back onto the draft so the row summary- // can render group names instead of prefixed IDs. Stripped at payload- // time (see priceListValuesToParams).const [customerGroups, setCustomerGroups] = useState<CustomerGroup[]>(draft.customer_groups ?? [])function handleSave() {diff --git a/packages/dashboard/src/components/spree/price-list-editors/rule-customer.tsx b/packages/dashboard/src/components/spree/price-list-editors/rule-customer.tsxindex cc7c348046..adcd125bc6 100644--- a/packages/dashboard/src/components/spree/price-list-editors/rule-customer.tsx+++ b/packages/dashboard/src/components/spree/price-list-editors/rule-customer.tsx@@ -14,11 +14,12 @@ import type { PriceRuleEditorContext } from './types'*/export function CustomerRuleEditor({ draft, onSave, onClose }: PriceRuleEditorContext) {const { t } = useTranslation()- const [customerIds, setCustomerIds] = useState<string[]>(- () => (draft.preferences?.user_ids ?? []) as string[],+ // Seed from `draft.customers` (the embed) — `preferences.user_ids` holds raw+ // integer IDs server-side while the embed carries the prefixed customer IDs+ // the picker round-trips.+ const [customerIds, setCustomerIds] = useState<string[]>(() =>+ (draft.customers ?? []).map((c) => c.id),)- // Display-only embed echoed back onto the draft so RuleSummary can- // render customer names instead of prefixed IDs. Stripped at payload time.const [customers, setCustomers] = useState<Customer[]>(draft.customers ?? [])function handleSave() {diff --git a/packages/dashboard/src/components/spree/price-list-editors/rule-market.tsx b/packages/dashboard/src/components/spree/price-list-editors/rule-market.tsxnew file mode 100644index 0000000000..9e0d20674d--- /dev/null+++ b/packages/dashboard/src/components/spree/price-list-editors/rule-market.tsx@@ -0,0 +1,52 @@+import type { Market } from '@spree/admin-sdk'+import { MarketMultiCombobox } from '@spree/dashboard-core'+import { Field, FieldGroup, FieldLabel } from '@spree/dashboard-ui'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { EditorShell } from '@/components/spree/promotion-editors/editor-shell'+import { useAllMarkets } from '@/hooks/use-markets'+import type { PriceRuleEditorContext } from './types'++/**+ * Multi-select market picker for the Market price 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 }: PriceRuleEditorContext) {+ 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.fields.price_rule.markets.label')}</FieldLabel>+ <MarketMultiCombobox markets={markets} value={marketIds} onValueChange={setMarketIds} />+ <p className="text-xs text-muted-foreground">+ {t('admin.fields.price_rule.markets.help')}+ </p>+ </Field>+ </FieldGroup>+ </EditorShell>+ )+}diff --git a/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx b/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsxindex 55a5c7446c..5e008b0777 100644--- a/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx+++ b/packages/dashboard/src/components/spree/promotion-editors/promotion-form.tsx@@ -675,7 +675,9 @@ function RulesCard({{pickerOpen && (<RulePickerSheet- types={types}+ // One rule type per promotion (backend uniqueness on `type`).+ types={types.filter((tt) => !watchedRules.some((r) => r.type === tt.type))}+ registeredCount={types.length}openonOpenChange={(o) => !o && setPickerOpen(false)}onPicked={(type) => {@@ -857,15 +859,24 @@ function customerLabel(c: Customer): string {function RulePickerSheet({types,+ registeredCount,open,onOpenChange,onPicked,}: {+ /** Types still selectable — already-added types are filtered out upstream. */types: ResourceTypeDefinition[]+ /** Total registered types regardless of selection. */+ registeredCount: numberopen: booleanonOpenChange: (open: boolean) => voidonPicked: (type: ResourceTypeDefinition) => void}) {+ const { t } = useTranslation()+ const emptyKey =+ registeredCount === 0+ ? 'admin.promotions.rule_types_empty'+ : 'admin.promotions.rule_types_all_used'return (<Sheet open={open} onOpenChange={onOpenChange}><SheetContent>@@ -874,19 +885,23 @@ function RulePickerSheet({<SheetDescription>Pick a rule type to configure.</SheetDescription></SheetHeader><div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4">- {types.map((t) => (- <button- key={t.type}- type="button"- onClick={() => onPicked(t)}- className="flex flex-col items-start rounded-md border p-3 text-left transition-colors hover:bg-muted/50"- >- <span className="text-sm font-medium">{t.label}</span>- {t.description && (- <span className="text-xs text-muted-foreground">{t.description}</span>- )}- </button>- ))}+ {types.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t(emptyKey)}</p>+ ) : (+ types.map((tt) => (+ <button+ key={tt.type}+ type="button"+ onClick={() => onPicked(tt)}+ className="flex flex-col items-start rounded-md border p-3 text-left transition-colors hover:bg-muted/50"+ >+ <span className="text-sm font-medium">{tt.label}</span>+ {tt.description && (+ <span className="text-xs text-muted-foreground">{tt.description}</span>+ )}+ </button>+ ))+ )}</div><SheetFooter><Button type="button" variant="outline" size="sm" onClick={() => onOpenChange(false)}>diff --git a/packages/dashboard/src/hooks/use-markets.ts b/packages/dashboard/src/hooks/use-markets.tsindex cd26927020..3f8de0a302 100644--- a/packages/dashboard/src/hooks/use-markets.ts+++ b/packages/dashboard/src/hooks/use-markets.ts@@ -1,5 +1,5 @@import type { Market, MarketCreateParams, MarketUpdateParams } from '@spree/admin-sdk'-import { adminClient, useResourceMutation } from '@spree/dashboard-core'+import { adminClient, useResourceMutation, useStore } from '@spree/dashboard-core'import { useQuery, useQueryClient } from '@tanstack/react-query'export const marketsQueryKey = ['markets'] as const@@ -22,6 +22,24 @@ export function useMarkets({ page = 1, limit = 100, expand }: UseMarketsParams =})}+/**+ * Cached full-list fetch for markets — markets are store-scoped, rarely+ * change, and a store typically has only a handful. Reused by pickers+ * (e.g. the Market price rule) that need to filter client-side without+ * round-tripping the API on each keystroke. `storeId` is in the key so+ * switching stores doesn't surface another store's markets.+ */+export function useAllMarkets() {+ const { storeId } = useStore()+ const { data, isLoading } = useQuery({+ queryKey: [...marketsQueryKey, storeId, 'all'],+ queryFn: () => adminClient.markets.list({ limit: 100, sort: 'position' }),+ staleTime: 1000 * 60 * 30,+ })++ return { markets: data?.data ?? [], isLoading }+}+export function useMarket(id: string | undefined) {return useQuery({queryKey: id ? marketQueryKey(id) : ['markets', 'noop'],diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex d48123b877..067469a2eb 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -237,6 +237,10 @@"customer_groups": {"label": "Customer groups","help": "Leave empty to apply this rule to every customer regardless of group."+ },+ "markets": {+ "label": "Markets",+ "help": "Leave empty to apply this rule in every market."}},"stock_location": {@@ -495,6 +499,8 @@}},"promotions": {+ "rule_types_empty": "No rule types registered.",+ "rule_types_all_used": "Every available rule type is already on this promotion.","generate_code": {"title": "Generate a random code"},@@ -575,6 +581,12 @@}}},+ "components": {+ "market_combobox": {+ "search_placeholder": "Search markets…",+ "empty": "No markets match"+ }+ },"pages": {"home": {"top_products": "Top Products",@@ -823,6 +835,7 @@"rules_empty": "No rules — this list applies to every shopper.","add_rule_help": "Pick a rule type to configure.","rule_types_empty": "No rule types registered.",+ "rule_types_all_used": "Every available rule type is already on this list.","rule_default_description": "Tune the rule's parameters.","products_help": "Pick the products this list applies to. Placeholder prices are created on save — fill them in below.","products_search_placeholder": "Search products by name…",diff --git a/packages/dashboard/src/schemas/price-list.ts b/packages/dashboard/src/schemas/price-list.tsindex 9b7050abcc..d72769d6a5 100644--- a/packages/dashboard/src/schemas/price-list.ts+++ b/packages/dashboard/src/schemas/price-list.ts@@ -1,6 +1,7 @@import type {Customer,CustomerGroup,+ Market,PreferenceField,PriceListCreateParams,PriceListUpdateParams,@@ -38,6 +39,7 @@ export interface PriceRuleFormDraft {*/customers?: Customer[]customer_groups?: CustomerGroup[]+ markets?: Market[]}const priceRuleDraftSchema: z.ZodType<PriceRuleFormDraft> = z.object({@@ -50,6 +52,7 @@ const priceRuleDraftSchema: z.ZodType<PriceRuleFormDraft> = z.object({preferences: z.record(z.string(), z.unknown()).default({}),customers: z.array(z.any()).optional(),customer_groups: z.array(z.any()).optional(),+ markets: z.array(z.any()).optional(),}) as unknown as z.ZodType<PriceRuleFormDraft>export const priceListFormSchema = z@@ -120,6 +123,9 @@ export function ruleDraftFromRule(rule: PriceRule): PriceRuleFormDraft {description: rule.description,preference_schema: rule.preference_schema,preferences: rule.preferences,+ customers: rule.customers ?? undefined,+ customer_groups: rule.customer_groups ?? undefined,+ markets: rule.markets ?? undefined,}}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.rbindex 6aebc75ee5..bd0aa8cdfa 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@@ -33,6 +33,21 @@ module Spreeattribute :description do |rule|rule.class.respond_to?(:description) ? rule.class.description : nilend++ # Embeds skip rules that don't carry the association (e.g.+ # VolumeRule has no markets/customers — the keys are omitted).+ many :markets,+ resource: Spree.api.admin_market_serializer,+ if: proc { |rule| rule.respond_to?(:markets) }++ many :customer_groups,+ resource: Spree.api.admin_customer_group_serializer,+ if: proc { |rule| rule.respond_to?(:customer_groups) }++ many :users,+ key: :customers,+ resource: Spree.api.admin_customer_serializer,+ if: proc { |rule| rule.respond_to?(:users) }endendenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rbindex 6430fa3514..8ea6519c38 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/price_lists_controller_spec.rb@@ -40,7 +40,10 @@ RSpec.describe Spree::Api::V3::Admin::PriceListsController, type: :controller doexpect(list.price_rules.length).to eq(2)cg_rule = list.price_rules.find { |r| r.is_a?(Spree::PriceRules::CustomerGroupRule) }volume_rule = list.price_rules.find { |r| r.is_a?(Spree::PriceRules::VolumeRule) }- expect(cg_rule.preferred_customer_group_ids).to contain_exactly(customer_group.id)+ # Preferences are normalized to string-coerced raw IDs by the+ # rule's `parse_on_set` decoder — prefixed `cg_…` IDs come in+ # off the wire and land as `customer_group.id.to_s` in storage.+ expect(cg_rule.preferred_customer_group_ids).to contain_exactly(customer_group.id.to_s)expect(volume_rule.preferred_min_quantity).to eq(10)endend@@ -91,6 +94,263 @@ RSpec.describe Spree::Api::V3::Admin::PriceListsController, type: :controller doendend+ describe 'POST #create — per rule type' do+ # Covers every registered subclass in `Spree.pricing.rules`. Each+ # case asserts the rule persists as the right STI subclass, that+ # wire preferences land in the model with the expected coercion+ # (prefixed IDs decoded, scalars typed), and that the API embed is+ # present where applicable.+ #+ # `list_name` is unique per context to keep `find_by!` deterministic+ # under random spec ordering — the suite has many "EU wholesale"+ # callsites and `let!(:price_list)` already seeds another list.+ let(:created_list) { Spree::PriceList.for_store(store).find_by!(name: list_name) }+ let(:base_params) { { name: list_name, match_policy: 'all' } }++ context 'volume_rule' do+ let(:list_name) { 'Volume list' }++ it 'persists min_quantity / max_quantity as integers' do+ post :create,+ params: base_params.merge(+ rules: [{ type: 'volume_rule', preferences: { min_quantity: 5, max_quantity: 25 } }]+ ),+ as: :json++ expect(response).to have_http_status(:created)+ rule = created_list.price_rules.first+ expect(rule).to be_a(Spree::PriceRules::VolumeRule)+ expect(rule.preferred_min_quantity).to eq(5)+ expect(rule.preferred_max_quantity).to eq(25)+ end++ it 'accepts a nil max_quantity (unbounded ceiling)' do+ post :create,+ params: base_params.merge(+ rules: [{ type: 'volume_rule', preferences: { min_quantity: 3, max_quantity: nil } }]+ ),+ as: :json++ expect(response).to have_http_status(:created)+ rule = created_list.price_rules.first+ expect(rule.preferred_min_quantity).to eq(3)+ expect(rule.preferred_max_quantity).to be_nil+ end+ end++ # NOTE: market_rule wire-decoding is covered by the model spec —+ # `Spree::PriceRules::MarketRule#preferred_market_ids=` (see+ # `spec/models/spree/price_rules/market_rule_spec.rb`). Creating+ # markets through the factory in this controller suite leaks+ # transactional state via the factory's `after(:build)` callback+ # (Zone / ShippingMethod), so the controller-level coverage uses+ # customer_group_rule instead.++ context 'customer_group_rule' do+ let(:list_name) { 'Customer group list' }+ let(:customer_group) { create(:customer_group, store: store) }+ let(:other_group) { create(:customer_group, store: store) }++ it 'decodes prefixed customer-group IDs to raw IDs in storage' do+ post :create,+ params: base_params.merge(+ rules: [{+ type: 'customer_group_rule',+ preferences: { customer_group_ids: [customer_group.prefixed_id, other_group.prefixed_id] }+ }]+ ),+ as: :json++ expect(response).to have_http_status(:created)+ rule = created_list.price_rules.first+ expect(rule).to be_a(Spree::PriceRules::CustomerGroupRule)+ expect(rule.preferred_customer_group_ids).to contain_exactly(customer_group.id.to_s, other_group.id.to_s)+ expect(rule.customer_groups).to contain_exactly(customer_group, other_group)+ end++ it 'returns 404 for an unknown customer-group ID' do+ post :create,+ params: base_params.merge(+ rules: [{+ type: 'customer_group_rule',+ preferences: { customer_group_ids: ['cg_doesnotexist'] }+ }]+ ),+ as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ context 'user_rule' do+ # Wire shorthand is `user_rule` (legacy preference column name);+ # the SPA labels it "Customer rule".+ let(:list_name) { 'User list' }+ let(:user) { create(:user) }+ let(:other_user) { create(:user) }++ it 'decodes prefixed user IDs to raw IDs in storage' do+ post :create,+ params: base_params.merge(+ rules: [{+ type: 'user_rule',+ preferences: { user_ids: [user.prefixed_id, other_user.prefixed_id] }+ }]+ ),+ as: :json++ expect(response).to have_http_status(:created)+ rule = created_list.price_rules.first+ expect(rule).to be_a(Spree::PriceRules::UserRule)+ expect(rule.preferred_user_ids).to contain_exactly(user.id.to_s, other_user.id.to_s)+ expect(rule.users).to contain_exactly(user, other_user)+ end++ it 'returns 404 for an unknown user ID' do+ post :create,+ params: base_params.merge(+ rules: [{ type: 'user_rule', preferences: { user_ids: ['cus_doesnotexist'] } }]+ ),+ as: :json++ expect(response).to have_http_status(:not_found)+ end+ end++ context 'duplicate rule types in a single payload' do+ let(:list_name) { 'Dup rule list' }++ it 'rejects two rules of the same type on one list' do+ post :create,+ params: base_params.merge(+ rules: [+ { type: 'volume_rule', preferences: { min_quantity: 1 } },+ { type: 'volume_rule', preferences: { min_quantity: 2 } }+ ]+ ),+ as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end+ end++ describe 'PATCH #update — rule reconciliation per rule type' do+ # The flat payload contract: existing rules update in place when+ # matched by id; rules omitted from the payload get destroyed.+ let(:customer_group) { create(:customer_group, store: store) }++ it 'updates a volume_rule in place when matched by id' do+ rule = price_list.price_rules.create!(+ type: 'Spree::PriceRules::VolumeRule', preferences: { min_quantity: 1 }+ )++ patch :update,+ params: {+ id: price_list.prefixed_id,+ rules: [{ id: rule.prefixed_id, type: 'volume_rule', preferences: { min_quantity: 50 } }]+ },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(rule.reload.preferred_min_quantity).to eq(50)+ end++ it 'replaces customer_group_ids on an existing customer_group_rule' do+ rule = price_list.price_rules.create!(type: 'Spree::PriceRules::CustomerGroupRule')+ rule.preferred_customer_group_ids = [customer_group.id]+ rule.save!+ other_group = create(:customer_group, store: store)++ patch :update,+ params: {+ id: price_list.prefixed_id,+ rules: [{+ id: rule.prefixed_id,+ type: 'customer_group_rule',+ preferences: { customer_group_ids: [other_group.prefixed_id] }+ }]+ },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(rule.reload.preferred_customer_group_ids).to contain_exactly(other_group.id.to_s)+ end++ it 'destroys rules omitted from the payload' do+ kept = price_list.price_rules.create!(+ type: 'Spree::PriceRules::VolumeRule', preferences: { min_quantity: 1 }+ )+ removed = price_list.price_rules.create!(type: 'Spree::PriceRules::MarketRule')++ patch :update,+ params: {+ id: price_list.prefixed_id,+ rules: [{ id: kept.prefixed_id, type: 'volume_rule' }]+ },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(price_list.price_rules.pluck(:id)).to eq([kept.id])+ expect(Spree::PriceRule.find_by(id: removed.id)).to be_nil+ end++ it 'destroys all rules when given an empty array' do+ price_list.price_rules.create!(+ type: 'Spree::PriceRules::VolumeRule', preferences: { min_quantity: 1 }+ )++ patch :update,+ params: { id: price_list.prefixed_id, rules: [] },+ as: :json++ expect(response).to have_http_status(:ok)+ expect(price_list.reload.price_rules).to be_empty+ end++ it 'adds a new rule alongside an existing one in a single PATCH' do+ existing = price_list.price_rules.create!(+ type: 'Spree::PriceRules::VolumeRule', preferences: { min_quantity: 1 }+ )++ patch :update,+ params: {+ id: price_list.prefixed_id,+ rules: [+ { id: existing.prefixed_id, type: 'volume_rule', preferences: { min_quantity: 1 } },+ {+ type: 'customer_group_rule',+ preferences: { customer_group_ids: [customer_group.prefixed_id] }+ }+ ]+ },+ as: :json++ expect(response).to have_http_status(:ok)+ rules = price_list.reload.price_rules+ expect(rules.length).to eq(2)+ cg_rule = rules.find { |r| r.is_a?(Spree::PriceRules::CustomerGroupRule) }+ expect(cg_rule.preferred_customer_group_ids).to contain_exactly(customer_group.id.to_s)+ end++ it 'silently drops a rule with an unknown type' do+ patch :update,+ params: {+ id: price_list.prefixed_id,+ rules: [+ { type: 'volume_rule', preferences: { min_quantity: 2 } },+ { type: 'NotARealRule' }+ ]+ },+ as: :json++ expect(response).to have_http_status(:ok)+ rules = price_list.reload.price_rules+ expect(rules.length).to eq(1)+ expect(rules.first).to be_a(Spree::PriceRules::VolumeRule)+ end+ end+describe 'PATCH #update — prices nullability contract' dolet(:product) { create(:product, stores: [store]) }let(:variant) { product.master }diff --git a/spree/api/spec/integration/spree/api/v3/admin/price_lists_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/price_lists_spec.rbindex db07b2a060..fbb2909033 100644--- a/spree/api/spec/integration/spree/api/v3/admin/price_lists_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/price_lists_spec.rb@@ -139,7 +139,10 @@ RSpec.describe 'Admin Price Lists API', type: :request, swagger_doc: 'api-refereexpect(list.price_rules.length).to eq(2)cg_rule = list.price_rules.find { |r| r.is_a?(Spree::PriceRules::CustomerGroupRule) }volume_rule = list.price_rules.find { |r| r.is_a?(Spree::PriceRules::VolumeRule) }- expect(cg_rule.preferred_customer_group_ids).to contain_exactly(customer_group.id)+ # Preferences are normalized to string-coerced raw IDs by the+ # rule's `parse_on_set` decoder — prefixed `cg_…` IDs come in+ # off the wire and land as `customer_group.id.to_s` in storage.+ expect(cg_rule.preferred_customer_group_ids).to contain_exactly(customer_group.id.to_s)expect(volume_rule.preferred_min_quantity).to eq(10)endenddiff --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.rbnew file mode 100644index 0000000000..eb2ce60c00--- /dev/null+++ b/spree/api/spec/serializers/spree/api/v3/admin/price_rule_serializer_spec.rb@@ -0,0 +1,94 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::PriceRuleSerializer do+ let(:store) { @default_store }+ let(:price_list) { create(:price_list, store: store) }+ let(:base_params) { { store: store, currency: 'USD' } }++ subject(:payload) { described_class.new(rule, params: base_params).to_h }++ describe 'market rule' do+ let(:market) { create(:market, store: store) }+ let(:other_market) { create(:market, store: store) }+ let(:rule) do+ r = Spree::PriceRules::MarketRule.create!(price_list: price_list)+ r.preferred_market_ids = [market.id, other_market.id]+ r.save!+ r+ end++ it 'embeds the related markets' do+ ids = payload['markets'].map { |m| m['id'] }+ expect(ids).to contain_exactly(market.prefixed_id, other_market.prefixed_id)+ end++ it 'does not embed unrelated associations' do+ expect(payload).not_to have_key('customer_groups')+ expect(payload).not_to have_key('customers')+ end+ end++ describe 'customer group rule' do+ let(:customer_group) { create(:customer_group, store: store) }+ let(:rule) do+ r = Spree::PriceRules::CustomerGroupRule.create!(price_list: price_list)+ r.preferred_customer_group_ids = [customer_group.id]+ r.save!+ r+ end++ it 'embeds the related customer groups' do+ ids = payload['customer_groups'].map { |g| g['id'] }+ expect(ids).to contain_exactly(customer_group.prefixed_id)+ end++ it 'does not embed unrelated associations' do+ expect(payload).not_to have_key('markets')+ expect(payload).not_to have_key('customers')+ end+ end++ describe 'user (customer) rule' do+ let(:user) { create(:user) }+ let(:rule) do+ r = Spree::PriceRules::UserRule.create!(price_list: price_list)+ r.preferred_user_ids = [user.id]+ r.save!+ r+ end++ it 'embeds the related customers under the `customers` key' do+ ids = payload['customers'].map { |c| c['id'] }+ expect(ids).to contain_exactly(user.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')+ 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+ 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 'prefixed-ID decoding via the API surface' do+ let(:market) { create(:market, store: store) }+ let(:rule) { Spree::PriceRules::MarketRule.create!(price_list: price_list) }++ it 'stores raw IDs when the wire sends prefixed IDs' do+ rule.preferred_market_ids = [market.prefixed_id]+ expect(rule.preferred_market_ids).to eq([market.id.to_s])+ end+ end+enddiff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rbindex 11a3b4af67..cc20def28b 100644--- a/spree/core/app/models/concerns/spree/preference_schema.rb+++ b/spree/core/app/models/concerns/spree/preference_schema.rb@@ -75,6 +75,47 @@ module Spree[]end+ # Builds a `parse_on_set:` lambda for `preference :foo_ids, :array`+ # declarations that accept prefixed IDs (e.g. `cg_…`, `mkt_…`) from+ # the API. Splits comma-separated entries, strips whitespace, and+ # decodes any prefixed IDs to raw IDs so eligibility checks compare+ # against `belongs_to` foreign keys directly.+ #+ # When `klass` is nil, prefixed-ID decoding is skipped — used for+ # ISO/string-keyed preferences where the value is the identifier+ # (e.g. country `:country_isos`).+ #+ # When `scope:` is given, the existence check runs through the+ # scope relation derived from the owning record — prevents a+ # rule from being persisted with IDs that belong to another+ # store (e.g. a Market rule referencing markets from a different+ # store). The proc receives the rule instance.+ #+ # @param klass [Class<Spree::Base>, nil] AR class used to resolve+ # prefixed IDs via Sqids decoding + a single existence check.+ # @param scope [Proc, nil] optional `->(rule) { rule.price_list.store.markets }`+ # relation builder; defaults to the unscoped `klass`.+ # @return [Proc] suitable for the `parse_on_set:` preference option.+ def normalize_id_preference(klass: nil, scope: nil)+ lambda do |values, owner = nil|+ raw = Array(values).flat_map { |v| v.to_s.split(',') }.compact_blank.map(&:strip)+ next raw unless klass++ decoded = raw.map do |v|+ Spree::PrefixedId.prefixed_id?(v) ? Spree::PrefixedId.decode_prefixed_id(v).to_s : v+ end++ relation = scope && owner ? scope.call(owner) : klass+ found = relation.where(id: decoded).pluck(:id).map(&:to_s).to_set+ missing = decoded.reject { |id| found.include?(id) }+ raise ActiveRecord::RecordNotFound.new(+ "Couldn't find #{klass.name} with id=#{missing.join(',')}", klass.name+ ) if missing.any?++ decoded+ end+ end+# Resolve a wire-format shorthand back to its registered subclass.# Returns nil for unknown shorthands. Lookup is registry-driven so# removed/foreign subclasses can't be smuggled in.diff --git a/spree/core/app/models/concerns/spree/typed_associations.rb b/spree/core/app/models/concerns/spree/typed_associations.rbindex c3ca155aa5..4b416ee099 100644--- a/spree/core/app/models/concerns/spree/typed_associations.rb+++ b/spree/core/app/models/concerns/spree/typed_associations.rb@@ -109,8 +109,12 @@ module Spreeklass = collection.proxy_association.klass.find_by_api_type(row[:type])return nil unless klass- record = collection.build(type: klass.to_s)- record.class == klass ? record : record.becomes(klass)+ # `build(type:) + becomes(klass)` would leave a stale STI-parent stub+ # in the collection target alongside the becomes'd copy; autosave then+ # validates both under different identities and uniqueness checks fail.+ record = klass.new+ collection.proxy_association.add_to_target(record)+ recordendendenddiff --git a/spree/core/app/models/spree/market.rb b/spree/core/app/models/spree/market.rbindex f5c432c139..1f62bc0603 100644--- a/spree/core/app/models/spree/market.rb+++ b/spree/core/app/models/spree/market.rb@@ -10,7 +10,7 @@ module Spree## Associations#- belongs_to :store, class_name: 'Spree::Store', touch: true+ belongs_to :store, class_name: 'Spree::Store', touch: true, inverse_of: :marketshas_many :market_countries, class_name: 'Spree::MarketCountry', dependent: :destroyhas_many :countries, through: :market_countries, class_name: 'Spree::Country'has_many :orders, class_name: 'Spree::Order', dependent: :nullifydiff --git a/spree/core/app/models/spree/price_rule.rb b/spree/core/app/models/spree/price_rule.rbindex e528774c68..12f0d535b4 100644--- a/spree/core/app/models/spree/price_rule.rb+++ b/spree/core/app/models/spree/price_rule.rb@@ -4,7 +4,10 @@ module Spreebelongs_to :price_list, class_name: 'Spree::PriceList', touch: true+ delegate :store, to: :price_list+validates :type, :price_list, presence: true+ validates :type, uniqueness: { scope: [:price_list_id, *spree_base_uniqueness_scope] }# Returns true if the price rule is applicable to the context# @param context [Spree::Pricing::Context]diff --git a/spree/core/app/models/spree/price_rules/customer_group_rule.rb b/spree/core/app/models/spree/price_rules/customer_group_rule.rbindex a2e87425f7..8c830ef5d7 100644--- a/spree/core/app/models/spree/price_rules/customer_group_rule.rb+++ b/spree/core/app/models/spree/price_rules/customer_group_rule.rb@@ -1,7 +1,21 @@module Spreemodule PriceRulesclass CustomerGroupRule < Spree::PriceRule- preference :customer_group_ids, :array, default: []+ # Stored as raw IDs. Accepts prefixed IDs (`cg_…`) from API+ # callers and decodes them on write so eligibility checks compare+ # against raw `customer_group_id` rows directly. Scope confines+ # the existence check to the price-list's store.+ preference :customer_group_ids, :array, default: [],+ parse_on_set: normalize_id_preference(+ klass: Spree::CustomerGroup,+ scope: ->(rule) { rule.store.customer_groups }+ )++ def customer_groups+ return [] if preferred_customer_group_ids.blank?++ Spree::CustomerGroup.where(id: preferred_customer_group_ids)+ enddef applicable?(context)return false unless context.userdiff --git a/spree/core/app/models/spree/price_rules/market_rule.rb b/spree/core/app/models/spree/price_rules/market_rule.rbindex 8a849590f9..d7d7928638 100644--- a/spree/core/app/models/spree/price_rules/market_rule.rb+++ b/spree/core/app/models/spree/price_rules/market_rule.rb@@ -1,7 +1,22 @@module Spreemodule PriceRulesclass MarketRule < Spree::PriceRule- preference :market_ids, :array, default: []+ # Stored as raw IDs. Accepts prefixed IDs (`mkt_…`) from API+ # callers and decodes them on write so eligibility checks compare+ # against raw `market_id` rows directly. Scope confines the+ # existence check to the price-list'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.store.markets }+ )++ def markets+ return [] if preferred_market_ids.blank?++ Spree::Market.where(id: preferred_market_ids)+ enddef applicable?(context)return false unless context.marketdiff --git a/spree/core/app/models/spree/price_rules/user_rule.rb b/spree/core/app/models/spree/price_rules/user_rule.rbindex 00f5f15b7a..72953c17b9 100644--- a/spree/core/app/models/spree/price_rules/user_rule.rb+++ b/spree/core/app/models/spree/price_rules/user_rule.rb@@ -1,7 +1,19 @@module Spreemodule PriceRulesclass UserRule < Spree::PriceRule- preference :user_ids, :array, default: []+ # Stored as raw IDs. Accepts prefixed IDs (the user class's prefix,+ # e.g. `usr_…`) from API callers and decodes them on write. Resolves+ # `Spree.user_class` lazily — the user class is configured at boot,+ # and class-body evaluation runs before that on cold loads.+ preference :user_ids, :array, default: [], parse_on_set: ->(values) {+ normalize_id_preference(klass: Spree.user_class).call(values)+ }++ def users+ return [] if preferred_user_ids.blank?++ Spree.user_class.where(id: preferred_user_ids)+ enddef applicable?(context)return false unless context.userdiff --git a/spree/core/app/models/spree/promotion_rule.rb b/spree/core/app/models/spree/promotion_rule.rbindex bcef04278b..e061f414bd 100644--- a/spree/core/app/models/spree/promotion_rule.rb+++ b/spree/core/app/models/spree/promotion_rule.rb@@ -10,7 +10,7 @@ module Spreescope :of_type, ->(t) { where(type: t) }validates :promotion, presence: true- validate :unique_per_promotion, on: :create+ validates :type, uniqueness: { scope: [:promotion_id, *spree_base_uniqueness_scope] }# Per-subclass permitted attributes beyond `type` and `preferences`.# Override in STI subclasses that accept association IDs (e.g.@@ -20,27 +20,6 @@ module Spree[]end- # Builds a `parse_on_set:` lambda for `preference :foo_ids, :array`- # declarations on rules that accept prefixed IDs from the API.- # Splits comma-separated entries, strips whitespace, and decodes- # any prefixed IDs to raw IDs (so eligibility checks compare- # against `belongs_to` foreign keys directly).- #- # When `klass` is nil, prefixed-ID decoding is skipped — used for- # ISO/string-keyed preferences where the value is the identifier.- def self.normalize_id_preference(klass: nil)- lambda do |values|- Array(values).flat_map { |v| v.to_s.split(',') }.compact_blank.map do |v|- v = v.strip- if klass && Spree::PrefixedId.prefixed_id?(v)- klass.find_by_param!(v).id.to_s- else- v- end- end- end- end-def self.for(promotable)all.select { |rule| rule.applicable?(promotable) }end@@ -83,12 +62,6 @@ module Spreeprivate- def unique_per_promotion- if Spree::PromotionRule.exists?(promotion_id: promotion_id, type: self.class.name)- errors.add(:base, 'Promotion already contains this rule type')- end- end-def eligibility_error_message(key, options = {})Spree.t(key, Hash[scope: [:eligibility_errors, :messages]].merge(options))enddiff --git a/spree/core/db/migrate/20260529000001_add_unique_index_to_spree_price_rules.rb b/spree/core/db/migrate/20260529000001_add_unique_index_to_spree_price_rules.rbnew file mode 100644index 0000000000..c1be71a9df--- /dev/null+++ b/spree/core/db/migrate/20260529000001_add_unique_index_to_spree_price_rules.rb@@ -0,0 +1,41 @@+class AddUniqueIndexToSpreePriceRules < ActiveRecord::Migration[7.2]+ def up+ # Remove duplicate rules (same type within the same price list),+ # keeping the oldest record. Mirrors the+ # `validates :type, uniqueness: { scope: :price_list_id }` model+ # constraint at the DB level so concurrent writes can't race past+ # the validation.+ if ActiveRecord::Base.connection.adapter_name == 'Mysql2'+ execute <<-SQL+ DELETE FROM spree_price_rules+ WHERE id NOT IN (+ SELECT min_id FROM (+ SELECT MIN(id) AS min_id+ FROM spree_price_rules+ GROUP BY price_list_id, type+ ) AS keeper_ids+ )+ SQL+ else+ execute <<-SQL+ DELETE FROM spree_price_rules+ WHERE id NOT IN (+ SELECT MIN(id)+ FROM spree_price_rules+ GROUP BY price_list_id, type+ )+ SQL+ end++ remove_index :spree_price_rules, [:price_list_id, :type], if_exists: true++ add_index :spree_price_rules, [:price_list_id, :type], unique: true,+ name: 'index_spree_price_rules_on_price_list_id_and_type'+ end++ def down+ remove_index :spree_price_rules, name: 'index_spree_price_rules_on_price_list_id_and_type', if_exists: true++ add_index :spree_price_rules, [:price_list_id, :type]+ end+enddiff --git a/spree/core/db/migrate/20260529000002_add_unique_index_to_spree_promotion_rules.rb b/spree/core/db/migrate/20260529000002_add_unique_index_to_spree_promotion_rules.rbnew file mode 100644index 0000000000..f20b99603e--- /dev/null+++ b/spree/core/db/migrate/20260529000002_add_unique_index_to_spree_promotion_rules.rb@@ -0,0 +1,37 @@+class AddUniqueIndexToSpreePromotionRules < ActiveRecord::Migration[7.2]+ def up+ # Remove duplicate rules (same type within the same promotion),+ # keeping the oldest record. Mirrors the+ # `validates :type, uniqueness: { scope: :promotion_id }` model+ # constraint at the DB level so concurrent writes can't race past+ # the validation.+ if ActiveRecord::Base.connection.adapter_name == 'Mysql2'+ execute <<-SQL+ DELETE FROM spree_promotion_rules+ WHERE id NOT IN (+ SELECT min_id FROM (+ SELECT MIN(id) AS min_id+ FROM spree_promotion_rules+ GROUP BY promotion_id, type+ ) AS keeper_ids+ )+ SQL+ else+ execute <<-SQL+ DELETE FROM spree_promotion_rules+ WHERE id NOT IN (+ SELECT MIN(id)+ FROM spree_promotion_rules+ GROUP BY promotion_id, type+ )+ SQL+ end++ add_index :spree_promotion_rules, [:promotion_id, :type], unique: true,+ name: 'index_spree_promotion_rules_on_promotion_id_and_type'+ end++ def down+ remove_index :spree_promotion_rules, name: 'index_spree_promotion_rules_on_promotion_id_and_type', if_exists: true+ end+enddiff --git a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb b/spree/core/lib/spree/core/preferences/preferable_class_methods.rbindex e453b1ab39..0a14fe320a 100644--- a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb+++ b/spree/core/lib/spree/core/preferences/preferable_class_methods.rb@@ -18,7 +18,13 @@ module Spree::Preferencesenddefine_method preference_setter_method(name) do |value|- value = parse_on_set.call(value) if parse_on_set.is_a?(Proc)+ if parse_on_set.is_a?(Proc)+ # Procs that accept more than one arg opt into receiving the+ # owning record so they can scope (e.g. `normalize_id_preference`+ # rejecting cross-store IDs). `arity.abs > 1` covers both the+ # `(value, owner)` and `(value, owner = nil)` shapes.+ value = parse_on_set.arity.abs > 1 ? parse_on_set.call(value, self) : parse_on_set.call(value)+ endvalue = convert_preference_value(value, type, nullable: nullable)preferences[name] = valuediff --git a/spree/core/spec/models/spree/price_rule_spec.rb b/spree/core/spec/models/spree/price_rule_spec.rbnew file mode 100644index 0000000000..cf3e7ced99--- /dev/null+++ b/spree/core/spec/models/spree/price_rule_spec.rb@@ -0,0 +1,27 @@+require 'spec_helper'++describe Spree::PriceRule, type: :model do+ let(:price_list) { create(:price_list) }++ describe 'uniqueness of type per price_list' do+ it 'allows two rules of different types on the same list' do+ create(:market_price_rule, price_list: price_list)+ other = build(:customer_group_price_rule, price_list: price_list)+ expect(other).to be_valid+ end++ it 'rejects a second rule of the same type on the same list' do+ create(:market_price_rule, price_list: price_list)+ duplicate = build(:market_price_rule, price_list: price_list)+ expect(duplicate).not_to be_valid+ expect(duplicate.errors[:type]).to be_present+ end++ it 'allows the same rule type on a different list' do+ create(:market_price_rule, price_list: price_list)+ other_list = create(:price_list)+ other = build(:market_price_rule, price_list: other_list)+ expect(other).to be_valid+ end+ end+enddiff --git a/spree/core/spec/models/spree/price_rules/customer_group_rule_spec.rb b/spree/core/spec/models/spree/price_rules/customer_group_rule_spec.rbindex 2384c14c50..a7d77a318d 100644--- a/spree/core/spec/models/spree/price_rules/customer_group_rule_spec.rb+++ b/spree/core/spec/models/spree/price_rules/customer_group_rule_spec.rb@@ -76,4 +76,28 @@ describe Spree::PriceRules::CustomerGroupRule, type: :model doexpect(Spree::PriceRules::CustomerGroupRule.description).to eq(Spree.t('price_rules.customer_group_rule.description'))endend++ describe '#preferred_customer_group_ids=' do+ it 'decodes prefixed customer group IDs to raw IDs' do+ rule.preferred_customer_group_ids = [customer_group.prefixed_id]+ expect(rule.preferred_customer_group_ids).to eq([customer_group.id.to_s])+ end++ it 'accepts a mix of prefixed and raw IDs' do+ rule.preferred_customer_group_ids = [customer_group.prefixed_id, other_customer_group.id.to_s]+ expect(rule.preferred_customer_group_ids).to contain_exactly(customer_group.id.to_s, other_customer_group.id.to_s)+ end+ end++ describe '#customer_groups' do+ it 'returns the customer groups matching the preferred IDs' do+ rule.preferred_customer_group_ids = [customer_group.id, other_customer_group.id]+ expect(rule.customer_groups).to contain_exactly(customer_group, other_customer_group)+ end++ it 'returns an empty relation when no groups are set' do+ rule.preferred_customer_group_ids = []+ expect(rule.customer_groups).to be_empty+ end+ endenddiff --git a/spree/core/spec/models/spree/price_rules/market_rule_spec.rb b/spree/core/spec/models/spree/price_rules/market_rule_spec.rbindex aeb06ae4ba..c9aae034d1 100644--- a/spree/core/spec/models/spree/price_rules/market_rule_spec.rb+++ b/spree/core/spec/models/spree/price_rules/market_rule_spec.rb@@ -3,7 +3,9 @@ require 'spec_helper'describe Spree::PriceRules::MarketRule, type: :model dolet(:price_list) { create(:price_list) }let(:rule) { create(:market_price_rule, price_list: price_list) }- let(:market) { create(:market) }+ # Markets are store-scoped via `parse_on_set: normalize_id_preference(scope: …)`,+ # so all markets referenced here live in the same store as the rule.+ let(:market) { create(:market, store: price_list.store) }let(:variant) { create(:variant) }describe '#applicable?' do@@ -25,12 +27,16 @@ describe Spree::PriceRules::MarketRule, type: :model doendit 'returns false when context market does not match' do- other_market = create(:market)+ other_market = create(:market, store: price_list.store)context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', market: other_market)expect(rule.applicable?(context)).to be falseendit 'returns false when context has no market' do+ # `Spree::Pricing::Context` falls back to `Spree::Current.market`+ # when none is passed, so stub the fallback to truly mimic the+ # no-market case (e.g. pricing a guest cart with no inferred market).+ allow(Spree::Current).to receive(:market).and_return(nil)context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', market: nil)expect(rule.applicable?(context)).to be falseend@@ -45,10 +51,55 @@ describe Spree::PriceRules::MarketRule, type: :model doendit 'returns false when context market does not match' do- other_market = create(:market)+ other_market = create(:market, store: price_list.store)context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', market: other_market)expect(rule.applicable?(context)).to be falseendendend++ describe '#preferred_market_ids=' do+ it 'decodes prefixed market IDs to raw IDs' do+ rule.preferred_market_ids = [market.prefixed_id]+ expect(rule.preferred_market_ids).to eq([market.id.to_s])+ end++ it 'accepts a mix of prefixed and raw IDs' do+ other_market = create(:market, store: price_list.store)+ rule.preferred_market_ids = [market.prefixed_id, other_market.id.to_s]+ expect(rule.preferred_market_ids).to contain_exactly(market.id.to_s, other_market.id.to_s)+ end++ it 'accepts a comma-separated string' do+ other_market = create(:market, store: price_list.store)+ rule.preferred_market_ids = "#{market.prefixed_id},#{other_market.prefixed_id}"+ expect(rule.preferred_market_ids).to contain_exactly(market.id.to_s, other_market.id.to_s)+ end++ it 'raises when given an unknown prefixed ID' do+ expect { rule.preferred_market_ids = ['mkt_doesnotexist'] }.to raise_error(ActiveRecord::RecordNotFound)+ end++ it 'rejects a market that belongs to another store' do+ other_store = create(:store)+ cross_store_market = create(:market, store: other_store)+ expect {+ rule.preferred_market_ids = [cross_store_market.prefixed_id]+ }.to raise_error(ActiveRecord::RecordNotFound)+ end+ end++ describe '#markets' do+ let(:other_market) { create(:market, store: price_list.store) }++ it 'returns the markets matching the preferred IDs' do+ rule.preferred_market_ids = [market.id, other_market.id]+ expect(rule.markets).to contain_exactly(market, other_market)+ end++ it 'returns empty when no markets are set' do+ rule.preferred_market_ids = []+ expect(rule.markets).to be_empty+ end+ endenddiff --git a/spree/core/spec/models/spree/price_rules/user_rule_spec.rb b/spree/core/spec/models/spree/price_rules/user_rule_spec.rbindex eb5430f29a..b3a9043906 100644--- a/spree/core/spec/models/spree/price_rules/user_rule_spec.rb+++ b/spree/core/spec/models/spree/price_rules/user_rule_spec.rb@@ -51,4 +51,31 @@ describe Spree::PriceRules::UserRule, type: :model doendendend++ describe '#preferred_user_ids=' do+ it 'decodes prefixed user IDs to raw IDs' do+ rule.preferred_user_ids = [user.prefixed_id]+ expect(rule.preferred_user_ids).to eq([user.id.to_s])+ end++ it 'accepts a mix of prefixed and raw IDs' do+ other_user = create(:user)+ rule.preferred_user_ids = [user.prefixed_id, other_user.id.to_s]+ expect(rule.preferred_user_ids).to contain_exactly(user.id.to_s, other_user.id.to_s)+ end+ end++ describe '#users' do+ let(:other_user) { create(:user) }++ it 'returns the users matching the preferred IDs' do+ rule.preferred_user_ids = [user.id, other_user.id]+ expect(rule.users).to contain_exactly(user, other_user)+ end++ it 'returns an empty relation when no users are set' do+ rule.preferred_user_ids = []+ expect(rule.users).to be_empty+ end+ endenddiff --git a/spree/core/spec/models/spree/promotion_spec.rb b/spree/core/spec/models/spree/promotion_spec.rbindex 4b526707ac..62027e355f 100644--- a/spree/core/spec/models/spree/promotion_spec.rb+++ b/spree/core/spec/models/spree/promotion_spec.rb@@ -591,8 +591,10 @@ describe Spree::Promotion, type: :model doendcontext "with 'all' match policy" do- let(:promo1) { Spree::PromotionRule.create!(promotion: promotion) }- let(:promo2) { Spree::PromotionRule.create!(promotion: promotion) }+ # Two distinct STI subclasses — uniqueness scopes on `(promotion_id, type)`,+ # so re-using the abstract base would fail validation for the second row.+ let(:promo1) { Spree::Promotion::Rules::FirstOrder.create!(promotion: promotion) }+ let(:promo2) { Spree::Promotion::Rules::OneUsePerUser.create!(promotion: promotion) }before { promotion.match_policy = 'all' }