Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: Keep the configured calculator when editing promotion actions (#14608)
Damian Legawiec76e5757490c4
diff --git a/packages/admin-sdk/tests/promotions.test.ts b/packages/admin-sdk/tests/promotions.test.tsindex 1872e864ed..045ce95111 100644--- a/packages/admin-sdk/tests/promotions.test.ts+++ b/packages/admin-sdk/tests/promotions.test.ts@@ -271,7 +271,7 @@ describe('promotionActions', () => {http.get(`${API_PREFIX}/promotion_actions/calculators`, ({ request }) => {url = new URL(request.url)return HttpResponse.json({- data: [{ type: 'Spree::Calculator::FlatRate', label: 'Flat Rate' }],+ data: [{ type: 'flat_rate', label: 'Flat Rate' }],})}),)@@ -281,7 +281,7 @@ describe('promotionActions', () => {)expect(url!.searchParams.get('type')).toBe('Spree::Promotion::Actions::CreateItemAdjustments')- expect(res.data[0]?.type).toBe('Spree::Calculator::FlatRate')+ expect(res.data[0]?.type).toBe('flat_rate')})})})diff --git a/packages/dashboard/e2e/promotions.spec.ts b/packages/dashboard/e2e/promotions.spec.tsindex 2cd2e06eb9..ddcb02d6eb 100644--- a/packages/dashboard/e2e/promotions.spec.ts+++ b/packages/dashboard/e2e/promotions.spec.ts@@ -317,6 +317,39 @@ test.describe('promotions', () => {await expect(page.getByText(/currency:\s*USD/i).first()).toBeVisible({ timeout: 5_000 })})+ test('reopens a Create Adjustment action on the configured calculator', async ({ page }) => {+ const creds = await login(page)+ await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)++ const name = `E2E Adjustment Edit ${Date.now()}`+ await startNewPromotion(page, creds.store_id, name)++ await pickAction(page, /^create whole-order adjustment\b/i)+ await expect(+ page.getByRole('heading', { name: /^create whole-order adjustment$/i }),+ ).toBeVisible({ timeout: 5_000 })++ const calculatorSelect = page.locator('#calculator-type')+ await expect(calculatorSelect).toBeEnabled({ timeout: 10_000 })+ await calculatorSelect.click()+ await page.getByRole('option', { name: /^flat rate$/i }).click()+ await saveEditor(page)++ await submitCreate(page, name)++ await page+ .locator('div.items-stretch')+ .filter({ hasText: /create whole-order adjustment/i })+ .first()+ .getByRole('button')+ .first()+ .click()+ await expect(+ page.getByRole('heading', { name: /^create whole-order adjustment$/i }),+ ).toBeVisible({ timeout: 5_000 })+ await expect(calculatorSelect).toContainText(/flat rate/i, { timeout: 10_000 })+ })+test('creates a promotion with a Create Adjustment action', async ({ page }) => {const creds = await login(page)await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)diff --git a/packages/dashboard/src/components/spree/promotion-editors/action-adjustment.tsx b/packages/dashboard/src/components/spree/promotion-editors/action-adjustment.tsxindex 42b0d69ef6..ee06de88c6 100644--- a/packages/dashboard/src/components/spree/promotion-editors/action-adjustment.tsx+++ b/packages/dashboard/src/components/spree/promotion-editors/action-adjustment.tsx@@ -14,6 +14,8 @@ import { useQuery } from '@tanstack/react-query'import { useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'+import { resolveCalculatorType } from '../../../lib/promotion-calculator-type'+import { EditorShell } from './editor-shell'import type { PromotionActionEditorContext } from './types'@@ -36,14 +38,18 @@ export function AdjustmentActionEditor({ draft, onSave, onClose }: PromotionActi() => 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.+ // Once the catalog arrives, reconcile the draft's calculator against the+ // list. Accepts api shorthand or legacy full class names, and only falls+ // back to the first entry for a new action or a calculator that no longer+ // exists. Runs when the catalog loads — not on every picker change.useEffect(() => {if (calculators.length === 0) return- const matches = calculators.some((c) => c.type === calculatorType)- if (!matches) setCalculatorType(calculators[0].type)- }, [calculators, calculatorType])++ setCalculatorType((current) => {+ const resolved = resolveCalculatorType(calculators, current)+ return resolved ?? calculators[0].type+ })+ }, [calculators])const selectedCalculator: PromotionActionCalculator | undefined = useMemo(() => calculators.find((c) => c.type === calculatorType),diff --git a/packages/dashboard/src/lib/promotion-calculator-type.test.ts b/packages/dashboard/src/lib/promotion-calculator-type.test.tsnew file mode 100644index 0000000000..06dbc823d2--- /dev/null+++ b/packages/dashboard/src/lib/promotion-calculator-type.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest'++import { normalizeCalculatorType, resolveCalculatorType } from './promotion-calculator-type'++const catalog = [{ type: 'flat_percent_item_total' }, { type: 'flat_rate' }, { type: 'flexi_rate' }]++describe('normalizeCalculatorType', () => {+ it('passes through api shorthand unchanged', () => {+ expect(normalizeCalculatorType('flat_rate')).toBe('flat_rate')+ })++ it('derives api shorthand from a Ruby class name', () => {+ expect(normalizeCalculatorType('Spree::Calculator::FlatRate')).toBe('flat_rate')+ expect(normalizeCalculatorType('Spree::Calculator::FlatPercentItemTotal')).toBe(+ 'flat_percent_item_total',+ )+ })+})++describe('resolveCalculatorType', () => {+ it('matches catalog entries by api shorthand', () => {+ expect(resolveCalculatorType(catalog, 'flat_rate')).toBe('flat_rate')+ })++ it('matches catalog entries when the draft carries a Ruby class name', () => {+ expect(resolveCalculatorType(catalog, 'Spree::Calculator::FlatRate')).toBe('flat_rate')+ })++ it('returns undefined when nothing matches', () => {+ expect(resolveCalculatorType(catalog, 'Spree::Calculator::Gone')).toBeUndefined()+ })+})diff --git a/packages/dashboard/src/lib/promotion-calculator-type.ts b/packages/dashboard/src/lib/promotion-calculator-type.tsnew file mode 100644index 0000000000..c3fa7957da--- /dev/null+++ b/packages/dashboard/src/lib/promotion-calculator-type.ts@@ -0,0 +1,34 @@+/**+ * Resolves a draft calculator `type` against the catalog returned by+ * `GET /promotion_actions/calculators`. The promotion action payload uses+ * api shorthand (`flat_rate`) while older catalog responses used the full+ * Ruby class name (`Spree::Calculator::FlatRate`).+ */+export function resolveCalculatorType(+ calculators: ReadonlyArray<{ type: string }>,+ type: string,+): string | undefined {+ if (!type) return undefined++ const normalized = normalizeCalculatorType(type)++ return calculators.find((calculator) => {+ const catalogType = calculator.type+ return (+ catalogType === type ||+ catalogType === normalized ||+ normalizeCalculatorType(catalogType) === normalized+ )+ })?.type+}++/** Mirrors `Spree::Base.api_type`: demodulize + underscore. */+export function normalizeCalculatorType(type: string): string {+ if (!type.includes('::')) return type++ const leaf = type.split('::').pop() ?? type+ return leaf+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')+ .toLowerCase()+}diff --git a/spree/api/spec/controllers/spree/api/v3/admin/promotion_actions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/promotion_actions_controller_spec.rbindex e8d6c997c1..0893c76f11 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/promotion_actions_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/promotion_actions_controller_spec.rb@@ -44,4 +44,15 @@ RSpec.describe Spree::Api::V3::Admin::PromotionActionsController, type: :controlexpect(response).to have_http_status(:not_found)endend++ describe 'GET #calculators' do+ it 'returns calculator api types that match the action serializer' do+ get :calculators, params: { type: 'create_adjustment' }, as: :json++ expect(response).to have_http_status(:ok)+ types = json_response['data'].map { |entry| entry['type'] }+ expect(types).to include('flat_rate')+ expect(types).not_to include('Spree::Calculator::FlatRate')+ end+ endend