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
Rebuild promotion editor with embedded rules/actions setters
Damian Legawiecdc3dbc93a202
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 507717bdab..f2f854df28 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -123,6 +123,7 @@ import type {PaymentMethodType,PaymentMethodUpdateParams,ProductUpdateParams,+ PromotionActionCalculator,PromotionActionCreateParams,PromotionActionUpdateParams,PromotionCreateParams,@@ -151,6 +152,7 @@ import type {Country,CreditCard,Customer,+ CustomerGroup,CustomField,CustomFieldDefinition,Export,@@ -1097,6 +1099,16 @@ export class AdminClient {'/promotion_actions/types',options,),++ calculators: (+ type: string,+ options?: RequestOptions,+ ): Promise<{ data: PromotionActionCalculator[] }> =>+ this.request<{ data: PromotionActionCalculator[] }>(+ 'GET',+ '/promotion_actions/calculators',+ { ...options, params: { type } },+ ),}readonly promotionRules = {@@ -1123,6 +1135,24 @@ export class AdminClient {}),}+ // ============================================+ // Customer groups+ // ============================================++ readonly customerGroups = {+ list: (+ params?: ListParams & Record<string, unknown>,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<CustomerGroup>> =>+ this.request<PaginatedResponse<CustomerGroup>>('GET', '/customer_groups', {+ ...options,+ params: params ? transformListParams(params) : undefined,+ }),++ get: (id: string, options?: RequestOptions): Promise<CustomerGroup> =>+ this.request<CustomerGroup>('GET', `/customer_groups/${id}`, options),+ }+// ============================================// Exports (CSV: products, orders, customers, …)// ============================================diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 1da97203c8..e4103a6551 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -590,7 +590,6 @@ export interface PromotionCreateParams {code?: string | nullusage_limit?: number | nullmatch_policy?: 'all' | 'any'- advertise?: booleanpath?: string | nullpromotion_category_id?: string | null/** `coupon_code` requires a code (or multi_codes); `automatic` triggers without one. */@@ -601,6 +600,10 @@ export interface PromotionCreateParams {code_prefix?: string | nullstore_ids?: string[]metadata?: Record<string, unknown>+ /** Optional rules to create alongside the promotion. Sent as a desired-set on update. */+ rules?: PromotionRuleDraft[]+ /** Optional actions to create alongside the promotion. */+ actions?: PromotionActionDraft[]}export interface PromotionUpdateParams {@@ -611,7 +614,6 @@ export interface PromotionUpdateParams {code?: string | nullusage_limit?: number | nullmatch_policy?: 'all' | 'any'- advertise?: booleanpath?: string | nullpromotion_category_id?: string | nullkind?: PromotionKind@@ -620,24 +622,111 @@ export interface PromotionUpdateParams {code_prefix?: string | nullstore_ids?: string[]metadata?: Record<string, unknown>+ /** Replaces the rule set: rows with `id` update, rows without build, missing rows are removed. */+ rules?: PromotionRuleDraft[]+ /** Same desired-set semantic as `rules`. */+ actions?: PromotionActionDraft[]+}++/**+ * One entry in a `Promotion#rules`/`#actions` payload. `id` is optional —+ * supply it on updates to match an existing row, omit for new rows. The+ * server reconciles to the desired set: anything not in the array is+ * removed.+ */+export interface PromotionRuleDraft {+ id?: string+ /** Fully-qualified STI subclass (`'Spree::Promotion::Rules::Currency'`). */+ type: string+ preferences?: Record<string, unknown>+ /** For `Rules::Product`. */+ product_ids?: string[]+ /** For `Rules::Taxon` (renamed Category in 6.0). */+ category_ids?: string[]+ /** For `Rules::User`. */+ user_ids?: string[]+}++export interface PromotionActionDraft {+ id?: string+ /** Fully-qualified STI subclass (`'Spree::Promotion::Actions::FreeShipping'`). */+ type: string+ preferences?: Record<string, unknown>+ /** For adjustment actions. */+ calculator?: PromotionActionCalculatorParams+ /** For `CreateLineItems`. */+ line_items?: PromotionActionLineItemParams[]+}++/**+ * Nested calculator payload for adjustment actions. Sent on+ * `Spree::Promotion::Actions::CreateAdjustment` and `CreateItemAdjustments`.+ *+ * - `type` — fully-qualified calculator STI subclass (e.g.+ * `'Spree::Calculator::FlatRate'`); changing the type swaps the+ * underlying calculator record.+ * - `preferences` — per-calculator preference values (`amount`,+ * `flat_percent`, `currency`, …). Keys are coerced via the typed+ * setters server-side.+ */+export interface PromotionActionCalculatorParams {+ type?: string+ preferences?: Record<string, unknown>+}++/**+ * Nested promotion-action line item — one row in the "give the customer+ * variant X with quantity N" payload for `CreateLineItems`. The submitted+ * list is the *desired* set: variants not present are removed, variants+ * present are upserted by `(promotion_action_id, variant_id)`.+ */+export interface PromotionActionLineItemParams {+ variant_id: string+ quantity: number+}++/**+ * One entry returned by `GET /promotion_actions/calculators?type=…` — a+ * calculator subclass available for the given action, with the preference+ * fields the SPA renders below the calculator picker.+ */+export interface PromotionActionCalculator {+ type: string+ label: string+ preference_schema: PreferenceField[]}export interface PromotionActionCreateParams {/** Fully-qualified STI subclass (`'Spree::Promotion::Actions::FreeShipping'`). */type: stringpreferences?: Record<string, unknown>+ /** For adjustment actions — calculator subclass + its preference values. */+ calculator?: PromotionActionCalculatorParams+ /** For `CreateLineItems` — desired set of variants + quantities. */+ line_items?: PromotionActionLineItemParams[]}export interface PromotionActionUpdateParams {preferences?: Record<string, unknown>+ calculator?: PromotionActionCalculatorParams+ line_items?: PromotionActionLineItemParams[]}export interface PromotionRuleCreateParams {/** Fully-qualified STI subclass (`'Spree::Promotion::Rules::Currency'`). */type: stringpreferences?: Record<string, unknown>+ /** For `Rules::Product` — prefixed product IDs to associate with this rule. */+ product_ids?: string[]+ /** For `Rules::Taxon` — prefixed category IDs (Taxon is renamed to Category in 6.0). */+ category_ids?: string[]+ /** For `Rules::User` — prefixed user IDs. */+ user_ids?: string[]}export interface PromotionRuleUpdateParams {preferences?: Record<string, unknown>+ product_ids?: string[]+ category_ids?: string[]+ user_ids?: string[]}diff --git a/packages/admin-sdk/src/types/generated/CustomerGroup.ts b/packages/admin-sdk/src/types/generated/CustomerGroup.tsnew file mode 100644index 0000000000..5ac6ec5479--- /dev/null+++ b/packages/admin-sdk/src/types/generated/CustomerGroup.ts@@ -0,0 +1,13 @@+// Typelizer digest 1e9340b059025e03642d5f847ac24ec6+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface CustomerGroup {+ id: string;+ name: string;+ users_count: number;+ created_at: string;+ updated_at: string;+}++export default CustomerGroup;diff --git a/packages/admin-sdk/src/types/generated/Promotion.ts b/packages/admin-sdk/src/types/generated/Promotion.tsindex 0e7fca5a01..d6ae96ebe0 100644--- a/packages/admin-sdk/src/types/generated/Promotion.ts+++ b/packages/admin-sdk/src/types/generated/Promotion.ts@@ -1,4 +1,4 @@-// Typelizer digest fda477c7d58f2e396a10c7d78299b617+// Typelizer digest e4c17fb68f77c262bcc9f97f9d04d450//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -11,7 +11,6 @@ interface Promotion {expires_at: string | null;usage_limit: number | null;match_policy: 'all' | 'any';- advertise: boolean;path: string | null;kind: 'coupon_code' | 'automatic';multi_codes: boolean;diff --git a/packages/admin-sdk/src/types/generated/PromotionAction.ts b/packages/admin-sdk/src/types/generated/PromotionAction.tsindex ffe5efb8ae..86c69ab8c3 100644--- a/packages/admin-sdk/src/types/generated/PromotionAction.ts+++ b/packages/admin-sdk/src/types/generated/PromotionAction.ts@@ -1,4 +1,4 @@-// Typelizer digest c13562b46cfefd606826376803cd620b+// Typelizer digest 7afe7b75ef6cc7880ba53b93194e1f1e//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -7,10 +7,13 @@ interface PromotionAction {type: string;created_at: string;updated_at: string;+ key: string;promotion_id: string;preferences: Record<string, unknown>;preference_schema: Array<{ key: string; type: string; default: unknown }>;label: string;+ calculator: { type: string; label: string; preferences: Record<string, unknown>; preference_schema: Array<{ key: string; type: string; default: unknown }> } | null;+ line_items: Array<{ variant_id: string; quantity: number }> | null;}export default PromotionAction;diff --git a/packages/admin-sdk/src/types/generated/PromotionRule.ts b/packages/admin-sdk/src/types/generated/PromotionRule.tsindex b259218dd2..5fa1824bd7 100644--- a/packages/admin-sdk/src/types/generated/PromotionRule.ts+++ b/packages/admin-sdk/src/types/generated/PromotionRule.ts@@ -1,16 +1,26 @@-// Typelizer digest d95f72a9071375ed89f138810d57aa25+// Typelizer digest b00d15e0fe6e07d81e070bfa94cc8933//// DO NOT MODIFY: This file was automatically generated by Typelizer.+import type {Product, Category, Customer, CustomerGroup, Country} from '@/types'interface PromotionRule {id: string;type: string;created_at: string;updated_at: string;+ key: string;promotion_id: string;preferences: Record<string, unknown>;preference_schema: Array<{ key: string; type: string; default: unknown }>;label: string;+ product_ids: Array<string> | null;+ category_ids: Array<string> | null;+ user_ids: Array<string> | null;+ products?: Array<Product>;+ categories?: Array<Category>;+ customers?: Array<Customer>;+ customer_groups?: Array<CustomerGroup>;+ countries?: Array<Country>;}export default PromotionRule;diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.tsindex 1dbde8d7da..3778ac87eb 100644--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@ -1,4 +1,4 @@-// Typelizer digest 8b2fb3c06397f3f1bf93d3d55f32c826+// Typelizer digest 07edc878d242688dc28dabdabb31aca9//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'@@ -12,6 +12,7 @@ export type { default as CouponCode } from './CouponCode'export type { default as CreditCard } from './CreditCard'export type { default as CustomFieldDefinition } from './CustomFieldDefinition'export type { default as CustomField } from './CustomField'+export type { default as CustomerGroup } from './CustomerGroup'export type { default as Customer } from './Customer'export type { default as DeliveryMethod } from './DeliveryMethod'export type { default as DeliveryRate } from './DeliveryRate'diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex 9b4a55570f..7f28ef2aa8 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -19,6 +19,7 @@ export type { default as CouponCode } from './generated/CouponCode'export type { default as Country } from './generated/Country'export type { default as CreditCard } from './generated/CreditCard'export type { default as Customer } from './generated/Customer'+export type { default as CustomerGroup } from './generated/CustomerGroup'export type { default as CustomField } from './generated/CustomField'export type { default as CustomFieldDefinition } from './generated/CustomFieldDefinition'export type { default as DeliveryMethod } from './generated/DeliveryMethod'diff --git a/packages/admin/src/components/spree/calculator-summary.tsx b/packages/admin/src/components/spree/calculator-summary.tsxnew file mode 100644index 0000000000..06d7e134b6--- /dev/null+++ b/packages/admin/src/components/spree/calculator-summary.tsx@@ -0,0 +1,114 @@+/**+ * One-line preview of a calculator's configuration — "Flat Rate · $5.00",+ * "Percent on line item · 10%", etc. Used for promotion-action rows+ * today; intended as the shared row-summary for any calculator-backed+ * model (delivery methods, tax rates, …).+ *+ * The expected payload mirrors the admin API's calculator embed: a+ * `{ label, preferences, preference_schema }` triple. The component is+ * tolerant of partial input — missing schema or preferences just fall+ * back to the label alone.+ *+ * Lives on the frontend (rather than as a server-rendered string) so+ * draft edits update the row immediately, before any save.+ */+export interface CalculatorPayload {+ /** Human-readable name (e.g. "Flat Rate"). Optional; if missing the type is demodulized. */+ label?: string | null+ /** STI class name (e.g. "Spree::Calculator::FlatRate"). Used as a label fallback. */+ type?: string | null+ preferences?: Record<string, unknown> | null+ preference_schema?: ReadonlyArray<{ key: string; type: string }> | null+}++interface CalculatorSummaryProps {+ calculator: CalculatorPayload | null | undefined+ /**+ * What to show when `calculator` is missing or empty. Use this to+ * differentiate "no calculator picked" from "calculator with no+ * preferences yet." Defaults to nothing (returns null).+ */+ fallback?: React.ReactNode+ className?: string+}++export function CalculatorSummary({ calculator, fallback = null, className }: CalculatorSummaryProps) {+ const text = formatCalculatorSummary(calculator)+ if (!text) return <>{fallback}</>+ return <span className={className}>{text}</span>+}++/**+ * Pure formatter — exported for callers that want to embed the string+ * inside a larger sentence (e.g. "Free shipping · {summary}") or use+ * it in a non-React context.+ */+export function formatCalculatorSummary(calculator: CalculatorPayload | null | undefined): string | null {+ if (!calculator) return null++ const label =+ calculator.label?.trim() ||+ (calculator.type ? (calculator.type.split('::').pop() ?? calculator.type) : '')++ const schema = calculator.preference_schema+ const prefs = calculator.preferences++ if (!schema?.length || !prefs) return label || null++ const currency = (typeof prefs.currency === 'string' && prefs.currency) || 'USD'+ const details = schema+ .map((field) => formatField(field, prefs[field.key], currency))+ .filter((s): s is string => s !== null)+ .join(', ')++ if (!details) return label || null+ return label ? `${label} · ${details}` : details+}++/**+ * Formats one preference value by naming convention. Calculators don't+ * carry richer field metadata (no `display_format`, no `unit`), so we+ * fall back to key-name heuristics that match the Ruby preference+ * declarations in `Spree::Calculator::*`.+ *+ * - `amount` / `*_amount` decimals → currency-formatted.+ * - `*_percent` decimals → `N%`.+ * - `currency` strings → omitted (folded into the money formatting).+ * - booleans → humanized key when true; skipped when false.+ * - everything else → `key: value`.+ */+function formatField(+ field: { key: string; type: string },+ value: unknown,+ currency: string,+): string | null {+ if (value === null || value === undefined || value === '') return null+ if (field.key === 'currency') return null++ if (field.type === 'decimal') {+ if (/(?:^|_)percent$/.test(field.key)) return `${value}%`+ if (field.key === 'amount' || field.key.endsWith('_amount')) {+ return formatMoney(value, currency)+ }+ return `${humanize(field.key)}: ${value}`+ }+ if (field.type === 'boolean') {+ return value ? humanize(field.key) : null+ }+ return `${humanize(field.key)}: ${value}`+}++function formatMoney(value: unknown, currency: string): string {+ const n = typeof value === 'number' ? value : Number(value)+ if (Number.isNaN(n)) return String(value)+ try {+ return new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(n)+ } catch {+ return `${n} ${currency}`+ }+}++function humanize(key: string): string {+ const spaced = key.replace(/_/g, ' ').trim()+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)+}diff --git a/packages/admin/src/components/spree/preferences-form.tsx b/packages/admin/src/components/spree/preferences-form.tsxindex edfa08f62e..e4a41b084c 100644--- a/packages/admin/src/components/spree/preferences-form.tsx+++ b/packages/admin/src/components/spree/preferences-form.tsx@@ -1,4 +1,5 @@import type { PreferenceField as PreferenceFieldDef } from '@spree/admin-sdk'+import { CurrencySelect } from '@/components/spree/currency-select'import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'import { Input } from '@/components/ui/input'import { Switch } from '@/components/ui/switch'@@ -74,6 +75,22 @@ export function PreferenceField({const id = `preference-${field.key}`const displayLabel = label ?? humanizeKey(field.key)+ // Currency-typed preferences (`currency`, `default_currency`,+ // `display_currency`, …) get the store's CurrencySelect — same+ // localized `CODE — Full Name` rendering as the rest of admin.+ if (isCurrencyKey(field.key)) {+ return (+ <Field>+ <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>+ <CurrencySelect+ id={id}+ value={(value as string) || undefined}+ onChange={onChange}+ />+ </Field>+ )+ }+switch (field.type) {case 'boolean':return (@@ -194,3 +211,7 @@ function humanizeKey(key: string): string {.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ')}++function isCurrencyKey(key: string): boolean {+ return key === 'currency' || key.endsWith('_currency')+}diff --git a/packages/admin/src/components/spree/promotion-editors/action-adjustment.tsx b/packages/admin/src/components/spree/promotion-editors/action-adjustment.tsxnew file mode 100644index 0000000000..c9cfd37444--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/action-adjustment.tsx@@ -0,0 +1,152 @@+import type { PromotionActionCalculator } from '@spree/admin-sdk'+import { useQuery } from '@tanstack/react-query'+import { useEffect, useMemo, useState } from 'react'+import { adminClient } from '@/client'+import { PreferencesForm } from '@/components/spree/preferences-form'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { EditorShell } from './editor-shell'+import type { PromotionActionEditorContext } from './types'++/**+ * Editor for `Spree::Promotion::Actions::CreateAdjustment` and+ * `CreateItemAdjustments`. Both wrap a Calculator: the merchant picks+ * the subclass, the form below renders that calculator's preferences.+ */+export function AdjustmentActionEditor({+ draft,+ onSave,+ onClose,+}: PromotionActionEditorContext) {+ const { data: calculatorsData, isLoading: calculatorsLoading } = useQuery({+ queryKey: ['promotion-action-calculators', draft.type],+ queryFn: () => adminClient.promotionActions.calculators(draft.type),+ })++ const calculators = calculatorsData?.data ?? []++ const [calculatorType, setCalculatorType] = useState<string>(+ () => draft.calculator?.type ?? '',+ )+ const [preferences, setPreferences] = useState<Record<string, unknown>>(+ () => draft.calculator?.preferences ?? {},+ )++ // Once the catalog arrives, ensure `calculatorType` points at a known+ // calculator. Falls back to the first entry if the draft has no+ // calculator yet (newly-picked action) or carries a removed one.+ useEffect(() => {+ if (calculators.length === 0) return+ const matches = calculators.some((c) => c.type === calculatorType)+ if (!matches) setCalculatorType(calculators[0].type)+ }, [calculators, calculatorType])++ const selectedCalculator: PromotionActionCalculator | undefined = useMemo(+ () => calculators.find((c) => c.type === calculatorType),+ [calculators, calculatorType],+ )++ // Type changes swap the schema; previous preferences won't fit.+ function handleCalculatorChange(nextType: string) {+ if (nextType === calculatorType) return+ const next = calculators.find((c) => c.type === nextType)+ setCalculatorType(nextType)+ setPreferences(+ Object.fromEntries(+ (next?.preference_schema ?? []).map((field) => [field.key, field.default ?? '']),+ ),+ )+ }++ function handleSave() {+ if (!calculatorType) return+ onSave({+ ...draft,+ calculator: {+ type: calculatorType,+ preferences,+ // Display-only — lets `<ActionSummary>` render the row preview+ // without fetching `/calculators` again. Stripped at payload time.+ label: selectedCalculator?.label,+ preference_schema: selectedCalculator?.preference_schema,+ },+ })+ onClose()+ }++ return (+ <EditorShell+ onSave={handleSave}+ onCancel={onClose}+ pending={false}+ saveDisabled={!calculatorType}+ >+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="calculator-type">Calculator</FieldLabel>+ <Select+ value={calculatorType}+ onValueChange={handleCalculatorChange}+ disabled={calculatorsLoading || calculators.length === 0}+ >+ <SelectTrigger id="calculator-type">+ <SelectValue+ placeholder={calculatorsLoading ? 'Loading calculators…' : 'Select a calculator'}+ >+ {(value) =>+ calculators.find((c) => c.type === value)?.label ?? (value as string)+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {calculators.map((calculator) => (+ <SelectItem key={calculator.type} value={calculator.type}>+ {calculator.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ </FieldGroup>++ {selectedCalculator && (+ <CalculatorPreferences+ calculator={selectedCalculator}+ values={preferences}+ onChange={setPreferences}+ />+ )}+ </EditorShell>+ )+}++function CalculatorPreferences({+ calculator,+ values,+ onChange,+}: {+ calculator: PromotionActionCalculator+ values: Record<string, unknown>+ onChange: (next: Record<string, unknown>) => void+}) {+ if (!calculator.preference_schema?.length) {+ return <p className="text-sm text-muted-foreground">This calculator has no extra settings.</p>+ }++ return (+ <FieldGroup>+ <FieldLabel>Calculator settings</FieldLabel>+ <PreferencesForm+ schema={calculator.preference_schema}+ values={values}+ onChange={onChange}+ />+ </FieldGroup>+ )+}diff --git a/packages/admin/src/components/spree/promotion-editors/editor-shell.tsx b/packages/admin/src/components/spree/promotion-editors/editor-shell.tsxnew file mode 100644index 0000000000..c518be467b--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/editor-shell.tsx@@ -0,0 +1,50 @@+import type { ReactNode } from 'react'+import { Button } from '@/components/ui/button'+import { SheetFooter } from '@/components/ui/sheet'++/**+ * Shared layout for promotion rule and action editors. Wraps the body+ * in the standard scroll container and renders a save/cancel footer+ * — both behaviors that all built-in editors share. Editors only+ * provide their fields and a save handler.+ */+export function EditorShell({+ children,+ onSave,+ onCancel,+ pending,+ saveLabel = 'Save',+ saveDisabled,+}: {+ children: ReactNode+ onSave: () => void | Promise<void>+ onCancel: () => void+ pending: boolean+ saveLabel?: string+ saveDisabled?: boolean+}) {+ return (+ <>+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">{children}</div>+ <SheetFooter>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={onCancel}+ disabled={pending}+ >+ Cancel+ </Button>+ <Button+ type="button"+ size="sm"+ onClick={() => onSave()}+ disabled={pending || saveDisabled}+ >+ {pending ? 'Saving…' : saveLabel}+ </Button>+ </SheetFooter>+ </>+ )+}diff --git a/packages/admin/src/components/spree/promotion-editors/match-policy-picker.tsx b/packages/admin/src/components/spree/promotion-editors/match-policy-picker.tsxnew file mode 100644index 0000000000..cd6befc45a--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/match-policy-picker.tsx@@ -0,0 +1,54 @@+import { FieldGroup, FieldLabel } from '@/components/ui/field'+import { cn } from '@/lib/utils'++export interface MatchPolicyOption<TValue extends string> {+ value: TValue+ label: string+ description: string+}++/**+ * Card-style toggle group used by promotion rules with a `match_policy`+ * preference (Product → any/all/none, Taxon → any/all). Each option+ * is a labelled card with a description; visually emphasises the+ * selected one with a primary border + tinted background.+ */+export function MatchPolicyPicker<TValue extends string>({+ label = 'Match policy',+ policies,+ value,+ onChange,+}: {+ label?: string+ policies: readonly MatchPolicyOption<TValue>[]+ value: TValue+ onChange: (value: TValue) => void+}) {+ return (+ <FieldGroup>+ <FieldLabel>{label}</FieldLabel>+ <div className="grid gap-2">+ {policies.map((policy) => {+ const active = value === policy.value+ return (+ <button+ key={policy.value}+ type="button"+ onClick={() => onChange(policy.value)}+ className={cn(+ 'flex flex-col items-start gap-0.5 rounded-lg border p-3 text-left transition-colors',+ active+ ? 'border-blue-500 bg-blue-50 dark:border-blue-500/60 dark:bg-blue-500/10'+ : 'hover:bg-muted',+ )}+ aria-pressed={active}+ >+ <span className="text-sm font-medium">{policy.label}</span>+ <span className="text-xs text-muted-foreground">{policy.description}</span>+ </button>+ )+ })}+ </div>+ </FieldGroup>+ )+}diff --git a/packages/admin/src/components/spree/promotion-editors/register.ts b/packages/admin/src/components/spree/promotion-editors/register.tsnew file mode 100644index 0000000000..2d57d07b5a--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/register.ts@@ -0,0 +1,58 @@+import { registerSlot } from '@/lib/slot-registry'+import { AdjustmentActionEditor } from './action-adjustment'+import { CategoryRuleEditor } from './rule-category'+import { CountryRuleEditor } from './rule-country'+import { CustomerGroupRuleEditor } from './rule-customer-group'+import { ProductRuleEditor } from './rule-product'+import { UserRuleEditor } from './rule-user'+import { actionFormSlot, ruleFormSlot } from './types'++/**+ * Built-in editors for promotion rules and actions whose configuration+ * goes beyond a simple `preferences` hash. Imported once for its+ * side effects from the promotion detail route — extensions can call+ * `removeSlot(name, 'builtin')` to replace any of these with their own.+ *+ * Slot keys follow `promotion.rule_form.<rule.key>` and+ * `promotion.action_form.<action.key>`. Rules/actions whose key isn't+ * registered fall through to the generic `<DefaultRuleEditor>` /+ * `<DefaultActionEditor>` (preferences-only) in the parent route.+ */++// Rules with associations (products, taxons → categories, users) or+// preference arrays of prefixed IDs (customer groups, countries).+registerSlot(ruleFormSlot('product'), {+ id: 'builtin',+ component: ProductRuleEditor,+})++registerSlot(ruleFormSlot('category'), {+ id: 'builtin',+ component: CategoryRuleEditor,+})++registerSlot(ruleFormSlot('user'), {+ id: 'builtin',+ component: UserRuleEditor,+})++registerSlot(ruleFormSlot('customer_group'), {+ id: 'builtin',+ component: CustomerGroupRuleEditor,+})++registerSlot(ruleFormSlot('country'), {+ id: 'builtin',+ component: CountryRuleEditor,+})++// Both adjustment actions wrap a calculator and share the same editor.+registerSlot(actionFormSlot('create_adjustment'), {+ id: 'builtin',+ component: AdjustmentActionEditor,+})++registerSlot(actionFormSlot('create_item_adjustments'), {+ id: 'builtin',+ component: AdjustmentActionEditor,+})diff --git a/packages/admin/src/components/spree/promotion-editors/rule-category.tsx b/packages/admin/src/components/spree/promotion-editors/rule-category.tsxnew file mode 100644index 0000000000..808b8f4d71--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/rule-category.tsx@@ -0,0 +1,71 @@+import type { Category } from '@spree/admin-sdk'+import { useState } from 'react'+import { adminClient } from '@/client'+import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { EditorShell } from './editor-shell'+import { MatchPolicyPicker } from './match-policy-picker'+import type { PromotionRuleEditorContext } from './types'++type MatchPolicy = 'any' | 'all'+const MATCH_POLICIES: readonly { value: MatchPolicy; label: string; description: string }[] = [+ {+ value: 'any',+ label: 'Any of these categories',+ description: 'Order must contain a product in at least one.',+ },+ {+ value: 'all',+ label: 'All of these categories',+ description: 'Order must contain a product in every category.',+ },+]++/**+ * Surfaced as "Category(ies)" per the 6.0 Taxon→Category rename.+ * Backed by `Spree::Promotion::Rules::Taxon` until the table rename+ * ships; descendant categories match implicitly server-side.+ */+export function CategoryRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {+ const initialMatchPolicy = ((draft.preferences?.match_policy as MatchPolicy) ?? 'any') as MatchPolicy+ const [matchPolicy, setMatchPolicy] = useState<MatchPolicy>(+ MATCH_POLICIES.some((p) => p.value === initialMatchPolicy) ? initialMatchPolicy : 'any',+ )+ const [categoryIds, setCategoryIds] = useState<string[]>(draft.category_ids ?? [])+ const [categories, setCategories] = useState<Category[]>(draft.categories ?? [])++ function handleSave() {+ onSave({+ ...draft,+ preferences: { ...draft.preferences, match_policy: matchPolicy },+ category_ids: categoryIds,+ categories,+ })+ onClose()+ }++ return (+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>+ <MatchPolicyPicker policies={MATCH_POLICIES} value={matchPolicy} onChange={setMatchPolicy} />++ <FieldGroup>+ <Field>+ <FieldLabel>Categories</FieldLabel>+ <ResourceMultiAutocomplete+ queryKey="promotion-rule-categories"+ value={categoryIds}+ onChange={setCategoryIds}+ onResolvedOptionsChange={setCategories}+ search={(q) =>+ adminClient.categories.list({ name_cont: q, limit: 20, sort: 'pretty_name' })+ }+ hydrate={(ids) => adminClient.categories.list({ id_in: ids, limit: ids.length })}+ getOptionLabel={(c) => c.pretty_name ?? c.name ?? c.id}+ placeholder="Search categories…"+ emptyText="No categories match"+ />+ </Field>+ </FieldGroup>+ </EditorShell>+ )+}diff --git a/packages/admin/src/components/spree/promotion-editors/rule-country.tsx b/packages/admin/src/components/spree/promotion-editors/rule-country.tsxnew file mode 100644index 0000000000..576a2a4b3d--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/rule-country.tsx@@ -0,0 +1,73 @@+import type { Country } from '@spree/admin-sdk'+import { useState } from 'react'+import { adminClient } from '@/client'+import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { EditorShell } from './editor-shell'+import type { PromotionRuleEditorContext } from './types'++/**+ * Stores ISO codes — the `Country` resource has no numeric id, so its+ * primary key is `iso`. The autocomplete contract requires `{id: string}`,+ * so we project ISO onto `id` for the picker and round-trip it through+ * the rule's `country_isos` preference.+ */+export function CountryRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {+ const [countryIsos, setCountryIsos] = useState<string[]>(() =>+ ((draft.preferences?.country_isos ?? []) as string[]).map((s) => s.toUpperCase()),+ )+ const [countries, setCountries] = useState<Country[]>(draft.countries ?? [])++ function handleSave() {+ onSave({+ ...draft,+ preferences: { ...draft.preferences, country_isos: countryIsos },+ countries,+ })+ onClose()+ }++ return (+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>+ <FieldGroup>+ <Field>+ <FieldLabel>Countries</FieldLabel>+ <ResourceMultiAutocomplete<CountryOption>+ queryKey="promotion-rule-countries"+ value={countryIsos}+ onChange={setCountryIsos}+ onResolvedOptionsChange={(options) => setCountries(options.map(fromOption))}+ search={async (q) => {+ const result = await adminClient.countries.list({+ name_cont: q,+ limit: 20,+ sort: 'name',+ })+ return { data: result.data.map(toOption) }+ }}+ hydrate={async (isos) => {+ const result = await adminClient.countries.list({+ iso_in: isos,+ limit: isos.length,+ })+ return { data: result.data.map(toOption) }+ }}+ getOptionLabel={(c) => `${c.name} (${c.id})`}+ placeholder="Search countries…"+ emptyText="No countries match"+ />+ </Field>+ </FieldGroup>+ </EditorShell>+ )+}++type CountryOption = { id: string; name: string; raw: Country }++function toOption(country: Country): CountryOption {+ return { id: country.iso, name: country.name, raw: country }+}++function fromOption(option: CountryOption): Country {+ return option.raw+}diff --git a/packages/admin/src/components/spree/promotion-editors/rule-customer-group.tsx b/packages/admin/src/components/spree/promotion-editors/rule-customer-group.tsxnew file mode 100644index 0000000000..021e7490ef--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/rule-customer-group.tsx@@ -0,0 +1,48 @@+import type { CustomerGroup } from '@spree/admin-sdk'+import { useState } from 'react'+import { adminClient } from '@/client'+import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { EditorShell } from './editor-shell'+import type { PromotionRuleEditorContext } from './types'++export function CustomerGroupRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {+ const [groupIds, setGroupIds] = useState<string[]>(+ () => (draft.preferences?.customer_group_ids ?? []) as string[],+ )+ const [customerGroups, setCustomerGroups] = useState<CustomerGroup[]>(+ draft.customer_groups ?? [],+ )++ function handleSave() {+ onSave({+ ...draft,+ preferences: { ...draft.preferences, customer_group_ids: groupIds },+ customer_groups: customerGroups,+ })+ onClose()+ }++ return (+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>+ <FieldGroup>+ <Field>+ <FieldLabel>Customer groups</FieldLabel>+ <ResourceMultiAutocomplete+ queryKey="promotion-rule-customer-groups"+ value={groupIds}+ onChange={setGroupIds}+ onResolvedOptionsChange={setCustomerGroups}+ search={(q) =>+ adminClient.customerGroups.list({ name_cont: q, limit: 20, sort: 'name' })+ }+ hydrate={(ids) => adminClient.customerGroups.list({ id_in: ids, limit: ids.length })}+ getOptionLabel={(g) => g.name ?? g.id}+ placeholder="Search customer groups…"+ emptyText="No customer groups match"+ />+ </Field>+ </FieldGroup>+ </EditorShell>+ )+}diff --git a/packages/admin/src/components/spree/promotion-editors/rule-product.tsx b/packages/admin/src/components/spree/promotion-editors/rule-product.tsxnew file mode 100644index 0000000000..a8d8839f61--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/rule-product.tsx@@ -0,0 +1,61 @@+import type { Product } from '@spree/admin-sdk'+import { useState } from 'react'+import { adminClient } from '@/client'+import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { EditorShell } from './editor-shell'+import { MatchPolicyPicker } from './match-policy-picker'+import type { PromotionRuleEditorContext } from './types'++type MatchPolicy = 'any' | 'all' | 'none'+const MATCH_POLICIES: readonly { value: MatchPolicy; label: string; description: string }[] = [+ { value: 'any', label: 'Any of these products', description: 'Order must contain at least one.' },+ { value: 'all', label: 'All of these products', description: 'Order must contain every product.' },+ {+ value: 'none',+ label: 'None of these products',+ description: 'Order must not contain any of them.',+ },+]++export function ProductRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {+ const initialMatchPolicy = ((draft.preferences?.match_policy as MatchPolicy) ?? 'any') as MatchPolicy+ const [matchPolicy, setMatchPolicy] = useState<MatchPolicy>(+ MATCH_POLICIES.some((p) => p.value === initialMatchPolicy) ? initialMatchPolicy : 'any',+ )+ const [productIds, setProductIds] = useState<string[]>(draft.product_ids ?? [])+ const [products, setProducts] = useState<Product[]>(draft.products ?? [])++ function handleSave() {+ onSave({+ ...draft,+ preferences: { ...draft.preferences, match_policy: matchPolicy },+ product_ids: productIds,+ products,+ })+ onClose()+ }++ return (+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>+ <MatchPolicyPicker policies={MATCH_POLICIES} value={matchPolicy} onChange={setMatchPolicy} />++ <FieldGroup>+ <Field>+ <FieldLabel>Products</FieldLabel>+ <ResourceMultiAutocomplete+ queryKey="promotion-rule-products"+ value={productIds}+ onChange={setProductIds}+ onResolvedOptionsChange={setProducts}+ search={(q) => adminClient.products.list({ name_cont: q, limit: 10, sort: 'name' })}+ hydrate={(ids) => adminClient.products.list({ id_in: ids, limit: ids.length })}+ getOptionLabel={(p) => p.name ?? p.id}+ placeholder="Search products by name…"+ emptyText="No products match"+ />+ </Field>+ </FieldGroup>+ </EditorShell>+ )+}diff --git a/packages/admin/src/components/spree/promotion-editors/rule-user.tsx b/packages/admin/src/components/spree/promotion-editors/rule-user.tsxnew file mode 100644index 0000000000..3a7438f79c--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/rule-user.tsx@@ -0,0 +1,38 @@+import type { Customer } from '@spree/admin-sdk'+import { useState } from 'react'+import { adminClient } from '@/client'+import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { EditorShell } from './editor-shell'+import type { PromotionRuleEditorContext } from './types'++export function UserRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {+ const [userIds, setUserIds] = useState<string[]>(draft.user_ids ?? [])+ const [customers, setCustomers] = useState<Customer[]>(draft.customers ?? [])++ function handleSave() {+ onSave({ ...draft, user_ids: userIds, customers })+ onClose()+ }++ return (+ <EditorShell onSave={handleSave} onCancel={onClose} pending={false}>+ <FieldGroup>+ <Field>+ <FieldLabel>Customers</FieldLabel>+ <ResourceMultiAutocomplete+ queryKey="promotion-rule-users"+ value={userIds}+ onChange={setUserIds}+ onResolvedOptionsChange={setCustomers}+ search={(q) => adminClient.customers.list({ search: q, limit: 10 })}+ hydrate={(ids) => adminClient.customers.list({ id_in: ids, limit: ids.length })}+ getOptionLabel={(c) => c.full_name || c.email || c.id}+ placeholder="Search customers by name or email…"+ emptyText="No customers match"+ />+ </Field>+ </FieldGroup>+ </EditorShell>+ )+}diff --git a/packages/admin/src/components/spree/promotion-editors/types.ts b/packages/admin/src/components/spree/promotion-editors/types.tsnew file mode 100644index 0000000000..8cc3807078--- /dev/null+++ b/packages/admin/src/components/spree/promotion-editors/types.ts@@ -0,0 +1,252 @@+import type {+ Category,+ Country,+ Customer,+ CustomerGroup,+ PreferenceField,+ Product,+ PromotionAction,+ PromotionActionCalculatorParams,+ PromotionActionDraft,+ PromotionActionLineItemParams,+ PromotionRule,+ PromotionRuleDraft,+} from '@spree/admin-sdk'++/**+ * Form-state row for a promotion rule. Carries everything the editor+ * needs to render (`key`, `label`, `preference_schema`) plus the+ * payload fields the SDK ships on save (extends `PromotionRuleDraft`).+ *+ * Drafts seeded from existing rules carry the server's `id`; drafts+ * created via the picker have no id until the parent form saves.+ */+export interface PromotionRuleFormDraft extends PromotionRuleDraft {+ /** Stable key for slot dispatch + React list keys (`product`, `category`, …). */+ key: string+ /** Human-readable header rendered by the edit sheet. */+ label: string+ preference_schema: PreferenceField[]+ /** Client-side row id, used for React keys when the row has no server id yet. */+ _localId: string+ /**+ * Display-only embeds carried over from the server payload so row+ * summaries can render names without a separate fetch. Stripped at+ * payload time — the API only consumes the matching `*_ids`/preference+ * arrays. Re-set by the editors after Save so the summary refreshes+ * before the parent form persists.+ */+ products?: Product[]+ categories?: Category[]+ customers?: Customer[]+ customer_groups?: CustomerGroup[]+ countries?: Country[]+}++/** Mirrors `PromotionRuleFormDraft` for actions. */+export interface PromotionActionFormDraft extends Omit<PromotionActionDraft, 'calculator'> {+ key: string+ label: string+ preference_schema: PreferenceField[]+ _localId: string+ /**+ * Form-only calculator shape — extends the API's `{ type, preferences }`+ * payload with display fields (`label`, `preference_schema`) so the+ * action-row summary can render the calculator preview without+ * round-tripping. Stripped at payload time by `actionDraftToPayload`.+ */+ calculator?: PromotionActionCalculatorFormDraft+}++export interface PromotionActionCalculatorFormDraft extends PromotionActionCalculatorParams {+ label?: string+ preference_schema?: PreferenceField[]+}++/**+ * Slot context for a promotion rule editor. Editors mutate the draft+ * locally and call `onSave(next)` to write back to the parent form;+ * the parent persists everything via a single `PATCH /promotions`+ * when the user hits Save on the page header.+ *+ * Slot key: `promotion.rule_form.<draft.key>`+ */+export interface PromotionRuleEditorContext {+ draft: PromotionRuleFormDraft+ onSave: (next: PromotionRuleFormDraft) => void+ onClose: () => void+}++/** Mirrors `PromotionRuleEditorContext` for actions. */+export interface PromotionActionEditorContext {+ draft: PromotionActionFormDraft+ onSave: (next: PromotionActionFormDraft) => void+ onClose: () => void+}++/**+ * Slot context for the one-line rule summary shown in the rules list —+ * "United States, Canada" for Country, "3 products · any" for Product.+ * Falls back to a generic preferences dump when no slot is registered.+ *+ * Slot key: `promotion.rule_summary.<draft.key>`+ */+export interface PromotionRuleSummaryContext {+ draft: PromotionRuleFormDraft+}++/** Mirrors `PromotionRuleSummaryContext` for actions. */+export interface PromotionActionSummaryContext {+ draft: PromotionActionFormDraft+}++const PROMOTION_RULE_FORM_SLOT_PREFIX = 'promotion.rule_form.'+const PROMOTION_ACTION_FORM_SLOT_PREFIX = 'promotion.action_form.'+const PROMOTION_RULE_SUMMARY_SLOT_PREFIX = 'promotion.rule_summary.'+const PROMOTION_ACTION_SUMMARY_SLOT_PREFIX = 'promotion.action_summary.'++export function ruleFormSlot(key: string): string {+ return `${PROMOTION_RULE_FORM_SLOT_PREFIX}${key}`+}++export function actionFormSlot(key: string): string {+ return `${PROMOTION_ACTION_FORM_SLOT_PREFIX}${key}`+}++export function ruleSummarySlot(key: string): string {+ return `${PROMOTION_RULE_SUMMARY_SLOT_PREFIX}${key}`+}++export function actionSummarySlot(key: string): string {+ return `${PROMOTION_ACTION_SUMMARY_SLOT_PREFIX}${key}`+}++let nextLocalId = 0+/** Unique id for a freshly-picked draft, used as the React key. */+export function newLocalId(): string {+ nextLocalId += 1+ return `draft-${nextLocalId}`+}++/**+ * Builds a fresh draft from a registry type definition (e.g. an entry+ * returned by `/promotion_rules/types`). The `_localId` lets React+ * track the row before the server assigns a real `id`.+ */+export function ruleDraftFromType(type: {+ type: string+ label: string+ preference_schema: PreferenceField[]+}): PromotionRuleFormDraft {+ return {+ _localId: newLocalId(),+ type: type.type,+ key: type.type.split('::').pop()?.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase() ?? type.type,+ label: type.label,+ preference_schema: type.preference_schema,+ preferences: defaultPreferences(type.preference_schema),+ }+}++export function actionDraftFromType(type: {+ type: string+ label: string+ preference_schema: PreferenceField[]+}): PromotionActionFormDraft {+ return {+ _localId: newLocalId(),+ type: type.type,+ key: type.type.split('::').pop()?.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase() ?? type.type,+ label: type.label,+ preference_schema: type.preference_schema,+ preferences: defaultPreferences(type.preference_schema),+ }+}++/** Materializes a draft from an existing server-side rule. */+export function ruleDraftFromRule(rule: PromotionRule): PromotionRuleFormDraft {+ return {+ _localId: rule.id,+ id: rule.id,+ type: rule.type,+ key: rule.key,+ label: rule.label,+ preference_schema: rule.preference_schema,+ preferences: rule.preferences,+ product_ids: rule.product_ids ?? undefined,+ category_ids: rule.category_ids ?? undefined,+ user_ids: rule.user_ids ?? undefined,+ products: rule.products,+ categories: rule.categories,+ customers: rule.customers,+ customer_groups: rule.customer_groups,+ countries: rule.countries,+ }+}++export function actionDraftFromAction(action: PromotionAction): PromotionActionFormDraft {+ return {+ _localId: action.id,+ id: action.id,+ type: action.type,+ key: action.key,+ label: action.label,+ preference_schema: action.preference_schema,+ preferences: action.preferences,+ calculator: calculatorFromAction(action.calculator),+ line_items: action.line_items ?? undefined,+ }+}++function calculatorFromAction(+ c: PromotionAction['calculator'],+): PromotionActionCalculatorFormDraft | undefined {+ if (!c) return undefined+ return {+ type: c.type,+ preferences: c.preferences,+ label: c.label,+ preference_schema: c.preference_schema,+ }+}++function defaultPreferences(schema: PreferenceField[]): Record<string, unknown> {+ const out: Record<string, unknown> = {}+ for (const f of schema) {+ if (f.default !== null && f.default !== undefined) out[f.key] = f.default+ }+ return out+}++/** Strips display-only fields before sending to the API. */+export function ruleDraftToPayload(draft: PromotionRuleFormDraft): PromotionRuleDraft {+ const {+ _localId: _,+ key: __,+ label: ___,+ preference_schema: ____,+ products: _____,+ categories: ______,+ customers: _______,+ customer_groups: ________,+ countries: _________,+ ...rest+ } = draft+ return rest+}++export function actionDraftToPayload(draft: PromotionActionFormDraft): PromotionActionDraft {+ const { _localId: _, key: __, label: ___, preference_schema: ____, calculator, ...rest } = draft+ return {+ ...rest,+ calculator: calculator+ ? { type: calculator.type, preferences: calculator.preferences }+ : undefined,+ }+}++// Re-exports for convenience (editors only need to import from one place).+export type {+ PromotionActionCalculatorParams,+ PromotionActionLineItemParams,+}diff --git a/packages/admin/src/components/spree/resource-multi-autocomplete.tsx b/packages/admin/src/components/spree/resource-multi-autocomplete.tsxnew file mode 100644index 0000000000..8760f91778--- /dev/null+++ b/packages/admin/src/components/spree/resource-multi-autocomplete.tsx@@ -0,0 +1,225 @@+import { useQuery } from '@tanstack/react-query'+import { useCallback, useMemo, useState } from 'react'+import {+ Combobox,+ ComboboxChip,+ ComboboxChips,+ ComboboxChipsInput,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxItem,+ ComboboxList,+ ComboboxValue,+ useComboboxAnchor,+} from '@/components/ui/combobox'++/**+ * Anything we can pick. Items must have a stable string `id`. The label+ * (and any other rendering) is up to the caller via `getOptionLabel`.+ */+export type AutocompleteOption = { id: string }++export interface ResourceMultiAutocompleteProps<T extends AutocompleteOption> {+ /** Currently selected IDs (controlled). */+ value: string[]+ onChange: (next: string[]) => void+ /**+ * Optional companion callback fired alongside `onChange` carrying the+ * resolved option records (search results + cache lookups) for the+ * selected IDs. Use this to stamp display labels on the parent state+ * without re-fetching. IDs whose record isn't yet hydrated will be+ * absent from this list.+ *+ * Split from `onChange` so the picker's generic `T` can still be+ * inferred from `search`/`hydrate`/`getOptionLabel` without+ * contravariance from the callback parameter widening it.+ */+ onResolvedOptionsChange?: (options: T[]) => void++ /**+ * Server-side search. Receives the trimmed query string. Should return+ * `{ data: T[] }`. Called any time the user types (with debouncing+ * provided by the caller's queryClient if needed). Returning an empty+ * array on an empty query is a fine default — pass `enabled` via+ * `searchEnabled` if you want to gate it.+ */+ search: (query: string) => Promise<{ data: T[] }>++ /**+ * Hydration query for the IDs in `value` that we don't yet have+ * details for. Called once per `idsToHydrate` change. Should return+ * the listed records, in any order — they're keyed by `id`.+ *+ * If your endpoint can't bulk-fetch by ID, return what you can —+ * unmatched IDs render with their raw ID until the user picks them+ * from a search.+ */+ hydrate: (ids: string[]) => Promise<{ data: T[] }>++ /** Stable cache key for this picker instance — e.g. `'rule-products'`. */+ queryKey: string++ /** Renders the chip and dropdown row label. */+ getOptionLabel: (option: T) => string++ /** Placeholder for the search input. */+ placeholder?: string++ /** Empty state text shown in the dropdown when search returns nothing. */+ emptyText?: string++ /** Disable the whole picker. */+ disabled?: boolean+}++/**+ * Search-driven multi-select for a remote resource (products, taxons,+ * users, etc.). Mirrors the `<TagCombobox>` UX but with a server-driven+ * option list and lazy hydration of currently-selected IDs.+ *+ * Why this exists: every promotion rule that picks records (`Product`,+ * `Taxon`, `User`, `CustomerGroup`, `Country`, …) needs the same shape+ * — search + chips + hydration on first render. Centralising it here+ * keeps each rule editor down to ~30 lines of glue.+ */+export function ResourceMultiAutocomplete<T extends AutocompleteOption>({+ value,+ onChange,+ onResolvedOptionsChange,+ search,+ hydrate,+ queryKey,+ getOptionLabel,+ placeholder = 'Search…',+ emptyText = 'No results',+ disabled,+}: ResourceMultiAutocompleteProps<T>) {+ const anchorRef = useComboboxAnchor()+ const [inputValue, setInputValue] = useState('')++ // id → option cache. Survives across search queries so chips don't+ // flicker when `value` changes. Stored as a `Map` in state so we+ // never miss a render — TanStack Query's settle re-renders the+ // component, which re-derives `selectedOptions`/`items` from this.+ const [cache, setCache] = useState<Map<string, T>>(() => new Map())++ const cacheItems = useCallback((items: T[]) => {+ setCache((prev) => {+ let next: Map<string, T> | null = null+ for (const item of items) {+ if (prev.get(item.id) === item) continue+ next ??= new Map(prev)+ next.set(item.id, item)+ }+ return next ?? prev+ })+ }, [])++ // Hydrate any selected ID not yet in the cache. Recomputed when+ // `value` or `cache` changes; the query key only contains the+ // missing ids so re-toggling a known id doesn't refetch.+ const idsToHydrate = useMemo(+ () => value.filter((id) => !cache.has(id)),+ [value, cache],+ )++ useQuery({+ queryKey: [queryKey, 'hydrate', idsToHydrate],+ queryFn: async () => {+ const result = await hydrate(idsToHydrate)+ cacheItems(result.data)+ return result+ },+ enabled: idsToHydrate.length > 0,+ staleTime: Number.POSITIVE_INFINITY,+ })++ const trimmedInput = inputValue.trim()++ const { data: searchData, isFetching } = useQuery({+ queryKey: [queryKey, 'search', trimmedInput],+ queryFn: async () => {+ const result = await search(trimmedInput)+ cacheItems(result.data)+ return result+ },+ enabled: trimmedInput.length > 0,+ })++ // Dropdown items — search results, then any selected IDs not in+ // results so the user can deselect chips via the dropdown.+ const items = useMemo<T[]>(() => {+ const seen = new Set<string>()+ const list: T[] = []+ for (const item of searchData?.data ?? []) {+ if (seen.has(item.id)) continue+ seen.add(item.id)+ list.push(item)+ }+ for (const id of value) {+ if (seen.has(id)) continue+ const cached = cache.get(id)+ if (cached) {+ seen.add(id)+ list.push(cached)+ }+ }+ return list+ }, [searchData, value, cache])++ // Stub-fallback so chips show their ID until hydration lands.+ const selectedOptions = useMemo<T[]>(+ () => value.map((id) => cache.get(id) ?? ({ id } as T)),+ [value, cache],+ )++ const handleChange = useCallback(+ (next: T[]) => {+ onChange(next.map((o) => o.id))+ // Filter out stub `{id}` placeholders for un-hydrated IDs — callers+ // typically stamp these on parent state and stubs would overwrite+ // earlier real records.+ onResolvedOptionsChange?.(next.filter((o) => Object.keys(o).length > 1))+ setInputValue('')+ },+ [onChange, onResolvedOptionsChange],+ )++ return (+ <Combobox+ multiple+ items={items}+ value={selectedOptions}+ onValueChange={handleChange as never}+ itemToStringLabel={(o) => getOptionLabel(o as T)}+ itemToStringValue={(o) => (o as T).id}+ isItemEqualToValue={(a, b) => (a as T).id === (b as T).id}+ disabled={disabled}+ >+ <ComboboxChips ref={anchorRef}>+ <ComboboxValue>+ {(selected: T[]) =>+ selected.map((opt) => (+ <ComboboxChip key={opt.id}>{getOptionLabel(opt)}</ComboboxChip>+ ))+ }+ </ComboboxValue>+ <ComboboxChipsInput+ placeholder={placeholder}+ value={inputValue}+ onChange={(e) => setInputValue((e.target as HTMLInputElement).value)}+ />+ </ComboboxChips>+ <ComboboxContent anchor={anchorRef}>+ <ComboboxEmpty>{isFetching ? 'Searching…' : emptyText}</ComboboxEmpty>+ <ComboboxList>+ {(option: T) => (+ <ComboboxItem key={option.id} value={option}>+ {getOptionLabel(option)}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ )+}diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsxindex b1f8e1a19e..b39a889b4c 100644--- a/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx@@ -1,16 +1,35 @@-import type { PromotionAction, PromotionRule, ResourceTypeDefinition } from '@spree/admin-sdk'+import type { ResourceTypeDefinition } from '@spree/admin-sdk'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { DownloadIcon, PlusIcon, TrashIcon } from 'lucide-react'import { useEffect, useState } from 'react'-import { Controller, useForm } from 'react-hook-form'+import { Controller, useFieldArray, useForm } from 'react-hook-form'import { Can } from '@/components/spree/can'+import { formatCalculatorSummary } from '@/components/spree/calculator-summary'import { useConfirm } from '@/components/spree/confirm-dialog'import { PageHeader } from '@/components/spree/page-header'import { PreferencesForm } from '@/components/spree/preferences-form'+import { EditorShell } from '@/components/spree/promotion-editors/editor-shell'+import '@/components/spree/promotion-editors/register'+import {+ actionDraftFromAction,+ actionDraftFromType,+ actionDraftToPayload,+ actionFormSlot,+ type PromotionActionEditorContext,+ type PromotionActionFormDraft,+ type PromotionRuleEditorContext,+ type PromotionRuleFormDraft,+ ruleDraftFromRule,+ ruleDraftFromType,+ ruleDraftToPayload,+ ruleFormSlot,+} from '@/components/spree/promotion-editors/types'import { ResourceLayout } from '@/components/spree/resource-layout'+import { Slot } from '@/components/spree/slot'import { Badge } from '@/components/ui/badge'import { Button } from '@/components/ui/button'import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'+import { DatePicker } from '@/components/ui/date-picker'import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'import { Input } from '@/components/ui/input'import {@@ -28,15 +47,10 @@ import {SheetHeader,SheetTitle,} from '@/components/ui/sheet'-import { Switch } from '@/components/ui/switch'import { Textarea } from '@/components/ui/textarea'import { useExport } from '@/hooks/use-export'import {- useCreatePromotionAction,- useCreatePromotionRule,useDeletePromotion,- useDeletePromotionAction,- useDeletePromotionRule,usePromotion,usePromotionActions,usePromotionActionTypes,@@ -44,8 +58,6 @@ import {usePromotionRules,usePromotionRuleTypes,useUpdatePromotion,- useUpdatePromotionAction,- useUpdatePromotionRule,} from '@/hooks/use-promotions'import { Subject } from '@/lib/permissions'@@ -53,14 +65,15 @@ export const Route = createFileRoute('/_authenticated/$storeId/promotions/$promocomponent: EditPromotionPage,})-interface BasicsFormValues {+interface PromotionFormValues {name: stringdescription: stringstarts_at: stringexpires_at: stringusage_limit: number | undefinedmatch_policy: 'all' | 'any'- advertise: boolean+ rules: PromotionRuleFormDraft[]+ actions: PromotionActionFormDraft[]}const MATCH_POLICY_OPTIONS = [@@ -68,41 +81,52 @@ const MATCH_POLICY_OPTIONS = [{ value: 'any', label: 'Any rule may match' },] as const+const DEFAULT_VALUES: PromotionFormValues = {+ name: '',+ description: '',+ starts_at: '',+ expires_at: '',+ usage_limit: undefined,+ match_policy: 'all',+ rules: [],+ actions: [],+}+function EditPromotionPage() {const { storeId, promotionId } = Route.useParams()const navigate = useNavigate()const { data: promotion, isLoading } = usePromotion(promotionId)+ // Rules and actions are listed separately because the promotion serializer+ // doesn't embed them; we re-hydrate the form once both lists arrive.+ const { data: rulesData } = usePromotionRules(promotionId)+ const { data: actionsData } = usePromotionActions(promotionId)const updateMutation = useUpdatePromotion(promotionId)const deleteMutation = useDeletePromotion()const confirm = useConfirm()- const form = useForm<BasicsFormValues>({- defaultValues: {- name: '',- description: '',- starts_at: '',- expires_at: '',- usage_limit: undefined,- match_policy: 'all',- advertise: false,- },- })+ const form = useForm<PromotionFormValues>({ defaultValues: DEFAULT_VALUES })+ const rulesArray = useFieldArray({ control: form.control, name: 'rules', keyName: '_key' })+ const actionsArray = useFieldArray({ control: form.control, name: 'actions', keyName: '_key' })++ // Seed the form once the promotion + its child collections all arrive.+ // Re-runs after a successful submit because the queries are invalidated.+ // biome-ignore lint/correctness/useExhaustiveDependencies: form is stableuseEffect(() => {- if (promotion) {- form.reset({- name: promotion.name,- description: promotion.description ?? '',- starts_at: promotion.starts_at ? promotion.starts_at.slice(0, 16) : '',- expires_at: promotion.expires_at ? promotion.expires_at.slice(0, 16) : '',- usage_limit: promotion.usage_limit ?? undefined,- match_policy: promotion.match_policy,- advertise: promotion.advertise,- })- }- }, [promotion, form])-- async function onSubmit(values: BasicsFormValues) {+ if (!promotion || !rulesData || !actionsData) return+ form.reset({+ name: promotion.name,+ description: promotion.description ?? '',+ starts_at: promotion.starts_at ?? '',+ expires_at: promotion.expires_at ?? '',+ usage_limit: promotion.usage_limit ?? undefined,+ match_policy: promotion.match_policy,+ rules: rulesData.data.map(ruleDraftFromRule),+ actions: actionsData.data.map(actionDraftFromAction),+ })+ }, [promotion, rulesData, actionsData])++ async function onSubmit(values: PromotionFormValues) {await updateMutation.mutateAsync({name: values.name,description: values.description?.length ? values.description : null,@@ -110,7 +134,8 @@ function EditPromotionPage() {expires_at: values.expires_at || null,usage_limit: values.usage_limit ?? null,match_policy: values.match_policy,- advertise: values.advertise,+ rules: values.rules.map(ruleDraftToPayload),+ actions: values.actions.map(actionDraftToPayload),})}@@ -170,8 +195,8 @@ function EditPromotionPage() {main={<><PromotionBasicsCard form={form} promotion={promotion} />- <PromotionRulesCard promotionId={promotionId} matchPolicy={promotion.match_policy} />- <PromotionActionsCard promotionId={promotionId} />+ <PromotionRulesCard rulesArray={rulesArray} matchPolicy={form.watch('match_policy')} />+ <PromotionActionsCard actionsArray={actionsArray} />{promotion.multi_codes && <PromotionCouponCodesCard promotionId={promotionId} />}</>}@@ -231,12 +256,34 @@ function PromotionBasicsCard({ form, promotion }: PromotionBasicsCardProps) {<div className="grid grid-cols-1 gap-4 sm:grid-cols-2"><Field>- <FieldLabel htmlFor="starts_at">Starts</FieldLabel>- <Input id="starts_at" type="datetime-local" {...form.register('starts_at')} />+ <FieldLabel>Starts</FieldLabel>+ <Controller+ name="starts_at"+ control={form.control}+ render={({ field }) => (+ <DatePicker+ value={field.value || null}+ onChange={(v) => field.onChange(v ?? '')}+ placeholder="No start date"+ includeTime+ />+ )}+ /></Field><Field>- <FieldLabel htmlFor="expires_at">Expires</FieldLabel>- <Input id="expires_at" type="datetime-local" {...form.register('expires_at')} />+ <FieldLabel>Expires</FieldLabel>+ <Controller+ name="expires_at"+ control={form.control}+ render={({ field }) => (+ <DatePicker+ value={field.value || null}+ onChange={(v) => field.onChange(v ?? '')}+ placeholder="No expiry"+ includeTime+ />+ )}+ /></Field></div>@@ -277,22 +324,6 @@ function PromotionBasicsCard({ form, promotion }: PromotionBasicsCardProps) {/></Field>- <Field>- <div className="flex items-start justify-between gap-4">- <div className="flex flex-col">- <FieldLabel htmlFor="advertise" className="cursor-pointer">- Advertise on storefront- </FieldLabel>- </div>- <Controller- name="advertise"- control={form.control}- render={({ field }) => (- <Switch id="advertise" checked={!!field.value} onCheckedChange={field.onChange} />- )}- />- </div>- </Field></FieldGroup></CardContent></Card>@@ -303,21 +334,21 @@ function PromotionBasicsCard({ form, promotion }: PromotionBasicsCardProps) {// Rules// ============================================================================+type RulesArray = ReturnType<typeof useFieldArray<PromotionFormValues, 'rules', '_key'>>+type ActionsArray = ReturnType<typeof useFieldArray<PromotionFormValues, 'actions', '_key'>>+function PromotionRulesCard({- promotionId,+ rulesArray,matchPolicy,}: {- promotionId: string+ rulesArray: RulesArraymatchPolicy: 'all' | 'any'}) {- const { data: rulesData } = usePromotionRules(promotionId)const { data: typesData } = usePromotionRuleTypes()const [pickerOpen, setPickerOpen] = useState(false)- const [editingId, setEditingId] = useState<string | null>(null)+ const [editingIndex, setEditingIndex] = useState<number | null>(null)- const rules = rulesData?.data ?? []const types = typesData?.data ?? []- const editing = rules.find((r) => r.id === editingId)return (<Card>@@ -330,18 +361,18 @@ function PromotionRulesCard({</CardHeader><CardContent><div className="space-y-2">- {rules.length === 0 ? (+ {rulesArray.fields.length === 0 ? (<p className="text-sm text-muted-foreground">No rules. Without rules, the promotion always qualifies (subject to schedule and usagelimit).</p>) : (- rules.map((rule) => (+ rulesArray.fields.map((field, index) => (<RuleRow- key={rule.id}- rule={rule}- promotionId={promotionId}- onEdit={() => setEditingId(rule.id)}+ key={field._key}+ draft={field as unknown as PromotionRuleFormDraft}+ onEdit={() => setEditingIndex(index)}+ onRemove={() => rulesArray.remove(index)}/>)))}@@ -355,23 +386,24 @@ function PromotionRulesCard({{pickerOpen && (<RulePickerSheet- promotionId={promotionId}types={types}openonOpenChange={(o) => !o && setPickerOpen(false)}- onCreated={(id) => {+ onPicked={(type) => {+ const draft = ruleDraftFromType(type)+ rulesArray.append(draft)setPickerOpen(false)- setEditingId(id)+ setEditingIndex(rulesArray.fields.length) // newly-appended row index}}/>)}- {editing && (+ {editingIndex !== null && rulesArray.fields[editingIndex] && (<RuleEditSheet- promotionId={promotionId}- rule={editing}+ draft={rulesArray.fields[editingIndex] as unknown as PromotionRuleFormDraft}open- onOpenChange={(o) => !o && setEditingId(null)}+ onOpenChange={(o) => !o && setEditingIndex(null)}+ onSave={(next) => rulesArray.update(editingIndex, next)}/>)}</CardContent>@@ -380,27 +412,26 @@ function PromotionRulesCard({}function RuleRow({- rule,- promotionId,+ draft,onEdit,+ onRemove,}: {- rule: PromotionRule- promotionId: string+ draft: PromotionRuleFormDraftonEdit: () => void+ onRemove: () => void}) {- const deleteMutation = useDeletePromotionRule(promotionId)const confirm = useConfirm()- async function onDelete(e: React.MouseEvent) {+ async function handleRemove(e: React.MouseEvent) {e.stopPropagation()const ok = await confirm({title: 'Remove rule?',- message: 'This rule will be removed from the promotion.',+ message: 'Removed when you save the promotion.',variant: 'destructive',confirmLabel: 'Remove',})if (!ok) return- deleteMutation.mutate(rule.id)+ onRemove()}return (@@ -410,22 +441,15 @@ function RuleRow({className="flex w-full items-center justify-between rounded-md border bg-card px-3 py-2 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><div className="min-w-0">- <div className="text-sm font-medium">{rule.label}</div>- {Object.keys(rule.preferences ?? {}).length > 0 && (- <div className="truncate text-xs text-muted-foreground">- {Object.entries(rule.preferences as Record<string, unknown>)- .map(([k, v]) => `${k}: ${formatPrefValue(v)}`)- .join(' · ')}- </div>- )}+ <div className="text-sm font-medium">{draft.label}</div>+ <RuleSummary draft={draft} /></div><Can I="destroy" a={Subject.PromotionRule}><Buttontype="button"size="icon-xs"variant="ghost"- onClick={onDelete}- disabled={deleteMutation.isPending}+ onClick={handleRemove}className="text-destructive hover:bg-destructive/10 hover:text-destructive"><TrashIcon className="size-4" />@@ -435,49 +459,85 @@ function RuleRow({)}+function RuleSummary({ draft }: { draft: PromotionRuleFormDraft }) {+ const parts: string[] = []+ const products = nameList(draft.products)+ const categories = nameList(draft.categories)+ const customers = nameList(draft.customers, customerLabel)+ const groups = nameList(draft.customer_groups)+ const countries = nameList(draft.countries)++ if (products) parts.push(products)+ else if (draft.product_ids?.length) parts.push(`${draft.product_ids.length} products`)++ if (categories) parts.push(categories)+ else if (draft.category_ids?.length) parts.push(`${draft.category_ids.length} categories`)++ if (customers) parts.push(customers)+ else if (draft.user_ids?.length) parts.push(`${draft.user_ids.length} customers`)++ if (groups) parts.push(groups)+ if (countries) parts.push(countries)++ const policy = draft.preferences?.match_policy+ if (policy) parts.push(String(policy))++ if (parts.length === 0) return null+ return <div className="truncate text-xs text-muted-foreground">{parts.join(' · ')}</div>+}++/**+ * Joins up to 3 names; collapses the tail into "+N more". Returns null+ * when the list is missing or empty so the caller can fall back to a+ * count-based summary built from `*_ids`.+ */+function nameList<T>(items: T[] | undefined, getLabel: (item: T) => string = defaultLabel): string | null {+ if (!items?.length) return null+ const labels = items.map(getLabel).filter(Boolean)+ if (labels.length === 0) return null+ if (labels.length <= 3) return labels.join(', ')+ return `${labels.slice(0, 3).join(', ')} +${labels.length - 3} more`+}++function defaultLabel(o: unknown): string {+ if (o && typeof o === 'object' && 'name' in o && typeof (o as { name: unknown }).name === 'string') {+ return (o as { name: string }).name+ }+ return ''+}++function customerLabel(c: unknown): string {+ if (!c || typeof c !== 'object') return ''+ const o = c as { first_name?: string; last_name?: string; email?: string }+ const full = [o.first_name, o.last_name].filter(Boolean).join(' ').trim()+ return full || o.email || ''+}+function RulePickerSheet({- promotionId,types,open,onOpenChange,- onCreated,+ onPicked,}: {- promotionId: stringtypes: ResourceTypeDefinition[]open: booleanonOpenChange: (open: boolean) => void- onCreated: (id: string) => void+ onPicked: (type: ResourceTypeDefinition) => void}) {- const [selected, setSelected] = useState<string>('')- const createMutation = useCreatePromotionRule(promotionId)-- async function handleCreate() {- if (!selected) return- const rule = await createMutation.mutateAsync({ type: selected })- onCreated(rule.id)- setSelected('')- }-- const selectedType = types.find((t) => t.type === selected)-return (<Sheet open={open} onOpenChange={onOpenChange}><SheetContent><SheetHeader><SheetTitle>Add rule</SheetTitle>- <SheetDescription>- Pick a rule type. Configure its values after it's added.- </SheetDescription>+ <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) => (<buttonkey={t.type}type="button"- onClick={() => setSelected(t.type)}- className={`flex flex-col items-start rounded-md border p-3 text-left transition-colors ${- selected === t.type ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'- }`}+ 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 && (@@ -487,27 +547,9 @@ function RulePickerSheet({))}</div><SheetFooter>- <Button- type="button"- variant="outline"- size="sm"- onClick={() => onOpenChange(false)}- disabled={createMutation.isPending}- >+ <Button type="button" variant="outline" size="sm" onClick={() => onOpenChange(false)}>Cancel</Button>- <Button- type="button"- size="sm"- onClick={handleCreate}- disabled={!selected || createMutation.isPending}- >- {createMutation.isPending- ? 'Adding…'- : selectedType- ? `Add ${selectedType.label}`- : 'Add rule'}- </Button></SheetFooter></SheetContent></Sheet>@@ -515,83 +557,79 @@ function RulePickerSheet({}function RuleEditSheet({- promotionId,- rule,+ draft,open,onOpenChange,+ onSave,}: {- promotionId: string- rule: PromotionRule+ draft: PromotionRuleFormDraftopen: booleanonOpenChange: (open: boolean) => void+ onSave: (next: PromotionRuleFormDraft) => void}) {- const updateMutation = useUpdatePromotionRule(promotionId, rule.id)- const [values, setValues] = useState<Record<string, unknown>>(rule.preferences ?? {})-- useEffect(() => {- setValues(rule.preferences ?? {})- }, [rule])-- async function handleSave() {- await updateMutation.mutateAsync({ preferences: values })- onOpenChange(false)- }+ const onClose = () => onOpenChange(false)+ const ctx: PromotionRuleEditorContext = { draft, onSave, onClose }return (<Sheet open={open} onOpenChange={onOpenChange}><SheetContent><SheetHeader>- <SheetTitle>{rule.label}</SheetTitle>+ <SheetTitle>{draft.label}</SheetTitle><SheetDescription>Tune the rule's parameters.</SheetDescription></SheetHeader>- <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">- {rule.preference_schema?.length ? (- <PreferencesForm schema={rule.preference_schema} values={values} onChange={setValues} />- ) : (- <p className="text-sm text-muted-foreground">- This rule has no configurable options — its presence alone applies the constraint.- </p>- )}- </div>- <SheetFooter>- <Button- type="button"- variant="outline"- size="sm"- onClick={() => onOpenChange(false)}- disabled={updateMutation.isPending}- >- Cancel- </Button>- {rule.preference_schema?.length ? (- <Button- type="button"- size="sm"- onClick={handleSave}- disabled={updateMutation.isPending}- >- {updateMutation.isPending ? 'Saving…' : 'Save'}- </Button>- ) : null}- </SheetFooter>+ <Slot+ name={ruleFormSlot(draft.key)}+ context={ctx}+ fallback={<DefaultRuleEditor {...ctx} />}+ /></SheetContent></Sheet>)}+/**+ * Default rule editor — renders a generic PreferencesForm for rules+ * whose configuration is exhausted by their preference schema+ * (Currency, FirstOrder, ItemTotal, etc.).+ */+function DefaultRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {+ const [values, setValues] = useState<Record<string, unknown>>(draft.preferences ?? {})++ const hasPreferences = !!draft.preference_schema?.length++ function handleSave() {+ onSave({ ...draft, preferences: values })+ onClose()+ }++ return (+ <EditorShell+ onSave={handleSave}+ onCancel={onClose}+ pending={false}+ saveDisabled={!hasPreferences}+ >+ {hasPreferences ? (+ <PreferencesForm schema={draft.preference_schema} values={values} onChange={setValues} />+ ) : (+ <p className="text-sm text-muted-foreground">+ This rule has no configurable options — its presence alone applies the constraint.+ </p>+ )}+ </EditorShell>+ )+}+// ============================================================================// Actions// ============================================================================-function PromotionActionsCard({ promotionId }: { promotionId: string }) {- const { data: actionsData } = usePromotionActions(promotionId)+function PromotionActionsCard({ actionsArray }: { actionsArray: ActionsArray }) {const { data: typesData } = usePromotionActionTypes()const [pickerOpen, setPickerOpen] = useState(false)- const [editingId, setEditingId] = useState<string | null>(null)+ const [editingIndex, setEditingIndex] = useState<number | null>(null)- const actions = actionsData?.data ?? []const types = typesData?.data ?? []- const editing = actions.find((a) => a.id === editingId)return (<Card>@@ -601,17 +639,17 @@ function PromotionActionsCard({ promotionId }: { promotionId: string }) {</CardHeader><CardContent><div className="space-y-2">- {actions.length === 0 ? (+ {actionsArray.fields.length === 0 ? (<p className="text-sm text-muted-foreground">No actions yet. A promotion without actions doesn't do anything when applied.</p>) : (- actions.map((action) => (+ actionsArray.fields.map((field, index) => (<ActionRow- key={action.id}- action={action}- promotionId={promotionId}- onEdit={() => setEditingId(action.id)}+ key={field._key}+ draft={field as unknown as PromotionActionFormDraft}+ onEdit={() => setEditingIndex(index)}+ onRemove={() => actionsArray.remove(index)}/>)))}@@ -625,23 +663,24 @@ function PromotionActionsCard({ promotionId }: { promotionId: string }) {{pickerOpen && (<ActionPickerSheet- promotionId={promotionId}types={types}openonOpenChange={(o) => !o && setPickerOpen(false)}- onCreated={(id) => {+ onPicked={(type) => {+ const draft = actionDraftFromType(type)+ actionsArray.append(draft)setPickerOpen(false)- setEditingId(id)+ setEditingIndex(actionsArray.fields.length)}}/>)}- {editing && (+ {editingIndex !== null && actionsArray.fields[editingIndex] && (<ActionEditSheet- promotionId={promotionId}- action={editing}+ draft={actionsArray.fields[editingIndex] as unknown as PromotionActionFormDraft}open- onOpenChange={(o) => !o && setEditingId(null)}+ onOpenChange={(o) => !o && setEditingIndex(null)}+ onSave={(next) => actionsArray.update(editingIndex, next)}/>)}</CardContent>@@ -650,27 +689,26 @@ function PromotionActionsCard({ promotionId }: { promotionId: string }) {}function ActionRow({- action,- promotionId,+ draft,onEdit,+ onRemove,}: {- action: PromotionAction- promotionId: string+ draft: PromotionActionFormDraftonEdit: () => void+ onRemove: () => void}) {- const deleteMutation = useDeletePromotionAction(promotionId)const confirm = useConfirm()- async function onDelete(e: React.MouseEvent) {+ async function handleRemove(e: React.MouseEvent) {e.stopPropagation()const ok = await confirm({title: 'Remove action?',- message: 'This action will be removed from the promotion.',+ message: 'Removed when you save the promotion.',variant: 'destructive',confirmLabel: 'Remove',})if (!ok) return- deleteMutation.mutate(action.id)+ onRemove()}return (@@ -680,22 +718,15 @@ function ActionRow({className="flex w-full items-center justify-between rounded-md border bg-card px-3 py-2 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><div className="min-w-0">- <div className="text-sm font-medium">{action.label}</div>- {Object.keys(action.preferences ?? {}).length > 0 && (- <div className="truncate text-xs text-muted-foreground">- {Object.entries(action.preferences as Record<string, unknown>)- .map(([k, v]) => `${k}: ${formatPrefValue(v)}`)- .join(' · ')}- </div>- )}+ <div className="text-sm font-medium">{draft.label}</div>+ <ActionSummary draft={draft} /></div><Can I="destroy" a={Subject.PromotionAction}><Buttontype="button"size="icon-xs"variant="ghost"- onClick={onDelete}- disabled={deleteMutation.isPending}+ onClick={handleRemove}className="text-destructive hover:bg-destructive/10 hover:text-destructive"><TrashIcon className="size-4" />@@ -705,31 +736,26 @@ function ActionRow({)}+function ActionSummary({ draft }: { draft: PromotionActionFormDraft }) {+ const parts: string[] = []+ const calc = formatCalculatorSummary(draft.calculator)+ if (calc) parts.push(calc)+ if (draft.line_items?.length) parts.push(`${draft.line_items.length} variants`)+ if (parts.length === 0) return null+ return <div className="truncate text-xs text-muted-foreground">{parts.join(' · ')}</div>+}+function ActionPickerSheet({- promotionId,types,open,onOpenChange,- onCreated,+ onPicked,}: {- promotionId: stringtypes: ResourceTypeDefinition[]open: booleanonOpenChange: (open: boolean) => void- onCreated: (id: string) => void+ onPicked: (type: ResourceTypeDefinition) => void}) {- const [selected, setSelected] = useState<string>('')- const createMutation = useCreatePromotionAction(promotionId)-- async function handleCreate() {- if (!selected) return- const action = await createMutation.mutateAsync({ type: selected })- onCreated(action.id)- setSelected('')- }-- const selectedType = types.find((t) => t.type === selected)-return (<Sheet open={open} onOpenChange={onOpenChange}><SheetContent>@@ -742,10 +768,8 @@ function ActionPickerSheet({<buttonkey={t.type}type="button"- onClick={() => setSelected(t.type)}- className={`flex flex-col items-start rounded-md border p-3 text-left transition-colors ${- selected === t.type ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'- }`}+ 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 && (@@ -755,27 +779,9 @@ function ActionPickerSheet({))}</div><SheetFooter>- <Button- type="button"- variant="outline"- size="sm"- onClick={() => onOpenChange(false)}- disabled={createMutation.isPending}- >+ <Button type="button" variant="outline" size="sm" onClick={() => onOpenChange(false)}>Cancel</Button>- <Button- type="button"- size="sm"- onClick={handleCreate}- disabled={!selected || createMutation.isPending}- >- {createMutation.isPending- ? 'Adding…'- : selectedType- ? `Add ${selectedType.label}`- : 'Add action'}- </Button></SheetFooter></SheetContent></Sheet>@@ -783,74 +789,66 @@ function ActionPickerSheet({}function ActionEditSheet({- promotionId,- action,+ draft,open,onOpenChange,+ onSave,}: {- promotionId: string- action: PromotionAction+ draft: PromotionActionFormDraftopen: booleanonOpenChange: (open: boolean) => void+ onSave: (next: PromotionActionFormDraft) => void}) {- const updateMutation = useUpdatePromotionAction(promotionId, action.id)- const [values, setValues] = useState<Record<string, unknown>>(action.preferences ?? {})-- useEffect(() => {- setValues(action.preferences ?? {})- }, [action])-- async function handleSave() {- await updateMutation.mutateAsync({ preferences: values })- onOpenChange(false)- }+ const onClose = () => onOpenChange(false)+ const ctx: PromotionActionEditorContext = { draft, onSave, onClose }return (<Sheet open={open} onOpenChange={onOpenChange}><SheetContent><SheetHeader>- <SheetTitle>{action.label}</SheetTitle>+ <SheetTitle>{draft.label}</SheetTitle><SheetDescription>Configure the action's parameters.</SheetDescription></SheetHeader>- <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">- {action.preference_schema?.length ? (- <PreferencesForm- schema={action.preference_schema}- values={values}- onChange={setValues}- />- ) : (- <p className="text-sm text-muted-foreground">- This action has no configurable options.- </p>- )}- </div>- <SheetFooter>- <Button- type="button"- variant="outline"- size="sm"- onClick={() => onOpenChange(false)}- disabled={updateMutation.isPending}- >- Cancel- </Button>- {action.preference_schema?.length ? (- <Button- type="button"- size="sm"- onClick={handleSave}- disabled={updateMutation.isPending}- >- {updateMutation.isPending ? 'Saving…' : 'Save'}- </Button>- ) : null}- </SheetFooter>+ <Slot+ name={actionFormSlot(draft.key)}+ context={ctx}+ fallback={<DefaultActionEditor {...ctx} />}+ /></SheetContent></Sheet>)}+function DefaultActionEditor({ draft, onSave, onClose }: PromotionActionEditorContext) {+ const [values, setValues] = useState<Record<string, unknown>>(draft.preferences ?? {})++ const hasPreferences = !!draft.preference_schema?.length++ function handleSave() {+ onSave({ ...draft, preferences: values })+ onClose()+ }++ return (+ <EditorShell+ onSave={handleSave}+ onCancel={onClose}+ pending={false}+ saveDisabled={!hasPreferences}+ >+ {hasPreferences ? (+ <PreferencesForm+ schema={draft.preference_schema}+ values={values}+ onChange={setValues}+ />+ ) : (+ <p className="text-sm text-muted-foreground">This action has no configurable options.</p>+ )}+ </EditorShell>+ )+}+// ============================================================================// Coupon codes (multi-codes only)// ============================================================================@@ -951,10 +949,3 @@ function PromotionCouponCodesCard({ promotionId }: { promotionId: string }) {</Card>)}--function formatPrefValue(value: unknown): string {- if (Array.isArray(value)) return `[${value.length}]`- if (typeof value === 'boolean') return value ? 'yes' : 'no'- if (value === null || value === undefined || value === '') return '—'- return String(value)-}diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsxindex 75ccac3dd9..a2c708cb05 100644--- a/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx@@ -6,6 +6,7 @@ import { PageHeader } from '@/components/spree/page-header'import { ResourceLayout } from '@/components/spree/resource-layout'import { Button } from '@/components/ui/button'import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'+import { DatePicker } from '@/components/ui/date-picker'import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'import { Input } from '@/components/ui/input'import {@@ -36,7 +37,6 @@ const formSchema = zexpires_at: z.string().optional(),usage_limit: z.coerce.number().int().positive().optional(),match_policy: z.enum(['all', 'any']),- advertise: z.boolean(),}).superRefine((v, ctx) => {if (v.kind === 'coupon_code' && !v.multi_codes && !v.code?.trim()) {@@ -110,7 +110,6 @@ const DEFAULTS: FormValues = {expires_at: '',usage_limit: undefined,match_policy: 'all',- advertise: false,}function NewPromotionPage() {@@ -135,7 +134,6 @@ function NewPromotionPage() {expires_at: values.expires_at || null,usage_limit: values.usage_limit ?? null,match_policy: values.match_policy,- advertise: values.advertise,...couponFieldsForKind(values),})navigate({@@ -314,15 +312,33 @@ function NewPromotionPage() {<FieldGroup><div className="grid grid-cols-1 gap-4 sm:grid-cols-2"><Field>- <FieldLabel htmlFor="starts_at">Starts</FieldLabel>- <Input id="starts_at" type="datetime-local" {...form.register('starts_at')} />+ <FieldLabel>Starts</FieldLabel>+ <Controller+ name="starts_at"+ control={form.control}+ render={({ field }) => (+ <DatePicker+ value={field.value || null}+ onChange={(v) => field.onChange(v ?? '')}+ placeholder="No start date"+ includeTime+ />+ )}+ /></Field><Field>- <FieldLabel htmlFor="expires_at">Expires</FieldLabel>- <Input- id="expires_at"- type="datetime-local"- {...form.register('expires_at')}+ <FieldLabel>Expires</FieldLabel>+ <Controller+ name="expires_at"+ control={form.control}+ render={({ field }) => (+ <DatePicker+ value={field.value || null}+ onChange={(v) => field.onChange(v ?? '')}+ placeholder="No expiry"+ includeTime+ />+ )}/></Field></div>@@ -366,35 +382,12 @@ function NewPromotionPage() {/></Field>- <Field>- <div className="flex items-start justify-between gap-4">- <div className="flex flex-col">- <FieldLabel htmlFor="advertise" className="cursor-pointer">- Advertise this promotion- </FieldLabel>- <span className="text-xs text-muted-foreground">- Surface it on the storefront when applicable.- </span>- </div>- <Controller- name="advertise"- control={form.control}- render={({ field }) => (- <Switch- id="advertise"- checked={!!field.value}- onCheckedChange={field.onChange}- />- )}- />- </div>- </Field></FieldGroup></CardContent></Card><p className="text-sm text-muted-foreground">- You'll add actions and rules after the promotion is created.+ Configure rules and actions after the promotion is created.</p></>}diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rbindex b68f9ba3f9..6c7efd84b7 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/subclassed_resource.rb@@ -38,14 +38,15 @@ module Spreeenddef create- klass = resolve_subclass(permitted_params[:type])+ klass = resolve_subclass(params[:type])return render_unknown_type unless klass- attrs = permitted_params.except(:type, :preferences)- preferences = permitted_params[:preferences]+ permitted = permitted_params_for(klass)+ attrs, preferences, calculator = extract_subclass_params(permitted)@resource = build_subclassed_resource(klass, attrs)apply_preferences(@resource, preferences) if preferences.present?+ apply_calculator(@resource, calculator) if calculator.present?authorize_resource!(@resource, :create)if @resource.save@@ -59,11 +60,12 @@ module Spree@resource = find_resourceauthorize_resource!(@resource, :update)- attrs = permitted_params.except(:type, :preferences)- preferences = permitted_params[:preferences]+ permitted = permitted_params_for(@resource.class)+ attrs, preferences, calculator = extract_subclass_params(permitted)@resource.assign_attributes(attrs)apply_preferences(@resource, preferences) if preferences.present?+ apply_calculator(@resource, calculator) if calculator.present?if @resource.saverender json: serialize_resource(@resource)@@ -74,6 +76,18 @@ module Spreeprivate+ # Per-subclass permitted params. Calls `permitted_params` (the base+ # allowlist with `type` + `preferences`) and merges in extras the+ # subclass has declared via `additional_permitted_attributes`.+ # Controllers can override this hook directly if their subclasses+ # expose extras through a different mechanism.+ def permitted_params_for(klass)+ extras = klass.respond_to?(:additional_permitted_attributes) ? klass.additional_permitted_attributes : []+ return permitted_params if extras.blank?++ params.permit(:type, { preferences: {} }, *extras)+ end+# Default build: top-level resource. Nested controllers (actions,# rules) override to attach the parent.def build_subclassed_resource(klass, attrs)@@ -102,6 +116,25 @@ module Spreeresource.set_preference(key.to_sym, value)endend++ # Pulls `preferences` and `calculator` out of the permitted+ # params so they can be routed through their typed setters+ # (`set_preference`, `assign_calculator_attributes`) instead+ # of generic `assign_attributes`. The remaining hash is+ # safe to pass through as plain attribute assignments.+ def extract_subclass_params(permitted)+ permitted = permitted.respond_to?(:to_unsafe_h) ? permitted.to_unsafe_h.with_indifferent_access : permitted.with_indifferent_access+ permitted.delete(:type) # subclass is already resolved; don't let it overwrite STI column+ preferences = permitted.delete(:preferences)+ calculator = permitted.delete(:calculator)+ [permitted, preferences, calculator]+ end++ def apply_calculator(resource, calculator)+ return unless resource.respond_to?(:assign_calculator_attributes)++ resource.assign_calculator_attributes(calculator)+ endendendenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/customer_groups_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customer_groups_controller.rbnew file mode 100644index 0000000000..3bb2fcaf5e--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/customer_groups_controller.rb@@ -0,0 +1,29 @@+module Spree+ module Api+ module V3+ module Admin+ # Admin CRUD for `Spree::CustomerGroup`. Scoped to the current+ # store so groups from sibling stores don't leak into pickers.+ class CustomerGroupsController < ResourceController+ protected++ def model_class+ Spree::CustomerGroup+ end++ def serializer_class+ Spree.api.admin_customer_group_serializer+ end++ def scope+ super.for_store(current_store)+ end++ def permitted_params+ params.permit(:name)+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rbindex 9f447b11d5..1c246dc340 100644--- a/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/promotion_actions_controller.rb@@ -19,6 +19,28 @@ module Spreerender json: { data: model_class.subclasses_with_preference_schema }end+ # Returns the calculator subclasses registered for the given action+ # `type` (e.g. `?type=Spree::Promotion::Actions::CreateAdjustment`).+ # Each entry includes the calculator's class name, label,+ # description, and preference schema so the SPA can render the+ # picker + nested fields without hardcoding the calculator list.+ def calculators+ authorize! :read, model_class++ klass = resolve_subclass(params[:type])+ return render_unknown_type unless klass && klass.respond_to?(:calculators)++ data = klass.calculators.map do |calc|+ {+ type: calc.to_s,+ label: calc.respond_to?(:description) ? calc.description : calc.to_s.demodulize.titleize,+ preference_schema: calc.respond_to?(:preference_schema) ? calc.preference_schema : []+ }+ end.sort_by { |entry| entry[:label].to_s }++ render json: { data: data }+ end+protecteddef model_class@@ -34,7 +56,7 @@ module Spreeenddef set_parent- return if action_name == 'types'+ return if %w[types calculators].include?(action_name)@parent = Spree::Promotion.accessible_by(current_ability, :show).find_by_prefix_id!(params[:promotion_id])diff --git a/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rbindex 9d136309d8..566700902c 100644--- a/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb@@ -26,11 +26,48 @@ module Spreepromotion_includesend+ # Extends the base permit list with `rules` and `actions` arrays+ # so a single `POST` / `PATCH /promotions[/:id]` can ship the+ # full graph (basics + rules + actions). Each entry is a flat+ # hash whose `type` selects the STI subclass; per-subclass+ # extras come from `additional_permitted_attributes`. The+ # `Promotion#rules=`/`actions=` setters reconcile to the+ # desired set on save.+ def permitted_params+ base = params.permit(*permitted_attributes).to_h+ rules = permit_subclassed_collection(:rules, Spree.promotions.rules)+ actions = permit_subclassed_collection(:actions, Spree.promotions.actions)++ base[:rules] = rules if params.key?(:rules)+ base[:actions] = actions if params.key?(:actions)++ normalize_params(ActionController::Parameters.new(base).permit!)+ end+privatedef promotion_includes[:stores, :promotion_actions, :promotion_rules]end++ # Permits an array of subclass payloads (`rules` / `actions`).+ # Each entry is permitted with the union of every registered+ # subclass's `additional_permitted_attributes`, plus `id`,+ # `type`, and `preferences`. Returns the array of plain+ # hashes ready to hand to `Promotion#rules=`/`actions=`.+ def permit_subclassed_collection(key, registry)+ entries = params[key]+ return [] unless entries.is_a?(Array) || entries.respond_to?(:to_a)++ extras = registry.flat_map do |klass|+ klass.respond_to?(:additional_permitted_attributes) ? klass.additional_permitted_attributes : []+ end.uniq++ Array(entries).map do |entry|+ entry = entry.respond_to?(:to_unsafe_h) ? ActionController::Parameters.new(entry.to_unsafe_h) : ActionController::Parameters.new(entry.to_h)+ entry.permit(:id, :type, { preferences: {} }, *extras).to_h+ end+ endendendenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/customer_group_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/customer_group_serializer.rbnew file mode 100644index 0000000000..2140c7100f--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/customer_group_serializer.rb@@ -0,0 +1,18 @@+module Spree+ module Api+ module V3+ module Admin+ # Serializes Spree::CustomerGroup for the admin pickers+ # (e.g. promotion rule, customer-group filters). Surfaces only+ # what the admin UI needs to display + select rows.+ class CustomerGroupSerializer < V3::BaseSerializer+ typelize name: :string,+ users_count: :number++ attributes :name, :users_count,+ created_at: :iso8601, updated_at: :iso8601+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rbindex 7d368259d5..7f04d27e74 100644--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_action_serializer.rb@@ -10,14 +10,21 @@ module Spree# current value hash, `preference_schema` describes its fields.class PromotionActionSerializer < BaseSerializertypelize type: :string,+ key: :string,promotion_id: :string,preferences: 'Record<string, unknown>',preference_schema: "Array<{ key: string; type: string; default: unknown }>",- label: :string+ label: :string,+ calculator: "{ type: string; label: string; preferences: Record<string, unknown>; preference_schema: Array<{ key: string; type: string; default: unknown }> } | null",+ line_items: 'Array<{ variant_id: string; quantity: number }> | null'attributes :type,created_at: :iso8601, updated_at: :iso8601+ attribute :key do |action|+ action.key+ end+attribute :promotion_id do |action|action.promotion&.prefixed_idend@@ -33,6 +40,37 @@ module Spreeattribute :label do |action|action.respond_to?(:human_name) ? action.human_name : action.type.to_s.demodulizeend++ # Calculator is exposed as a nested object so the SPA can render+ # the calculator picker + its own preference fields. Null for+ # actions that don't include CalculatedAdjustments. The SPA+ # formats the row summary itself off `label` + `preferences` —+ # see the action-summary helper in the admin promotion editor.+ attribute :calculator do |action|+ next nil unless action.respond_to?(:calculator) && action.calculator++ calc = action.calculator+ {+ type: calc.class.to_s,+ label: calc.class.respond_to?(:description) ? calc.class.description : calc.class.to_s.demodulize.titleize,+ preferences: calc.preferences.to_h,+ preference_schema: calc.class.preference_schema+ }+ end++ # Line items the action will add for CreateLineItems. variant_id+ # is prefixed for consistency with the rest of the API. Null on+ # actions that don't have the association.+ attribute :line_items do |action|+ next nil unless action.respond_to?(:promotion_action_line_items)++ action.promotion_action_line_items.map do |item|+ {+ variant_id: item.variant&.prefixed_id,+ quantity: item.quantity+ }+ end+ endendendenddiff --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 e7331f21aa..406e7cbf6a 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@@ -9,14 +9,22 @@ module Spree# frontend renders both with the same generic component.class PromotionRuleSerializer < BaseSerializertypelize type: :string,+ key: :string,promotion_id: :string,preferences: 'Record<string, unknown>',preference_schema: "Array<{ key: string; type: string; default: unknown }>",- label: :string+ label: :string,+ product_ids: 'Array<string> | null',+ category_ids: 'Array<string> | null',+ user_ids: 'Array<string> | null'attributes :type,created_at: :iso8601, updated_at: :iso8601+ attribute :key do |rule|+ rule.key+ end+attribute :promotion_id do |rule|rule.promotion&.prefixed_idend@@ -32,6 +40,51 @@ module Spreeattribute :label do |rule|rule.respond_to?(:human_name) ? rule.human_name : rule.type.to_s.demodulizeend++ # Association IDs for rules that wire products/taxons/users through+ # join tables. Returned as prefixed IDs to match the rest of the+ # API; null on rules that don't have the association. The matching+ # `products`/`categories`/`customers` collections below embed the+ # full records via their admin serializers so the SPA can render+ # names + extra info without an extra round-trip.+ attribute :product_ids do |rule|+ rule.products.map(&:prefixed_id) if rule.respond_to?(:products)+ end++ attribute :category_ids do |rule|+ rule.taxons.map(&:prefixed_id) if rule.respond_to?(:taxons)+ end++ attribute :user_ids do |rule|+ rule.users.map(&:prefixed_id) if rule.respond_to?(:users)+ 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+ # products) skip via `if:` and the key is omitted from the+ # payload.+ many :products,+ resource: Spree.api.admin_product_serializer,+ if: proc { |rule| rule.respond_to?(:products) }++ many :taxons,+ key: :categories,+ resource: Spree.api.admin_category_serializer,+ if: proc { |rule| rule.respond_to?(:taxons) }++ many :users,+ key: :customers,+ resource: Spree.api.admin_customer_serializer,+ if: proc { |rule| rule.respond_to?(:users) }++ many :customer_groups,+ resource: Spree.api.admin_customer_group_serializer,+ if: proc { |rule| rule.respond_to?(:customer_groups) }++ many :countries,+ resource: Spree.api.admin_country_serializer,+ if: proc { |rule| rule.respond_to?(:countries) }endendenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rbindex c3c890e931..10930c356a 100644--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb@@ -12,7 +12,6 @@ module Spreeexpires_at: [:string, nullable: true],usage_limit: [:number, nullable: true],match_policy: "'all' | 'any'",- advertise: :boolean,path: [:string, nullable: true],kind: "'coupon_code' | 'automatic'",multi_codes: :boolean,@@ -24,7 +23,7 @@ module Spreeaction_ids: 'string[]',rule_ids: 'string[]'- attributes :starts_at, :expires_at, :usage_limit, :match_policy, :advertise,+ attributes :starts_at, :expires_at, :usage_limit, :match_policy,:path, :kind, :multi_codes, :number_of_codes, :code_prefix,:promotion_category_id, :metadata,created_at: :iso8601, updated_at: :iso8601diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex e2838c239d..30ba40ac6e 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -201,6 +201,13 @@ Spree::Core::Engine.add_routes doget 'promotion_actions/types', to: 'promotion_actions#types'get 'promotion_rules/types', to: 'promotion_rules#types'+ # Calculator catalog for actions that include CalculatedAdjustments+ # (CreateAdjustment, CreateItemAdjustments). Returns the registered+ # calculator subclasses for the given action type along with each+ # calculator's preference schema, so the SPA can render the picker+ # + nested calculator preferences.+ get 'promotion_actions/calculators', to: 'promotion_actions#calculators'+# Tags (autocomplete for product/order/user tag inputs)resources :tags, only: [:index]@@ -211,6 +218,9 @@ Spree::Core::Engine.add_routes doresources :store_credits, controller: 'customers/store_credits'end+ # Customer groups (segmentation; used by promotion rules + bulk customer ops)+ resources :customer_groups+# Variants (top-level, for search/autocomplete across all products)resources :variants, only: [:index, :show], concerns: :custom_fieldablediff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex ec85bf6862..0cb4188688 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -196,6 +196,7 @@ module Spreeadmin_credit_card_serializer: 'Spree::Api::V3::Admin::CreditCardSerializer',admin_store_credit_serializer: 'Spree::Api::V3::Admin::StoreCreditSerializer',admin_store_credit_category_serializer: 'Spree::Api::V3::Admin::StoreCreditCategorySerializer',+ admin_customer_group_serializer: 'Spree::Api::V3::Admin::CustomerGroupSerializer',admin_payment_source_serializer: 'Spree::Api::V3::Admin::PaymentSourceSerializer',admin_digital_link_serializer: 'Spree::Api::V3::Admin::DigitalLinkSerializer',admin_store_serializer: 'Spree::Api::V3::Admin::StoreSerializer',diff --git a/spree/core/app/models/concerns/spree/calculated_adjustments.rb b/spree/core/app/models/concerns/spree/calculated_adjustments.rbindex 1c60331c5a..776213a081 100644--- a/spree/core/app/models/concerns/spree/calculated_adjustments.rb+++ b/spree/core/app/models/concerns/spree/calculated_adjustments.rb@@ -23,6 +23,25 @@ module Spreeself.calculator = klass.new if klass && !calculator.instance_of?(klass)end+ # API v3 writer for the flat `calculator: { type:, preferences: {} }`+ # payload. Routes preferences through `set_preference` so values+ # are coerced by the typed `preferred_<name>=` setters — direct+ # assignment to the serialized hash would skip coercion.+ def assign_calculator_attributes(attrs)+ return if attrs.nil?++ attrs = attrs.to_h.with_indifferent_access+ self.calculator_type = attrs[:type] if attrs[:type].present?++ return if calculator.nil? || attrs[:preferences].blank?++ attrs[:preferences].to_h.each do |key, value|+ next unless calculator.has_preference?(key.to_sym)++ calculator.set_preference(key.to_sym, value)+ end+ end+privatedef self.model_name_without_spree_namespacediff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rbindex 230bf52e19..c60b84194e 100644--- a/spree/core/app/models/spree/promotion.rb+++ b/spree/core/app/models/spree/promotion.rb@@ -39,7 +39,8 @@ module Spreehas_many :orders, through: :order_promotions, class_name: 'Spree::Order'has_many :store_promotions, class_name: 'Spree::StorePromotion'has_many :stores, class_name: 'Spree::Store', through: :store_promotions- accepts_nested_attributes_for :promotion_actions, :promotion_rules++ after_save :apply_pending_rules_and_actions, if: :pending_rules_or_actions?## Callbacks@@ -115,6 +116,25 @@ module Spreeendend+ # Flat-payload writer for `rules`. Accepts an array of hashes like+ # `[{ type:, preferences:, product_ids:, ... }]` and reconciles to+ # the desired set: existing rows update by `id`, new rows build,+ # missing rows destroy. Falls through to AR's standard writer+ # when assigned a real array of `Spree::PromotionRule` instances+ # (Rails internals do this on association swap).+ def rules=(rules_params)+ assign_subclassed_collection(:promotion_rules, rules_params, registry: Spree.promotions.rules)+ end++ # Same shape as `rules=` for promotion actions.+ def actions=(actions_params)+ assign_subclassed_collection(:promotion_actions, actions_params, registry: Spree.promotions.actions)+ end++ def pending_rules_or_actions?+ @pending_promotion_rules.present? || @pending_promotion_actions.present?+ end+def active?starts_at.present? && starts_at < Time.current && (expires_at.blank? || !expired?)end@@ -283,6 +303,89 @@ module Spreeprivate+ def assign_subclassed_collection(association, params, registry:)+ first = Array(params).first+ return public_send(:"#{association}=", params) if first.nil? || first.is_a?(Spree.base_class)++ pending = Array(params).map { |entry| entry.respond_to?(:to_h) ? entry.to_h.with_indifferent_access : entry.with_indifferent_access }++ if new_record?+ instance_variable_set(:"@pending_#{association}", { params: pending, registry: registry })+ return+ end++ apply_subclassed_collection(association, pending, registry: registry)+ end++ def apply_pending_rules_and_actions+ if (pending = @pending_promotion_rules)+ apply_subclassed_collection(:promotion_rules, pending[:params], registry: pending[:registry])+ @pending_promotion_rules = nil+ end+ if (pending = @pending_promotion_actions)+ apply_subclassed_collection(:promotion_actions, pending[:params], registry: pending[:registry])+ @pending_promotion_actions = nil+ end+ end++ # Applied to a persisted promotion. Reconciles `association` to the+ # supplied desired-set: rows with `id:` update, rows without build,+ # rows missing from the payload are destroyed.+ def apply_subclassed_collection(association, rows, registry:)+ collection = public_send(association)+ kept_ids = []++ rows.each do |row|+ klass = registry.find { |k| k.to_s == row[:type] } if row[:type]+ klass ||= collection.find_by(id: decode_id(row[:id]))&.class++ next unless klass++ record = if row[:id].present?+ collection.find { |r| r.id == decode_id(row[:id]) } || collection.find_by(id: decode_id(row[:id]))+ else+ collection.build(type: klass.to_s)+ end++ next unless record++ # Promote to the right STI subclass when building new (collection.build+ # uses the declared class_name, which is the parent).+ record = record.becomes(klass) if record.class != klass+ assign_subclass_attributes(record, row)+ record.save! if record.changed? || record.new_record?+ kept_ids << record.id+ end++ collection.where.not(id: kept_ids).destroy_all if kept_ids.any? || rows.empty?+ end++ def assign_subclass_attributes(record, row)+ preferences = row.delete(:preferences)+ calculator = row.delete(:calculator)+ row.delete(:type)+ row.delete(:id)++ record.assign_attributes(row) if row.any?++ if preferences.present?+ preferences.to_h.each do |key, value|+ next unless record.has_preference?(key.to_sym)++ record.set_preference(key.to_sym, value)+ end+ end++ record.assign_calculator_attributes(calculator) if calculator.present? && record.respond_to?(:assign_calculator_attributes)+ end++ def decode_id(value)+ return nil if value.blank?+ return value.to_i if value.is_a?(Integer) || value.to_s.match?(/\A\d+\z/)++ Spree::PrefixedId.decode_prefixed_id(value)+ end+def not_used?return true if orders.empty?diff --git a/spree/core/app/models/spree/promotion/actions/create_adjustment.rb b/spree/core/app/models/spree/promotion/actions/create_adjustment.rbindex 194888530a..bbfe066390 100644--- a/spree/core/app/models/spree/promotion/actions/create_adjustment.rb+++ b/spree/core/app/models/spree/promotion/actions/create_adjustment.rb@@ -7,6 +7,10 @@ module Spreebefore_validation -> { self.calculator ||= Calculator::FlatPercentItemTotal.new }+ def self.additional_permitted_attributes+ [calculator: [:type, { preferences: {} }]]+ end+def perform(options = {})order = options[:order]diff --git a/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb b/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rbindex b572e49109..62a5e438c1 100644--- a/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb+++ b/spree/core/app/models/spree/promotion/actions/create_item_adjustments.rb@@ -7,6 +7,10 @@ module Spreebefore_validation -> { self.calculator ||= Calculator::PercentOnLineItem.new }+ def self.additional_permitted_attributes+ [calculator: [:type, { preferences: {} }]]+ end+def perform(options = {})order = options[:order]promotion = options[:promotion]diff --git a/spree/core/app/models/spree/promotion/actions/create_line_items.rb b/spree/core/app/models/spree/promotion/actions/create_line_items.rbindex f1dc755c2f..d1698e1195 100644--- a/spree/core/app/models/spree/promotion/actions/create_line_items.rb+++ b/spree/core/app/models/spree/promotion/actions/create_line_items.rb@@ -8,6 +8,17 @@ module Spreeafter_save :handle_promotion_action_line_items+ def self.additional_permitted_attributes+ [line_items: [:variant_id, :quantity]]+ end++ # API v3 flat alias for `promotion_action_line_items_attributes`.+ # Accepts an array of `{ variant_id:, quantity: }` rows; the list+ # is the *desired* set, so anything missing on save is removed.+ def line_items=(rows)+ self.promotion_action_line_items_attributes = rows+ end+delegate :eligible?, to: :promotion# Adds a line item to the Order if the promotion is eligible@@ -85,29 +96,36 @@ module Spreeprivate- # Handles the creation and updating of promotion action line items- #- # This is a hacky replacement for accepts_nested_attributes_for- # that allows us to save the PromotionAction and PromotionActionLineItems- # at the same time.+ # Handles the creation, updating, and pruning of promotion action+ # line items. The submitted list is the *desired* set — variants+ # not present are deleted, ones that are get upserted. Accepts+ # both the legacy Rails admin hash shape (`{ "0" => attrs }`) and+ # a flat array from the API. Variant IDs may be raw or prefixed.def handle_promotion_action_line_itemsreturn unless promotion_action_line_items_attributes- # remove the ones marked for destruction- ids_for_destruction = promotion_action_line_items_attributes.map { |key, params| params["_destroy"] == "1" ? params["id"] : nil }.compact- promotion_action_line_items.where(id: ids_for_destruction).delete_all if ids_for_destruction.present?+ rows = promotion_action_line_items_attributes.is_a?(Hash) ? promotion_action_line_items_attributes.values : promotion_action_line_items_attributes+ rows = rows.map { |row| row.respond_to?(:to_h) ? row.to_h.with_indifferent_access : row.with_indifferent_access }++ rows = rows.map do |row|+ variant_id = row['variant_id']+ variant_id = Spree::Variant.find_by_param(variant_id)&.id if Spree::PrefixedId.prefixed_id?(variant_id)+ row.merge('variant_id' => variant_id)+ end++ desired_variant_ids = rows.map { |row| row['variant_id'] }.compact+ promotion_action_line_items.where.not(variant_id: desired_variant_ids).delete_all- # upsert the rest- records_for_upsert = promotion_action_line_items_attributes.map { |key, params| params["_destroy"] != "1" ? params : nil }.compact+ return if rows.empty?opts = {}opts[:unique_by] = [:promotion_action_id, :variant_id] unless ActiveRecord::Base.connection.adapter_name == 'Mysql2'promotion_action_line_items.upsert_all(- records_for_upsert.map do |params|+ rows.map do |params|{- variant_id: params["variant_id"],- quantity: params["quantity"],+ variant_id: params['variant_id'],+ quantity: params['quantity'],promotion_action_id: id}end,diff --git a/spree/core/app/models/spree/promotion/rules/country.rb b/spree/core/app/models/spree/promotion/rules/country.rbindex de100fca8e..e2654e2e21 100644--- a/spree/core/app/models/spree/promotion/rules/country.rb+++ b/spree/core/app/models/spree/promotion/rules/country.rb@@ -1,39 +1,61 @@-# A rule to limit a promotion based on shipment country.+# A rule to limit a promotion based on shipment country. Stores an+# array of ISO codes — countries are inherently identified by ISO+# in the API. The legacy single `country_id` / `country_iso`+# preferences still work; they fold into the multi-country list.module Spreeclass Promotionmodule Rulesclass Country < PromotionRule- preference :country_id, :integer- preference :country_iso, :string # Alternative way to configure the rule+ preference :country_isos, :array, default: [], parse_on_set: lambda { |values|+ normalize_id_preference.call(values).map(&:upcase)+ }+ preference :country_id, :integer # legacy single-country shortcut+ preference :country_iso, :string # legacy ISO-based shortcutdef applicable?(promotable)promotable.is_a?(Spree::Order)end- def eligible?(order, options = {})- if preferred_country_iso.present?- validate_eligibility_by_country_iso(order)- else- validate_eligibility_by_country_id(order, options)- end+ def countries+ isos = preferred_country_isos.presence || [preferred_country_iso].compact_blank+ return Spree::Country.none if isos.blank?++ Spree::Country.where(iso: isos.map { |s| s.to_s.upcase })end- private+ def eligible?(order, options = {})+ allowed_isos = eligible_country_isos(order)+ shipping_iso = options[:country_iso] || order.ship_address&.country_iso- def validate_eligibility_by_country_id(order, options)- country_id = options[:country_id] || order.ship_address.try(:country_id)- return true if country_id == (preferred_country_id || order.store.default_country_id)+ return true if allowed_isos.include?(shipping_iso)eligibility_errors.add(:base, eligibility_error_message(:wrong_country))falseend- def validate_eligibility_by_country_iso(order)- country_iso = order.ship_address&.country_iso- return true if country_iso == (preferred_country_iso || order.store.default_market&.default_country&.iso)+ # Effective list of eligible country ISOs, merging legacy+ # single-country preferences into the multi-country list.+ # Order-of-precedence: explicit ISO list > legacy single ISO+ # > legacy single ID > store default. Memoized per-instance —+ # eligibility checks fire repeatedly per cart change.+ def eligible_country_isos(order = nil)+ @eligible_country_isos ||= compute_eligible_country_isos(order)+ end- eligibility_errors.add(:base, eligibility_error_message(:wrong_country))- false+ private++ def compute_eligible_country_isos(order)+ return preferred_country_isos.map { |v| v.to_s.upcase } if preferred_country_isos.present?+ return [preferred_country_iso.to_s.upcase] if preferred_country_iso.present?++ if preferred_country_id.present?+ iso = Spree::Country.where(id: preferred_country_id).pick(:iso)+ return [iso.to_s.upcase] if iso.present?+ end++ return [] if order.nil?++ [order.store&.default_country&.iso, order.store&.default_market&.default_country&.iso].compact.map(&:upcase).uniqendendenddiff --git a/spree/core/app/models/spree/promotion/rules/customer_group.rb b/spree/core/app/models/spree/promotion/rules/customer_group.rbindex 1693cd33ed..b25cd191b1 100644--- a/spree/core/app/models/spree/promotion/rules/customer_group.rb+++ b/spree/core/app/models/spree/promotion/rules/customer_group.rb@@ -2,12 +2,21 @@ module Spreeclass Promotionmodule Rulesclass CustomerGroup < PromotionRule- 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 can+ # compare against raw `customer_group_id` rows directly.+ preference :customer_group_ids, :array, default: [], parse_on_set: normalize_id_preference(klass: Spree::CustomerGroup)def applicable?(promotable)promotable.is_a?(Spree::Order)end+ def customer_groups+ return Spree::CustomerGroup.none if preferred_customer_group_ids.blank?++ Spree::CustomerGroup.where(id: preferred_customer_group_ids)+ end+def eligible?(order, _options = {})return false unless order.user_id.present?return false if preferred_customer_group_ids.empty?diff --git a/spree/core/app/models/spree/promotion/rules/product.rb b/spree/core/app/models/spree/promotion/rules/product.rbindex e74443a690..5f854828d1 100644--- a/spree/core/app/models/spree/promotion/rules/product.rb+++ b/spree/core/app/models/spree/promotion/rules/product.rb@@ -13,6 +13,10 @@ module Spreedependent: :destroyhas_many :products, through: :product_promotion_rules, class_name: 'Spree::Product'+ def self.additional_permitted_attributes+ [product_ids: []]+ end+## Preferences#diff --git a/spree/core/app/models/spree/promotion/rules/taxon.rb b/spree/core/app/models/spree/promotion/rules/taxon.rbindex c07f6ede5d..f3922e3df5 100644--- a/spree/core/app/models/spree/promotion/rules/taxon.rb+++ b/spree/core/app/models/spree/promotion/rules/taxon.rb@@ -10,6 +10,28 @@ module Spreedependent: :destroyhas_many :taxons, through: :promotion_rule_taxons, class_name: 'Spree::Taxon'+ def self.additional_permitted_attributes+ [category_ids: []]+ end++ # API key is `category` (model is still `Taxon` pre-table-rename).+ def key+ 'category'+ end++ # PrefixedId's auto-resolver in `assign_attributes` only fires+ # when the `_ids` stem matches an association — `categories`+ # doesn't, so decode prefixed IDs explicitly here.+ def category_ids=(ids)+ self.taxon_ids = Array(ids).map do |id|+ Spree::PrefixedId.prefixed_id?(id) ? Spree::Taxon.find_by_param!(id).id : id+ end+ end++ def category_ids+ taxon_ids+ end+## Preferences#diff --git a/spree/core/app/models/spree/promotion/rules/user.rb b/spree/core/app/models/spree/promotion/rules/user.rbindex aca7829142..70f7070427 100644--- a/spree/core/app/models/spree/promotion/rules/user.rb+++ b/spree/core/app/models/spree/promotion/rules/user.rb@@ -10,6 +10,10 @@ module Spreedependent: :destroyhas_many :users, through: :promotion_rule_users, class_name: "::#{Spree.user_class}"+ def self.additional_permitted_attributes+ [user_ids: []]+ end+## Attributes#diff --git a/spree/core/app/models/spree/promotion_action.rb b/spree/core/app/models/spree/promotion_action.rbindex 6d70b58f5c..afb7cc55cb 100644--- a/spree/core/app/models/spree/promotion_action.rb+++ b/spree/core/app/models/spree/promotion_action.rb@@ -14,6 +14,15 @@ module Spreescope :of_type, ->(t) { where(type: t) }+ # Per-subclass permitted attributes beyond `type` and `preferences`.+ # Override in STI subclasses that accept nested attributes (e.g.+ # CreateLineItems needs `promotion_action_line_items_attributes`,+ # CreateAdjustment needs `calculator_type` + `calculator_attributes`).+ # The Admin API merges these into its `params.permit(...)` allowlist.+ def self.additional_permitted_attributes+ []+ end+# This method should be overridden in subclass# Updates the state of the order or performs some other action depending on the subclass# options will contain the payload from the event that activated the promotion. This will includediff --git a/spree/core/app/models/spree/promotion_rule.rb b/spree/core/app/models/spree/promotion_rule.rbindex 54a5c9a82f..1ae84d2164 100644--- a/spree/core/app/models/spree/promotion_rule.rb+++ b/spree/core/app/models/spree/promotion_rule.rb@@ -14,6 +14,35 @@ module Spreevalidates :promotion, presence: truevalidate :unique_per_promotion, on: :create+ # Per-subclass permitted attributes beyond `type` and `preferences`.+ # Override in STI subclasses that accept association IDs (e.g.+ # Rules::Product needs `product_ids`). The Admin API merges these+ # into its `params.permit(...)` allowlist.+ def self.additional_permitted_attributes+ []+ 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) }enddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 6243f91381..2003118694 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1910,9 +1910,9 @@ en:product:description: Order includes specified product(s)name: Product(s)- taxon:- description: Order includes products with specified taxon(s)- name: Taxon(s)+ category:+ description: Order includes products in specified category(ies)+ name: Category(ies)user:description: Available only to the specified customersname: Userdiff --git a/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb b/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rbindex 4153475298..9b097bdfa4 100644--- a/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb+++ b/spree/core/spec/models/spree/promotion/actions/create_line_items_spec.rb@@ -105,31 +105,34 @@ describe Spree::Promotion::Actions::CreateLineItems, type: :model docontext 'with existing promotion action line items' dobefore doaction.save!- # Change quantity for existing item+ # Submit the full desired set — both rows present, shirt's quantity bumped.action.promotion_action_line_items_attributes = {- '0' => { 'variant_id' => shirt.id, 'quantity' => 3 }+ '0' => { 'variant_id' => shirt.id, 'quantity' => 3 },+ '1' => { 'variant_id' => mug.id, 'quantity' => 2 }}end- it 'updates existing promotion action line items' do+ it 'updates existing promotion action line items in place' doexpect { action.save! }.not_to change(action.promotion_action_line_items, :count)expect(action.promotion_action_line_items.find_by(variant_id: shirt.id).quantity).to eq(3)expect(action.promotion_action_line_items.find_by(variant_id: mug.id).quantity).to eq(2)endend- context 'with items marked for destruction' do+ context 'with rows omitted from the desired set' dobefore doaction.save!+ # Omitting `mug` from the submitted set deletes it; the list is+ # the desired state, not a diff. Mirrors the API v3 flat payload.action.promotion_action_line_items_attributes = {- '0' => { 'id' => action.promotion_action_line_items.find_by(variant_id: shirt.id).id, '_destroy' => '1' }+ '0' => { 'variant_id' => shirt.id, 'quantity' => 1 }}end- it 'removes items marked for destruction' do+ it 'removes the omitted rows' doexpect { action.save! }.to change(action.promotion_action_line_items, :count).by(-1)- expect(action.promotion_action_line_items.find_by(variant_id: shirt.id)).to be_nil- expect(action.promotion_action_line_items.find_by(variant_id: mug.id)).to be_present+ expect(action.promotion_action_line_items.find_by(variant_id: shirt.id)).to be_present+ expect(action.promotion_action_line_items.find_by(variant_id: mug.id)).to be_nilendendend