Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Keep a catalog's quantity price ladder unless it was edited (#14820)

Damian Legawiecd95454d00e4e
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
index b449447904..4d0ab2d3eb 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx
@@ -120,10 +120,12 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
const canEdit = permissions.can('update', Subject.Catalog)
- // The mode as last saved, not as currently selected: switching away from
- // hand-entered prices has to clear them, and the warning has to know a
- // switch is what is about to happen.
- const savedPricingMode = catalogPricingValues(catalog.price_list).pricing_mode
+ // The pricing as last saved, not as currently selected: switching away from
+ // hand-entered prices has to clear them, and an untouched ladder must not
+ // be resent. Advanced on every successful save rather than only when the
+ // refetch lands, so a second save made before it arrives is not compared
+ // against a ladder the server no longer holds.
+ const [savedPricing, setSavedPricing] = useState(() => catalogPricingValues(catalog.price_list))
// Owned here so the pricing card and the assortment rows open the same
// spreadsheet — pricing an assortment is an action on those rows too.
const [priceEditorOpen, setPriceEditorOpen] = useState(false)
@@ -144,6 +146,8 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
// catalog mid-edit, and an unguarded reset would drop both the settings
// being typed and any staged product changes.
useEffect(() => {
+ const loadedPricing = catalogPricingValues(catalog.price_list)
+ setSavedPricing(loadedPricing)
if (form.formState.isDirty) return
form.reset({
name: catalog.name,
@@ -161,7 +165,7 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
currency: minimum.currency,
amount: minimum.amount,
})),
- ...catalogPricingValues(catalog.price_list),
+ ...loadedPricing,
staged_products: { adds: [], removes: [] },
// Not seeded from the server: terms arrive on the assortment rows, a
// page at a time, so the form holds only what the merchant edits. A
@@ -225,11 +229,19 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {
)
await saveMutation.mutateAsync({
- attributes: { ...catalogValuesToParams(values, savedPricingMode), ...extensionValues },
+ attributes: { ...catalogValuesToParams(values, savedPricing), ...extensionValues },
addProductIds: values.staged_products.adds.map((product) => product.id),
removeProductIds: values.staged_products.removes,
quantityRules: stagedTermsToParams(terms),
})
+ setSavedPricing({
+ pricing_mode: values.pricing_mode,
+ adjustment_direction: values.adjustment_direction,
+ adjustment_magnitude: values.adjustment_magnitude ?? '',
+ adjust_compare_at: values.adjust_compare_at,
+ minimum_quantity: values.minimum_quantity ?? '',
+ adjustment_tiers: values.adjustment_tiers,
+ })
form.reset({ ...values, ...extensionValues, staged_products: { adds: [], removes: [] } })
} catch (err) {
if (!mapSpreeErrorsToForm(err, form.setError)) throw err
diff --git a/packages/dashboard/src/schemas/catalog.test.ts b/packages/dashboard/src/schemas/catalog.test.ts
new file mode 100644
index 0000000000..563328bcb6
--- /dev/null
+++ b/packages/dashboard/src/schemas/catalog.test.ts
@@ -0,0 +1,115 @@
+import type { PriceList } from '@spree/admin-sdk'
+import { describe, expect, it } from 'vitest'
+import {
+ CATALOG_DEFAULTS,
+ type CatalogFormValues,
+ catalogPricingValues,
+ catalogValuesToParams,
+} from './catalog'
+
+type OwnedList = Pick<
+ PriceList,
+ 'price_adjustment_percentage' | 'adjust_compare_at' | 'price_rules' | 'price_adjustment_tiers'
+>
+
+// A discount from ten units and a markup from fifty — a ladder the Admin API
+// accepts but the form's single direction control cannot express.
+const MIXED_SIGN_TIERS = [
+ { min_quantity: 10, percentage: '-10.0' },
+ { min_quantity: 50, percentage: '5.0' },
+] as OwnedList['price_adjustment_tiers']
+
+function ownedList(overrides: Partial<OwnedList> = {}): OwnedList {
+ return {
+ price_adjustment_percentage: null,
+ adjust_compare_at: false,
+ price_rules: [],
+ price_adjustment_tiers: MIXED_SIGN_TIERS,
+ ...overrides,
+ } as OwnedList
+}
+
+function loadedForm(list: OwnedList) {
+ const loaded = catalogPricingValues(list)
+ const values: CatalogFormValues = { ...CATALOG_DEFAULTS, name: 'Wholesale', ...loaded }
+ return { loaded, values }
+}
+
+describe('catalogValuesToParams', () => {
+ it('leaves a mixed-sign ladder alone when only the name changes', () => {
+ const { loaded, values } = loadedForm(ownedList())
+
+ const params = catalogValuesToParams({ ...values, name: 'Wholesale 2027' }, loaded)
+
+ expect(params.name).toBe('Wholesale 2027')
+ expect(params.price_list).not.toHaveProperty('price_adjustment_tiers')
+ })
+
+ it('leaves the ladder alone beside a percentage of its own', () => {
+ const { loaded, values } = loadedForm(ownedList({ price_adjustment_percentage: '-5.0' }))
+
+ const params = catalogValuesToParams({ ...values, name: 'Renamed' }, loaded)
+
+ expect(params.price_list).toMatchObject({ price_adjustment_percentage: '-5' })
+ expect(params.price_list).not.toHaveProperty('price_adjustment_tiers')
+ })
+
+ it('sends the whole ladder once a band is edited', () => {
+ const { loaded, values } = loadedForm(ownedList())
+
+ const params = catalogValuesToParams(
+ {
+ ...values,
+ adjustment_tiers: [
+ { min_quantity: '10', percentage: '15' },
+ { min_quantity: '50', percentage: '5' },
+ ],
+ },
+ loaded,
+ )
+
+ expect(params.price_list).toMatchObject({
+ price_adjustment_tiers: [
+ { min_quantity: 10, percentage: '-15' },
+ { min_quantity: 50, percentage: '-5' },
+ ],
+ })
+ })
+
+ it('sends the whole ladder once the direction is flipped', () => {
+ const { loaded, values } = loadedForm(ownedList())
+
+ const params = catalogValuesToParams({ ...values, adjustment_direction: 'increase' }, loaded)
+
+ expect(params.price_list).toMatchObject({
+ price_adjustment_tiers: [
+ { min_quantity: 10, percentage: '10' },
+ { min_quantity: 50, percentage: '5' },
+ ],
+ })
+ })
+
+ it('still clears the ladder when switching to fixed prices', () => {
+ const { loaded, values } = loadedForm(ownedList())
+
+ const params = catalogValuesToParams({ ...values, pricing_mode: 'fixed' }, loaded)
+
+ expect(params.price_list).toMatchObject({
+ price_adjustment_percentage: null,
+ price_adjustment_tiers: [],
+ })
+ })
+
+ it('sends the ladder when there is nothing loaded to compare against', () => {
+ const { values } = loadedForm(ownedList())
+
+ const params = catalogValuesToParams(values)
+
+ expect(params.price_list).toMatchObject({
+ price_adjustment_tiers: [
+ { min_quantity: 10, percentage: '-10' },
+ { min_quantity: 50, percentage: '-5' },
+ ],
+ })
+ })
+})
diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.ts
index 26e7584712..5da40d0193 100644
--- a/packages/dashboard/src/schemas/catalog.ts
+++ b/packages/dashboard/src/schemas/catalog.ts
@@ -252,11 +252,16 @@ export const CATALOG_DEFAULTS: CatalogFormValues = {
* an object stands the list up or updates it, and an explicit null detaches
* — which is a deliberate act, since a released list starts matching by its
* own rules again.
+ *
+ * @param values the form values being saved
+ * @param loaded the pricing as last loaded from the catalog's owned list
+ * (`catalogPricingValues`), so a mode switch can be told from a plain save
+ * and an untouched ladder is left alone. Absent on create.
+ * @return the catalog create/update payload
*/
export function catalogValuesToParams(
values: CatalogFormValues,
- /** The mode the catalog was saved in, so a switch can be told from a plain save. */
- previousMode?: CatalogPricingMode,
+ loaded?: CatalogPricingValues,
): CatalogParams {
return {
name: values.name,
@@ -282,11 +287,11 @@ export function catalogValuesToParams(
currency: row.currency,
amount: row.amount,
})),
- price_list: priceListPayload(values, previousMode),
+ price_list: priceListPayload(values, loaded),
}
}
-function priceListPayload(values: CatalogFormValues, previousMode?: CatalogPricingMode) {
+function priceListPayload(values: CatalogFormValues, loaded?: CatalogPricingValues) {
if (values.pricing_mode === 'base') return null
if (values.pricing_mode === 'fixed') {
@@ -323,21 +328,42 @@ function priceListPayload(values: CatalogFormValues, previousMode?: CatalogPrici
// A minimum quantity rides as the list's volume rule; dropping it from the
// list of rules is what clears it, so removing the threshold is a real
// edit rather than a silent no-op.
+ // The payload is the whole ladder, so a band the merchant deleted is a
+ // band absent from this array rather than one marked for removal.
+ const tiers = adjustmentTiersPayload(values.adjustment_tiers, values.adjustment_direction)
const withRule = {
...base,
rules: volumeRulePayload(values.minimum_quantity),
- // The payload is the whole ladder, so a band the merchant deleted is a
- // band absent from this array rather than one marked for removal.
- price_adjustment_tiers: adjustmentTiersPayload(
- values.adjustment_tiers,
- values.adjustment_direction,
- ),
+ // Left out when untouched: the form reads every band through one
+ // direction, so a ladder the API holds with mixed signs would come back
+ // with its markups turned into discounts on an unrelated save.
+ ...(ladderUnchanged(tiers, loaded) ? {} : { price_adjustment_tiers: tiers }),
}
// Switching away from hand-entered prices clears them. An explicit amount
// beats the adjustment by design, so leaving the old rows behind would
// keep charging them while the card claims a percentage is in effect.
- return previousMode === 'fixed' ? { ...withRule, prices: [] } : withRule
+ return loaded?.pricing_mode === 'fixed' ? { ...withRule, prices: [] } : withRule
+}
+
+// Compared as payloads, so the direction is part of the comparison: flipping
+// it re-signs every band and is an edit, as is any band added, removed or
+// retyped.
+function ladderUnchanged(
+ tiers: ReturnType<typeof adjustmentTiersPayload>,
+ loaded: CatalogPricingValues | undefined,
+): boolean {
+ if (loaded?.pricing_mode !== 'automatic') return false
+
+ const loadedTiers = adjustmentTiersPayload(loaded.adjustment_tiers, loaded.adjustment_direction)
+ return (
+ tiers.length === loadedTiers.length &&
+ tiers.every(
+ (tier, index) =>
+ tier.min_quantity === loadedTiers[index].min_quantity &&
+ tier.percentage === loadedTiers[index].percentage,
+ )
+ )
}
/**
@@ -393,6 +419,16 @@ function volumeRulePayload(minimumQuantity: string | undefined) {
return [{ type: 'volume_rule', preferences: { min_quantity: quantity } }]
}
+/** The pricing fields of the catalog form, as read off its owned list. */
+export interface CatalogPricingValues {
+ pricing_mode: CatalogPricingMode
+ adjustment_direction: CatalogFormValues['adjustment_direction']
+ adjustment_magnitude: string
+ adjust_compare_at: boolean
+ minimum_quantity: string
+ adjustment_tiers: AdjustmentTierValue[]
+}
+
/**
* Splits a catalog's owned list back into the edited fields. No list means
* the catalog prices at base.
@@ -408,14 +444,7 @@ export function catalogPricingValues(
>
| null
| undefined,
-): {
- pricing_mode: CatalogPricingMode
- adjustment_direction: CatalogFormValues['adjustment_direction']
- adjustment_magnitude: string
- adjust_compare_at: boolean
- minimum_quantity: string
- adjustment_tiers: AdjustmentTierValue[]
-} {
+): CatalogPricingValues {
if (!priceList) {
return {
pricing_mode: 'base',