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
Read catalog quantity rules off the assortment rows
Damian Legawiec0f8e5c84c20d
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex 7dce77ac96..00225030d5 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -11566,7 +11566,7 @@ paths:example:data:- id: opt_UkLWZg9DAJ- name: foo-size-7+ name: foo-size-1label: Sizeposition: 1kind: dropdown@@ -11790,7 +11790,7 @@ paths:application/json:example:id: opt_UkLWZg9DAJ- name: foo-size-11+ name: foo-size-5label: Sizeposition: 1kind: dropdown@@ -11864,7 +11864,7 @@ paths:application/json:example:id: opt_UkLWZg9DAJ- name: foo-size-13+ name: foo-size-7label: Updated Labelposition: 1kind: dropdown@@ -12575,11 +12575,11 @@ paths:option_values:- id: optval_UkLWZg9DAJoption_type_id: opt_UkLWZg9DAJ- name: size-7+ name: size-1label: Sposition: 1color_code:- option_type_name: foo-size-16+ option_type_name: foo-size-10option_type_label: Sizeimage_url:metadata: {}@@ -12688,11 +12688,11 @@ paths:option_values:- id: optval_gbHJdmfrXBoption_type_id: opt_gbHJdmfrXB- name: size-9+ name: size-3label: Sposition: 1color_code:- option_type_name: foo-size-18+ option_type_name: foo-size-12option_type_label: Sizeimage_url:metadata: {}@@ -12823,11 +12823,11 @@ paths:option_values:- id: optval_UkLWZg9DAJoption_type_id: opt_UkLWZg9DAJ- name: size-10+ name: size-4label: Sposition: 1color_code:- option_type_name: foo-size-19+ option_type_name: foo-size-13option_type_label: Sizeimage_url:metadata: {}@@ -12931,11 +12931,11 @@ paths:option_values:- id: optval_UkLWZg9DAJoption_type_id: opt_UkLWZg9DAJ- name: size-11+ name: size-5label: Sposition: 1color_code:- option_type_name: foo-size-20+ option_type_name: foo-size-14option_type_label: Sizeimage_url:metadata: {}@@ -25837,11 +25837,11 @@ paths:option_values:- id: optval_UkLWZg9DAJoption_type_id: opt_UkLWZg9DAJ- name: size-31+ name: size-25label: Sposition: 1color_code:- option_type_name: foo-size-40+ option_type_name: foo-size-34option_type_label: Sizeimage_url:metadata: {}@@ -26224,11 +26224,11 @@ paths:option_values:- id: optval_UkLWZg9DAJoption_type_id: opt_UkLWZg9DAJ- name: size-34+ name: size-28label: Sposition: 1color_code:- option_type_name: foo-size-43+ option_type_name: foo-size-37option_type_label: Sizeimage_url:metadata: {}@@ -26360,11 +26360,11 @@ paths:option_values:- id: optval_UkLWZg9DAJoption_type_id: opt_UkLWZg9DAJ- name: size-36+ name: size-30label: Sposition: 1color_code:- option_type_name: foo-size-45+ option_type_name: foo-size-39option_type_label: Sizeimage_url:metadata: {}@@ -27997,138 +27997,6 @@ paths:- prod_abc123required:- product_ids- "/api/v3/admin/catalogs/{catalog_id}/quantity_rules":- get:- summary: List catalog quantity rules- tags:- - Catalogs- security:- - api_key: []- bearer_auth: []- description: |-- The catalog's per-variant quantity terms. The catalog-wide default is a pair of fields on the catalog itself, so these are strictly the overrides.-- **Required scope:** `read_products` (for API-key authentication).- parameters:- - name: x-spree-api-key- in: header- required: true- schema:- type: string- - name: Authorization- in: header- required: true- schema:- type: string- - name: catalog_id- in: path- required: true- schema:- type: string- responses:- '200':- description: quantity rules found- content:- application/json:- example:- data:- - id: cqr_UkLWZg9DAJ- minimum_order_quantity: 48- order_multiple: 24- created_at: '2026-01-15T12:00:00.000Z'- updated_at: '2026-01-15T12:00:00.000Z'- variant_id: variant_gbHJdmfrXB- variant_sku: SKU-5- product_name: Product 45457- options_text: 'Size: S'- meta:- page: 1- limit: 25- count: 1- pages: 1- from: 1- to: 1- in: 1- previous:- next:- post:- summary: Create a catalog quantity rule- tags:- - Catalogs- security:- - api_key: []- bearer_auth: []- description: |-- States how much of one variant a buyer on this agreement must order. Both fields are optional individually, but a rule must state at least one — a field left out falls through to the catalog default, and then to the variant.-- **Required scope:** `write_products` (for API-key authentication).- parameters:- - name: x-spree-api-key- in: header- required: true- schema:- type: string- - name: Authorization- in: header- required: true- schema:- type: string- - name: catalog_id- in: path- required: true- schema:- type: string- responses:- '201':- description: quantity rule created- content:- application/json:- example:- id: cqr_UkLWZg9DAJ- minimum_order_quantity: 48- order_multiple: 24- created_at: '2026-01-15T12:00:00.000Z'- updated_at: '2026-01-15T12:00:00.000Z'- variant_id: variant_gbHJdmfrXB- variant_sku: SKU-7- product_name: Product 51599- options_text: 'Size: S'- '422':- description: invalid request- content:- application/json:- example:- error:- code: validation_error- message: Set a minimum order quantity, an order multiple, or both- details:- base:- - code: quantity_rule_states_nothing- message: Set a minimum order quantity, an order multiple, or- both- specific: false- requestBody:- content:- application/json:- schema:- type: object- properties:- variant_id:- type: string- example: variant_86Rf07xd4z- minimum_order_quantity:- type: integer- nullable: true- example: 48- description: The least a buyer may order.- order_multiple:- type: integer- nullable: true- example: 24- description: Orders must land on a multiple of this, counted from- the minimum.- required:- - variant_id"/api/v3/admin/catalogs/{catalog_id}/order_minimums":get:summary: List catalog order minimums@@ -28249,103 +28117,6 @@ paths:required:- currency- amount- "/api/v3/admin/catalogs/{catalog_id}/quantity_rules/{id}":- patch:- summary: Update a catalog quantity rule- tags:- - Catalogs- security:- - api_key: []- bearer_auth: []- description: |-- Restates one variant term. A field sent as null hands that field back to the catalog default; a rule must still state at least one of the two.-- **Required scope:** `write_products` (for API-key authentication).- parameters:- - name: x-spree-api-key- in: header- required: true- schema:- type: string- - name: Authorization- in: header- required: true- schema:- type: string- - name: catalog_id- in: path- required: true- schema:- type: string- - name: id- in: path- required: true- schema:- type: string- responses:- '200':- description: quantity rule updated- content:- application/json:- example:- id: cqr_UkLWZg9DAJ- minimum_order_quantity: 96- order_multiple: 24- created_at: '2026-01-15T12:00:00.000Z'- updated_at: '2026-01-15T12:00:00.000Z'- variant_id: variant_gbHJdmfrXB- variant_sku: SKU-11- product_name: Product 71912- options_text: 'Size: S'- requestBody:- content:- application/json:- schema:- type: object- properties:- minimum_order_quantity:- type: integer- nullable: true- example: 96- order_multiple:- type: integer- nullable: true- example: 48- delete:- summary: Delete a catalog quantity rule- tags:- - Catalogs- security:- - api_key: []- bearer_auth: []- description: |-- Drops one variant's exception, so it falls back to the catalog's own default.-- **Required scope:** `write_products` (for API-key authentication).- parameters:- - name: x-spree-api-key- in: header- required: true- schema:- type: string- - name: Authorization- in: header- required: true- schema:- type: string- - name: catalog_id- in: path- required: true- schema:- type: string- - name: id- in: path- required: true- schema:- type: string- responses:- '204':- description: quantity rule deleted"/api/v3/admin/catalogs/{catalog_id}/order_minimums/{id}":patch:summary: Update a catalog order minimum@@ -28435,56 +28206,16 @@ paths:responses:'204':description: order minimum deleted- "/api/v3/admin/catalogs/{catalog_id}/product_terms":- get:- summary: List catalog terms by product- tags:- - Catalogs- security:- - api_key: []- bearer_auth: []- description: |-- The catalog's quantity terms at the grain a merchant states them: one entry per product, over rows the database keeps per variant. `mixed` marks a product whose variants carry different terms.-- **Required scope:** `read_products` (for API-key authentication).- parameters:- - name: x-spree-api-key- in: header- required: true- schema:- type: string- - name: Authorization- in: header- required: true- schema:- type: string- - name: catalog_id- in: path- required: true- schema:- type: string- responses:- '200':- description: product terms found- content:- application/json:- example:- data:- - id: prod_UkLWZg9DAJ- product_id: prod_UkLWZg9DAJ- product_name: Product 93986- minimum_order_quantity: 48- order_multiple: 24- mixed: true+ "/api/v3/admin/catalogs/{catalog_id}/quantity_rules":put:- summary: Set catalog terms by product+ summary: Set catalog quantity rulestags:- Catalogssecurity:- api_key: []bearer_auth: []description: |-- Writes the given products' terms in one request, keyed by prefixed product id. Both fields null clears that product's terms; a product not yet in the assortment is added, since a term with nothing to apply to is not a reachable state. Products absent from the payload are left alone — this is the one catalog-term surface that is not a whole-set replacement, because an agreement may name terms for thousands of SKUs.+ Writes the given products' quantity terms in one request, keyed by prefixed product id. The stated pair is written to every variant of the product, which is the grain the database keeps them at. Both fields null clears that product's terms; a product not yet in the assortment is added, since a term with nothing to apply to is not a reachable state. Products absent from the payload are left alone — an agreement may name terms for thousands of SKUs. Read them back on the assortment rows: `GET /catalogs/{id}/products?expand=quantity_rule`.**Required scope:** `write_products` (for API-key authentication).parameters:@@ -28504,18 +28235,8 @@ paths:schema:type: stringresponses:- '200':- description: product terms set- content:- application/json:- example:- data:- - id: prod_UkLWZg9DAJ- product_id: prod_UkLWZg9DAJ- product_name: Product 107053- minimum_order_quantity: 48- order_multiple: 24- mixed: false+ '204':+ description: quantity rules setrequestBody:content:application/json:@@ -37292,6 +37013,10 @@ components:thumbnail_url:type: stringnullable: true+ quantity_rule:+ allOf:+ - "$ref": "#/components/schemas/CatalogProductTerm"+ nullable: truecatalog_variants:type: arrayitems:diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 4d99676d94..4f37ea0352 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -105,7 +105,6 @@ import type {CatalogOrderMinimumParams,CatalogParams,CatalogProductTermsParams,- CatalogQuantityRuleParams,CategoryCreateParams,CategoryRepositionParams,CategoryUpdateParams,@@ -267,8 +266,6 @@ import type {CatalogAssignment,CatalogOrderMinimum,CatalogProduct,- CatalogProductTerm,- CatalogQuantityRule,Category,Channel,Claim,@@ -3781,61 +3778,15 @@ export class AdminClient {}),/**- * Per-variant quantity terms. The catalog-wide default is a pair of+ * A catalog's quantity terms. The catalog-wide default is a pair of* fields on the catalog itself, so this is strictly the overrides.+ *+ * Written as a whole set at the grain a merchant states them at (per+ * product, over rows the database keeps per variant). Read them back on+ * the assortment rows instead: `catalogs.products.list(id, { expand:+ * ['quantity_rule'] })`.*/quantityRules: {- list: (- catalogId: string,- params?: ListParams & Record<string, unknown>,- options?: RequestOptions,- ): Promise<PaginatedResponse<CatalogQuantityRule>> =>- this.request<PaginatedResponse<CatalogQuantityRule>>(- 'GET',- `/catalogs/${catalogId}/quantity_rules`,- { ...options, params: params ? transformListParams(params) : undefined },- ),-- create: (- catalogId: string,- params: CatalogQuantityRuleParams,- options?: RequestOptions,- ): Promise<CatalogQuantityRule> =>- this.request<CatalogQuantityRule>('POST', `/catalogs/${catalogId}/quantity_rules`, {- ...options,- body: params,- }),-- update: (- catalogId: string,- id: string,- params: CatalogQuantityRuleParams,- options?: RequestOptions,- ): Promise<CatalogQuantityRule> =>- this.request<CatalogQuantityRule>('PATCH', `/catalogs/${catalogId}/quantity_rules/${id}`, {- ...options,- body: params,- }),-- delete: (catalogId: string, id: string, options?: RequestOptions): Promise<void> =>- this.request<void>('DELETE', `/catalogs/${catalogId}/quantity_rules/${id}`, options),- },-- /**- * Per-product quantity terms — the grain the agreement editor states- * them at, over rows the database keeps per variant.- */- productTerms: {- list: (- catalogId: string,- options?: RequestOptions,- ): Promise<{ data: CatalogProductTerm[] }> =>- this.request<{ data: CatalogProductTerm[] }>(- 'GET',- `/catalogs/${catalogId}/product_terms`,- options,- ),-/*** Writes the whole set in one request. A product whose pair is both* null has its terms cleared; a product not yet in the assortment is@@ -3846,12 +3797,11 @@ export class AdminClient {catalogId: string,params: CatalogProductTermsParams,options?: RequestOptions,- ): Promise<{ data: CatalogProductTerm[] }> =>- this.request<{ data: CatalogProductTerm[] }>(- 'PUT',- `/catalogs/${catalogId}/product_terms`,- { ...options, body: params },- ),+ ): Promise<void> =>+ this.request<void>('PUT', `/catalogs/${catalogId}/quantity_rules`, {+ ...options,+ body: params,+ }),},/** The order minimum in each currency this agreement states one for. */diff --git a/packages/admin-sdk/src/types/generated/CatalogProduct.ts b/packages/admin-sdk/src/types/generated/CatalogProduct.tsindex 0825f9d769..6404241b04 100644--- a/packages/admin-sdk/src/types/generated/CatalogProduct.ts+++ b/packages/admin-sdk/src/types/generated/CatalogProduct.ts@@ -1,12 +1,13 @@-// Typelizer digest 344e8c3a65d386aa3658daed1023b4bd+// Typelizer digest 204c83a8b5fe99d5387f2f6375668cb9//// DO NOT MODIFY: This file was automatically generated by Typelizer.-import type {CatalogPrice} from '@/types'+import type {CatalogProductTerm, CatalogPrice} from '@/types'interface CatalogProduct {id: string;name: string;thumbnail_url: string | null;+ quantity_rule?: CatalogProductTerm | null;catalog_variants?: Array<CatalogPrice>;}diff --git a/packages/dashboard/src/components/spree/catalog-terms-card.tsx b/packages/dashboard/src/components/spree/catalog-terms-card.tsxindex 8960a2d7d4..d2453e844d 100644--- a/packages/dashboard/src/components/spree/catalog-terms-card.tsx+++ b/packages/dashboard/src/components/spree/catalog-terms-card.tsx@@ -1,3 +1,4 @@+import type { CatalogProductTerm } from '@spree/admin-sdk'import { CurrencySelect, normalizeQuantityRule, useStore } from '@spree/dashboard-core'import {Button,@@ -23,6 +24,7 @@ import { useTranslation } from 'react-i18next'import type {CatalogFormValues,OrderMinimumEntry,+ ProductTermEntry,StagedProductTerms,} from '../../schemas/catalog'@@ -256,10 +258,17 @@ function OrderMinimums({export function catalogTermColumns({form,canEdit,+ savedTermFor,headers,}: {form: UseFormReturn<CatalogFormValues>canEdit: boolean+ /**+ * The term the agreement already holds for a product, read off the+ * assortment row. Absent while a page is still loading, in which case the+ * cell shows only what the merchant has staged.+ */+ savedTermFor?: (productId: string) => ProductTermEntry | undefinedheaders: {/** Short column heading. */minimum: string@@ -277,6 +286,11 @@ export function catalogTermColumns({}}) {const terms = form.watch('staged_terms') ?? {}+ // An unedited cell shows what the agreement holds, which now arrives on the+ // assortment row itself rather than from a fetch of every rule in the+ // catalog (docs/plans/6.0-volume-pricing.md). A staged edit wins over it.+ const entryFor = (productId: string): ProductTermEntry | undefined =>+ terms[productId] ?? savedTermFor?.(productId)const catalogMinimum = form.watch('minimum_order_quantity')?.trim()const catalogMultiple = form.watch('order_multiple')?.trim()@@ -317,7 +331,7 @@ export function catalogTermColumns({</>),renderCells: (row: { id: string; pending?: 'added' | 'removed' }) => {- const entry = terms[row.id]+ const entry = entryFor(row.id)// A row on its way out takes its terms with it, so editing them is// meaningless — and the struck-through row already says so.const disabled = !canEdit || row.pending === 'removed'@@ -368,6 +382,30 @@ export function catalogTermColumns({}}+/**+ * The saved terms on a page of assortment rows, as the cells read them.+ * Built per page rather than for the whole catalog: the rules ride along on+ * the rows themselves (docs/plans/6.0-volume-pricing.md).+ */+export function savedTermLookup(+ products: Array<{ id: string; quantity_rule?: CatalogProductTerm | null }>,+): (productId: string) => ProductTermEntry | undefined {+ const byProduct = new Map(+ products+ .filter((product) => product.quantity_rule)+ .map((product) => [+ product.id,+ {+ minimum_order_quantity: product.quantity_rule?.minimum_order_quantity?.toString() ?? '',+ order_multiple: product.quantity_rule?.order_multiple?.toString() ?? '',+ mixed: product.quantity_rule?.mixed,+ } satisfies ProductTermEntry,+ ]),+ )++ return (productId) => byProduct.get(productId)+}+/** The API's product terms as the form holds them. */export function termsToFormValues(terms: Array<{diff --git a/packages/dashboard/src/hooks/use-catalogs.ts b/packages/dashboard/src/hooks/use-catalogs.tsindex 5fa31d2690..dddb1d31b5 100644--- a/packages/dashboard/src/hooks/use-catalogs.ts+++ b/packages/dashboard/src/hooks/use-catalogs.ts@@ -99,7 +99,7 @@ export function useCatalogProducts(catalogId: string | undefined, page = 1) {adminClient.catalogs.products.list(catalogId as string, {page,limit: 25,- expand: ['catalog_price'],+ expand: ['catalog_price', 'quantity_rule'],}),enabled: !!catalogId,placeholderData: (previous) => previous,@@ -124,7 +124,7 @@ export interface CatalogSavePayload {* the assortment are added by the save — a term with nothing to apply to* is not a state worth being able to reach.*/- productTerms?: Record<+ quantityRules?: Record<string,{ minimum_order_quantity: number | null; order_multiple: number | null }>@@ -141,7 +141,7 @@ export function useSaveCatalog(catalogId: string) {attributes,addProductIds = [],removeProductIds = [],- productTerms = {},+ quantityRules = {},}) => {if (attributes) await adminClient.catalogs.update(catalogId, attributes)@@ -154,17 +154,12 @@ export function useSaveCatalog(catalogId: string) {await adminClient.catalogs.products.create(catalogId, addProductIds)}- const termProductIds = Object.keys(productTerms)+ const termProductIds = Object.keys(quantityRules)if (termProductIds.length > 0) {- await adminClient.catalogs.productTerms.upsert(catalogId, { terms: productTerms })+ await adminClient.catalogs.quantityRules.upsert(catalogId, { terms: quantityRules })}},- invalidate: [- ['catalogs'],- ['catalogs', catalogId],- ['catalogs', catalogId, 'products'],- ['catalogs', catalogId, 'product_terms'],- ],+ invalidate: [['catalogs'], ['catalogs', catalogId], ['catalogs', catalogId, 'products']],successMessage: i18n.t('admin.catalogs.messages.updated'),errorMessage: i18n.t('admin.errors.failed_to_update'),})@@ -211,12 +206,3 @@ export function useUnassignCatalog(catalogId: string) {// ---------------------------------------------------------------------------// Commercial terms — what the buyer may order, and what the order must reach// -----------------------------------------------------------------------------/** A catalog's per-product quantity terms, at the grain the editor states them. */-export function useCatalogProductTerms(catalogId: string | undefined) {- return useQuery({- queryKey: useResourceKey('catalogs', catalogId ?? 'noop', 'product_terms'),- queryFn: () => adminClient.catalogs.productTerms.list(catalogId as string),- enabled: !!catalogId,- })-}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsxindex f03c04243b..02785b85e6 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/catalogs/$catalogId.tsx@@ -29,7 +29,7 @@ import {} from '@spree/dashboard-ui'import { PauseIcon, PlayIcon, TableIcon } from '@spree/dashboard-ui/icons'import { createFileRoute, useNavigate } from '@tanstack/react-router'-import { useEffect, useMemo, useState } from 'react'+import { useEffect, useState } from 'react'import { type UseFormReturn, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { CatalogAudienceCard } from '../../../../../components/spree/catalog-audience'@@ -41,9 +41,9 @@ import { CatalogPricingFields } from '../../../../../components/spree/catalog-primport {CatalogTermsCard,catalogTermColumns,+ savedTermLookup,stagedTermsHaveErrors,stagedTermsToParams,- termsToFormValues,} from '../../../../../components/spree/catalog-terms-card'import { DeferredProductMembershipCard } from '../../../../../components/spree/deferred-product-membership-card'import { ImportWizardDialog } from '../../../../../components/spree/imports/import-wizard-dialog'@@ -61,7 +61,6 @@ import {useActivateCatalog,useCatalog,useCatalogProducts,- useCatalogProductTerms,useDeactivateCatalog,useDeleteCatalog,useSaveCatalog,@@ -115,8 +114,6 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {const deleteMutation = useDeleteCatalog()const wizard = useImportWizardSearch(Route.useSearch())const saveMutation = useSaveCatalog(catalog.id)- const { data: productTermsData } = useCatalogProductTerms(catalog.id)- const productTerms = useMemo(() => productTermsData?.data ?? [], [productTermsData])const canEdit = permissions.can('update', Subject.Catalog)@@ -163,9 +160,13 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {})),...catalogPricingValues(catalog.price_list),staged_products: { adds: [], removes: [] },- staged_terms: termsToFormValues(productTerms),+ // 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+ // form seeded per page would send one page's terms as the whole set+ // and clear every other page's (docs/plans/6.0-volume-pricing.md).+ staged_terms: {},})- }, [catalog, productTerms, form])+ }, [catalog, form])// Both directions confirm: activating starts showing an audience prices they// were not seeing, and deactivating takes them away. Whole keys rather than@@ -219,7 +220,7 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {attributes: catalogValuesToParams(values, savedPricingMode),addProductIds: values.staged_products.adds.map((product) => product.id),removeProductIds: values.staged_products.removes,- productTerms: stagedTermsToParams(terms),+ quantityRules: stagedTermsToParams(terms),})form.reset({ ...values, staged_products: { adds: [], removes: [] } })} catch (err) {@@ -335,7 +336,7 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {variantsOf: (product) => product.catalog_variants,})}- extraColumns={() =>+ extraColumns={(products) =>mergeExtraColumns(catalogPriceColumns({headers: {@@ -346,6 +347,7 @@ function CatalogBody({ catalog }: { catalog: Catalog }) {catalogTermColumns({form,canEdit,+ savedTermFor: savedTermLookup(products),headers: {// Short column headers — the card's own title already// says these are quantity terms. The full names stay asdiff --git a/spree/api/app/controllers/spree/api/v3/admin/catalogs/product_terms_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalogs/product_terms_controller.rbdeleted file mode 100644index 8b48500146..0000000000--- a/spree/api/app/controllers/spree/api/v3/admin/catalogs/product_terms_controller.rb+++ /dev/null@@ -1,76 +0,0 @@-module Spree- module Api- module V3- module Admin- module Catalogs- # A catalog's per-product quantity terms, written as a set.- #- # Terms are stored per variant but edited per product, because that- # is the grain a merchant states them at ("minimum 48 of this- # product"). One request per save rather than one per row: the- # dashboard stages every edit behind the catalog's Save, and a- # partial application would leave an agreement half-changed.- class ProductTermsController < BaseController- before_action :authorize_parent_access!-- # GET /api/v3/admin/catalogs/:catalog_id/product_terms- def index- render json: { data: serialize_terms }- end-- # PUT /api/v3/admin/catalogs/:catalog_id/product_terms- #- # { terms: { "prod_abc": { minimum_order_quantity: 48,- # order_multiple: 24 } } }- #- # A product whose pair is both null has its terms cleared.- def upsert- authorize! :update, @catalog-- result = Spree::Catalogs::SetProductTerms.call(catalog: @catalog, terms: resolved_terms)-- if result.success?- render json: { data: serialize_terms }- else- render_service_error(result)- end- end-- protected-- def model_class- Spree::CatalogQuantityRule- end-- def serializer_class- Spree.api.admin_catalog_quantity_rule_serializer- end-- def scope- @catalog.quantity_rules- end-- private-- # Products resolve through this store, so an id belonging to- # another tenant is a 404 rather than a term written against a- # product the merchant does not sell.- def resolved_terms- params.require(:terms).to_unsafe_h.to_h do |product_id, values|- product = current_store.products.find_by_prefix_id!(product_id)- [product, values.to_h.symbolize_keys.slice(:minimum_order_quantity, :order_multiple)]- end- end-- # Grouped by product, which is how the dashboard reads them back.- def serialize_terms- @catalog.quantity_rules.includes(variant: :product).group_by { |rule| rule.variant.product }.- map { |product, rules| Spree::Catalogs::ProductTerm.new(product: product, rules: rules) }.- map { |term| Spree.api.admin_catalog_product_term_serializer.new(term, params: serializer_params).to_h }- end- end- end- end- end- end-enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/catalogs/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalogs/products_controller.rbindex 99eb143c1c..e2295ce36b 100644--- a/spree/api/app/controllers/spree/api/v3/admin/catalogs/products_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/catalogs/products_controller.rb@@ -27,9 +27,24 @@ module Spree# own `expand?` does, so the attribute never renders without the# resolver that fills it.def serializer_params- return super unless expanded_keys.include?('catalog_price')+ params = super+ params = params.merge(catalog_price_resolver: catalog_price_resolver) if expanded_keys.include?('catalog_price')+ params = params.merge(catalog_quantity_rules: quantity_rules_by_product) if expanded_keys.include?('quantity_rule')+ params+ end++ # The page's quantity rules in one query, keyed by product. The+ # rows are stored per variant and read per product, which is the+ # roll-up the serializer does — on variants this page has already+ # loaded (docs/plans/6.0-volume-pricing.md).+ def quantity_rules_by_product+ @quantity_rules_by_product ||= begin+ variant_ids = priced_variants.map(&:id)+ rules = variant_ids.any? ? @catalog.quantity_rules.where(variant_id: variant_ids).to_a : []+ product_by_variant = priced_variants.to_h { |variant| [variant.id, variant.product_id] }- super.merge(catalog_price_resolver: catalog_price_resolver)+ rules.group_by { |rule| product_by_variant[rule.variant_id] }+ endend# Preloaded with every variant the page renders — each row nowdiff --git a/spree/api/app/controllers/spree/api/v3/admin/catalogs/quantity_rules_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalogs/quantity_rules_controller.rbindex 4b7e7136e6..3454b14d6c 100644--- a/spree/api/app/controllers/spree/api/v3/admin/catalogs/quantity_rules_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/catalogs/quantity_rules_controller.rb@@ -3,13 +3,41 @@ module Spreemodule V3module Adminmodule Catalogs- # A catalog's per-variant quantity terms — the narrowest of the- # three levels a buyer's rules resolve through. The catalog-wide- # default is a pair of fields on the catalog itself, so this- # surface is strictly the overrides.+ # A catalog's quantity terms — the narrowest of the three levels a+ # buyer's rules resolve through. The catalog-wide default is a pair+ # of fields on the catalog itself, so this surface is strictly the+ # overrides.+ #+ # Rows are stored per variant and written as a whole set, because+ # that is the grain a merchant states them at ("minimum 48 of this+ # product") and the dashboard stages every edit behind the catalog's+ # Save — a partial application would leave an agreement half-changed.+ #+ # There is no read action: the rules are read back on the assortment+ # rows (`expand=quantity_rule` on this catalog's products), which+ # already hold the variants they roll up+ # (docs/plans/6.0-volume-pricing.md).class QuantityRulesController < BaseControllerbefore_action :authorize_parent_access!+ # PUT /api/v3/admin/catalogs/:catalog_id/quantity_rules+ #+ # { terms: { "prod_abc": { minimum_order_quantity: 48,+ # order_multiple: 24 } } }+ #+ # A product whose pair is both null has its terms cleared.+ def upsert+ authorize! :update, @catalog++ result = Spree::Catalogs::SetProductTerms.call(catalog: @catalog, terms: resolved_terms)++ if result.success?+ head :no_content+ else+ render_service_error(result)+ end+ end+protecteddef model_class@@ -21,28 +49,23 @@ module Spreeenddef scope- @parent.quantity_rules+ @catalog.quantity_rulesenddef parent_association:quantity_rulesend- def collection_includes- [variant: :product]- end-- # The variant resolves through this store's own products, so an- # id belonging to another tenant is a 404 rather than a term- # written against a variant the merchant does not sell.- def permitted_params- permitted = params.permit(:minimum_order_quantity, :order_multiple, :variant_id)+ private- if permitted.key?(:variant_id)- permitted[:variant_id] = current_store.variants.find_by_prefix_id!(permitted[:variant_id]).id+ # Products resolve through this store, so an id belonging to+ # another tenant is a 404 rather than a term written against a+ # product the merchant does not sell.+ def resolved_terms+ params.require(:terms).to_unsafe_h.to_h do |product_id, values|+ product = current_store.products.find_by_prefix_id!(product_id)+ [product, values.to_h.symbolize_keys.slice(:minimum_order_quantity, :order_multiple)]end-- permittedendendenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/catalog_product_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/catalog_product_serializer.rbindex 9ded3ebc87..796e1242be 100644--- a/spree/api/app/serializers/spree/api/v3/admin/catalog_product_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/catalog_product_serializer.rb@@ -13,12 +13,28 @@ module Spree# variants, and a figure on the product row would have to pick one# variant to speak for the rest (docs/plans/6.0-volume-pricing.md).class CatalogProductSerializer < Admin::MembershipProductSerializer+ typelize quantity_rule: ['CatalogProductTerm', nullable: true]+# Priced off the same variant the row's own price is read from, so# the agreement's amount and the shop's describe the same offer.## Null means nothing prices this variant in this currency at all —# distinct from a `base` source, which is a real amount the# agreement simply does not touch.+ # This product's quantity terms under the agreement, rolled up from+ # the variant rows the page already loaded. Its own request used to+ # fetch every rule in the catalog unpaginated and group them the+ # same way, which is the same object graph this endpoint holds+ # (docs/plans/6.0-volume-pricing.md).+ attribute :quantity_rule, if: proc { expand?('quantity_rule') } do |product|+ rules = params[:catalog_quantity_rules]&.fetch(product.id, nil)++ if rules.present?+ term = Spree::Catalogs::ProductTerm.new(product: product, rules: rules)+ Spree.api.admin_catalog_product_term_serializer.new(term, params: params).to_h+ end+ end+# Every variant with what this agreement charges for it. A product's# variants can be priced differently — and carry different quantity# ladders — so a single figure on the product row names one variant'sdiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 7567233c80..fa541a0b70 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -659,12 +659,13 @@ Spree::Core::Engine.add_routes do# Commercial terms. Typed per grain rather than one rules endpoint:# quantity rules are per variant, minimums are per currency.#- # Both also answer as a whole set, because the agreement editor- # stages every term behind the catalog's Save: a half-applied- # agreement is not a state to leave a merchant in.- resources :quantity_rules, controller: 'catalogs/quantity_rules',- only: [:index, :show, :create, :update, :destroy]- resources :product_terms, controller: 'catalogs/product_terms', only: [:index] do+ # Quantity rules are written as a whole set, because the agreement+ # editor stages every term behind the catalog's Save: a half-applied+ # agreement is not a state to leave a merchant in. They are read+ # back on the assortment rows themselves (`expand=quantity_rule` on+ # this catalog's products), where the variants they roll up are+ # already loaded (docs/plans/6.0-volume-pricing.md).+ resources :quantity_rules, controller: 'catalogs/quantity_rules', only: [] docollection { put :upsert, path: '' }endresources :order_minimums, controller: 'catalogs/order_minimums',diff --git a/spree/api/spec/controllers/spree/api/v3/admin/catalogs/product_terms_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/catalogs/product_terms_controller_spec.rbdeleted file mode 100644index 817bef2ccf..0000000000--- a/spree/api/spec/controllers/spree/api/v3/admin/catalogs/product_terms_controller_spec.rb+++ /dev/null@@ -1,83 +0,0 @@-require 'spec_helper'--RSpec.describe Spree::Api::V3::Admin::Catalogs::ProductTermsController, type: :controller do- render_views-- include_context 'API v3 Admin authenticated'-- let!(:catalog) { create(:catalog, store: store) }- let(:product) { create(:product, store: store) }-- before { request.headers.merge!(headers) }-- describe 'GET #index' do- it "lists a catalog's terms at product grain" do- catalog.add_products([product.id])- create(:catalog_quantity_rule, catalog: catalog, variant: product.default_variant,- minimum_order_quantity: 48, order_multiple: 24)-- get :index, params: { catalog_id: catalog.prefixed_id }, as: :json-- expect(response).to have_http_status(:ok)- row = json_response['data'].first- expect(row['product_id']).to eq(product.prefixed_id)- expect(row['minimum_order_quantity']).to eq(48)- end-- # The rows are per variant, so a product whose variants disagree is- # reported honestly rather than by picking one of them.- it 'marks a product whose variants carry different terms as mixed' do- second = create(:variant, product: product)- create(:catalog_quantity_rule, catalog: catalog, variant: product.default_variant,- minimum_order_quantity: 48)- create(:catalog_quantity_rule, catalog: catalog, variant: second, minimum_order_quantity: 96)-- get :index, params: { catalog_id: catalog.prefixed_id }, as: :json-- expect(json_response['data'].first['mixed']).to be(true)- end- end-- describe 'PUT #upsert' do- it 'states terms for a product and adds it to the assortment' do- put :upsert, params: {- catalog_id: catalog.prefixed_id,- terms: { product.prefixed_id => { minimum_order_quantity: 48, order_multiple: 24 } }- }, as: :json-- expect(response).to have_http_status(:ok)- expect(catalog.products.reload).to include(product)- expect(catalog.quantity_rules.reload.first.minimum_order_quantity).to eq(48)- end-- it 'clears a product\'s terms when both fields are blank' do- create(:catalog_quantity_rule, catalog: catalog, variant: product.default_variant)-- put :upsert, params: {- catalog_id: catalog.prefixed_id,- terms: { product.prefixed_id => { minimum_order_quantity: nil, order_multiple: nil } }- }, as: :json-- expect(catalog.quantity_rules.reload).to be_empty- end-- it 'is not found for a product from another store' do- foreign = create(:product, store: create(:store))-- put :upsert, params: {- catalog_id: catalog.prefixed_id,- terms: { foreign.prefixed_id => { minimum_order_quantity: 48 } }- }, as: :json-- expect(response).to have_http_status(:not_found)- end- end-- describe 'a catalog in another store' do- it 'is not found' do- get :index, params: { catalog_id: create(:catalog, store: create(:store)).prefixed_id }, as: :json-- expect(response).to have_http_status(:not_found)- end- end-enddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/catalogs/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/catalogs/products_controller_spec.rbindex b5d6e46d22..d932f00454 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/catalogs/products_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/catalogs/products_controller_spec.rb@@ -44,6 +44,50 @@ RSpec.describe Spree::Api::V3::Admin::Catalogs::ProductsController, type: :contrexpect(json_response['data'].first).not_to have_key('catalog_variants')end+ # The terms ride along on the rows they belong to. They used to be their+ # own unpaginated request that loaded every rule in the catalog and+ # grouped it by product — the same roll-up, over the variants this page+ # already holds (docs/plans/6.0-volume-pricing.md).+ it 'rolls a product\'s quantity terms up onto its row' do+ product = create(:product, store: store)+ create(:catalog_product, catalog: catalog, product: product)+ create(:catalog_quantity_rule, catalog: catalog, variant: product.default_variant,+ minimum_order_quantity: 48, order_multiple: 24)++ get :index, params: { catalog_id: catalog.prefixed_id, expand: 'quantity_rule' }, as: :json++ rule = json_response['data'].first['quantity_rule']+ expect(rule['product_id']).to eq(product.prefixed_id)+ expect(rule['minimum_order_quantity']).to eq(48)+ expect(rule['order_multiple']).to eq(24)+ end++ # The rows are per variant, so a product whose variants disagree is+ # reported honestly rather than by picking one of them.+ it 'marks a product whose variants carry different terms as mixed' do+ product = create(:product, store: store)+ second = create(:variant, product: product)+ create(:catalog_product, catalog: catalog, product: product)+ create(:catalog_quantity_rule, catalog: catalog, variant: product.default_variant,+ minimum_order_quantity: 48)+ create(:catalog_quantity_rule, catalog: catalog, variant: second, minimum_order_quantity: 96)++ get :index, params: { catalog_id: catalog.prefixed_id, expand: 'quantity_rule' }, as: :json++ expect(json_response['data'].first['quantity_rule']['mixed']).to be(true)+ end++ it 'leaves the terms out unless they are asked for' do+ product = create(:product, store: store)+ create(:catalog_product, catalog: catalog, product: product)+ create(:catalog_quantity_rule, catalog: catalog, variant: product.default_variant,+ minimum_order_quantity: 48)++ get :index, params: { catalog_id: catalog.prefixed_id }, as: :json++ expect(json_response['data'].first).not_to have_key('quantity_rule')+ end+# The card renders a name and a thumbnail, and the picker reads ids. A# full product payload per row is what made this page slow, so the shape# is pinned rather than left to whatever the admin serializer growsdiff --git a/spree/api/spec/controllers/spree/api/v3/admin/catalogs/quantity_rules_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/catalogs/quantity_rules_controller_spec.rbindex d70c3e6f29..4d72250744 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/catalogs/quantity_rules_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/catalogs/quantity_rules_controller_spec.rb@@ -6,91 +6,66 @@ RSpec.describe Spree::Api::V3::Admin::Catalogs::QuantityRulesController, type: :include_context 'API v3 Admin authenticated'let!(:catalog) { create(:catalog, store: store) }- let(:variant) { create(:variant, product: create(:product, store: store)) }+ let(:product) { create(:product, store: store) }before { request.headers.merge!(headers) }- describe 'GET #index' do- it "lists the catalog's overrides with the variant they name" do- rule = create(:catalog_quantity_rule, catalog: catalog, variant: variant)-- get :index, params: { catalog_id: catalog.prefixed_id }, as: :json-- expect(response).to have_http_status(:ok)- row = json_response['data'].first- expect(row['id']).to eq(rule.prefixed_id)- expect(row['variant_id']).to eq(variant.prefixed_id)- expect(row['minimum_order_quantity']).to eq(48)- end-- it "does not leak another catalog's rules" do- other = create(:catalog, store: store)- create(:catalog_quantity_rule, catalog: other, variant: variant)-- get :index, params: { catalog_id: catalog.prefixed_id }, as: :json-- expect(json_response['data']).to be_empty- end- end-- describe 'POST #create' do- it 'records an override' do- post :create, params: {+ # The whole set in one request, at the grain a merchant states terms at.+ # Reading them back is the assortment listing's job — see the products+ # controller spec (docs/plans/6.0-volume-pricing.md).+ describe 'PUT #upsert' do+ it 'states terms for a product and adds it to the assortment' do+ put :upsert, params: {catalog_id: catalog.prefixed_id,- variant_id: variant.prefixed_id,- minimum_order_quantity: 480,- order_multiple: 240+ terms: { product.prefixed_id => { minimum_order_quantity: 48, order_multiple: 24 } }}, as: :json- expect(response).to have_http_status(:created)- expect(catalog.quantity_rules.reload.first.minimum_order_quantity).to eq(480)- end-- it 'refuses a row stating neither field' do- post :create, params: { catalog_id: catalog.prefixed_id, variant_id: variant.prefixed_id }, as: :json-- expect(response).to have_http_status(:unprocessable_content)+ expect(response).to have_http_status(:no_content)+ expect(catalog.products.reload).to include(product)+ expect(catalog.quantity_rules.reload.first.minimum_order_quantity).to eq(48)end- # A variant belonging to another tenant must be unreachable, not merely- # rejected by a validation.- it 'is not found for a variant from another store' do- foreign = create(:variant, product: create(:product, store: create(:store)))+ it 'writes the stated pair to every variant of the product' do+ second = create(:variant, product: product)- post :create, params: {- catalog_id: catalog.prefixed_id, variant_id: foreign.prefixed_id, minimum_order_quantity: 12+ put :upsert, params: {+ catalog_id: catalog.prefixed_id,+ terms: { product.prefixed_id => { minimum_order_quantity: 48 } }}, as: :json- expect(response).to have_http_status(:not_found)+ expect(catalog.quantity_rules.reload.map(&:variant_id)).+ to match_array([product.default_variant.id, second.id])end- end- describe 'PATCH #update' do- it 'changes the stated terms' do- rule = create(:catalog_quantity_rule, catalog: catalog, variant: variant)+ it 'clears a product\'s terms when both fields are blank' do+ create(:catalog_quantity_rule, catalog: catalog, variant: product.default_variant)- patch :update, params: { catalog_id: catalog.prefixed_id, id: rule.prefixed_id, order_multiple: 12 }, as: :json+ put :upsert, params: {+ catalog_id: catalog.prefixed_id,+ terms: { product.prefixed_id => { minimum_order_quantity: nil, order_multiple: nil } }+ }, as: :json- expect(response).to have_http_status(:ok)- expect(rule.reload.order_multiple).to eq(12)+ expect(catalog.quantity_rules.reload).to be_emptyend- end- describe 'DELETE #destroy' do- it 'removes the override' do- rule = create(:catalog_quantity_rule, catalog: catalog, variant: variant)+ it 'is not found for a product from another store' do+ foreign = create(:product, store: create(:store))- delete :destroy, params: { catalog_id: catalog.prefixed_id, id: rule.prefixed_id }, as: :json+ put :upsert, params: {+ catalog_id: catalog.prefixed_id,+ terms: { foreign.prefixed_id => { minimum_order_quantity: 48 } }+ }, as: :json- expect(catalog.quantity_rules.reload).to be_empty+ expect(response).to have_http_status(:not_found)endenddescribe 'a catalog in another store' doit 'is not found' do- foreign = create(:catalog, store: create(:store))-- get :index, params: { catalog_id: foreign.prefixed_id }, as: :json+ put :upsert, params: {+ catalog_id: create(:catalog, store: create(:store)).prefixed_id,+ terms: { product.prefixed_id => { minimum_order_quantity: 48 } }+ }, as: :jsonexpect(response).to have_http_status(:not_found)enddiff --git a/spree/api/spec/integration/spree/api/v3/admin/catalogs_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/catalogs_spec.rbindex c0f889137c..c3be9743ea 100644--- a/spree/api/spec/integration/spree/api/v3/admin/catalogs_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/catalogs_spec.rb@@ -231,76 +231,6 @@ RSpec.describe 'Admin Catalogs API', type: :request, swagger_doc: 'api-referenceendend- path '/api/v3/admin/catalogs/{catalog_id}/quantity_rules' do- get 'List catalog quantity rules' do- tags 'Catalogs'- produces 'application/json'- security [api_key: [], bearer_auth: []]- description "The catalog's per-variant quantity terms. The catalog-wide default is a pair of fields on the catalog itself, so these are strictly the overrides."- admin_scope :read, :products-- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true- parameter name: :Authorization, in: :header, type: :string, required: true- parameter name: :catalog_id, in: :path, type: :string, required: true-- response '200', 'quantity rules found' do- let(:'x-spree-api-key') { secret_api_key.plaintext_token }- let(:catalog_id) { catalog.prefixed_id }- let!(:rule) do- create(:catalog_quantity_rule, catalog: catalog,- variant: create(:variant, product: create(:product, store: store)))- end-- run_test! do |response|- data = JSON.parse(response.body)- expect(data['data'].pluck('id')).to include(rule.prefixed_id)- end- end- end-- post 'Create a catalog quantity rule' do- tags 'Catalogs'- consumes 'application/json'- produces 'application/json'- security [api_key: [], bearer_auth: []]- description 'States how much of one variant a buyer on this agreement must order. Both fields are optional individually, but a rule must state at least one — a field left out falls through to the catalog default, and then to the variant.'- admin_scope :write, :products-- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true- parameter name: :Authorization, in: :header, type: :string, required: true- parameter name: :catalog_id, in: :path, type: :string, required: true- parameter name: :body, in: :body, schema: {- type: :object,- properties: {- variant_id: { type: :string, example: 'variant_86Rf07xd4z' },- minimum_order_quantity: { type: :integer, nullable: true, example: 48,- description: 'The least a buyer may order.' },- order_multiple: { type: :integer, nullable: true, example: 24,- description: 'Orders must land on a multiple of this, counted from the minimum.' }- },- required: ['variant_id']- }-- let(:'x-spree-api-key') { secret_api_key.plaintext_token }- let(:catalog_id) { catalog.prefixed_id }- let(:variant) { create(:variant, product: create(:product, store: store)) }-- response '201', 'quantity rule created' do- let(:body) { { variant_id: variant.prefixed_id, minimum_order_quantity: 48, order_multiple: 24 } }-- run_test! do |response|- expect(JSON.parse(response.body)['minimum_order_quantity']).to eq(48)- end- end-- response '422', 'invalid request' do- let(:body) { { variant_id: variant.prefixed_id } }-- run_test!- end- end- end-path '/api/v3/admin/catalogs/{catalog_id}/order_minimums' doget 'List catalog order minimums' dotags 'Catalogs'@@ -364,69 +294,6 @@ RSpec.describe 'Admin Catalogs API', type: :request, swagger_doc: 'api-referenceendend- path '/api/v3/admin/catalogs/{catalog_id}/quantity_rules/{id}' do- patch 'Update a catalog quantity rule' do- tags 'Catalogs'- consumes 'application/json'- produces 'application/json'- security [api_key: [], bearer_auth: []]- description 'Restates one variant term. A field sent as null hands that field back to the catalog default; a rule must still state at least one of the two.'- admin_scope :write, :products-- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true- parameter name: :Authorization, in: :header, type: :string, required: true- parameter name: :catalog_id, in: :path, type: :string, required: true- parameter name: :id, in: :path, type: :string, required: true- parameter name: :body, in: :body, schema: {- type: :object,- properties: {- minimum_order_quantity: { type: :integer, nullable: true, example: 96 },- order_multiple: { type: :integer, nullable: true, example: 48 }- }- }-- response '200', 'quantity rule updated' do- let(:'x-spree-api-key') { secret_api_key.plaintext_token }- let(:catalog_id) { catalog.prefixed_id }- let!(:quantity_rule) do- create(:catalog_quantity_rule, catalog: catalog,- variant: create(:variant, product: create(:product, store: store)))- end- let(:id) { quantity_rule.prefixed_id }- let(:body) { { minimum_order_quantity: 96 } }-- run_test! do |response|- expect(JSON.parse(response.body)['minimum_order_quantity']).to eq(96)- end- end- end-- delete 'Delete a catalog quantity rule' do- tags 'Catalogs'- produces 'application/json'- security [api_key: [], bearer_auth: []]- description "Drops one variant's exception, so it falls back to the catalog's own default."- admin_scope :write, :products-- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true- parameter name: :Authorization, in: :header, type: :string, required: true- parameter name: :catalog_id, in: :path, type: :string, required: true- parameter name: :id, in: :path, type: :string, required: true-- response '204', 'quantity rule deleted' do- let(:'x-spree-api-key') { secret_api_key.plaintext_token }- let(:catalog_id) { catalog.prefixed_id }- let!(:quantity_rule) do- create(:catalog_quantity_rule, catalog: catalog,- variant: create(:variant, product: create(:product, store: store)))- end- let(:id) { quantity_rule.prefixed_id }-- run_test!- end- end- end-path '/api/v3/admin/catalogs/{catalog_id}/order_minimums/{id}' dopatch 'Update a catalog order minimum' dotags 'Catalogs'@@ -481,38 +348,12 @@ RSpec.describe 'Admin Catalogs API', type: :request, swagger_doc: 'api-referenceendend- path '/api/v3/admin/catalogs/{catalog_id}/product_terms' do- get 'List catalog terms by product' do- tags 'Catalogs'- produces 'application/json'- security [api_key: [], bearer_auth: []]- description "The catalog's quantity terms at the grain a merchant states them: one entry per product, over rows the database keeps per variant. `mixed` marks a product whose variants carry different terms."- admin_scope :read, :products-- parameter name: 'x-spree-api-key', in: :header, type: :string, required: true- parameter name: :Authorization, in: :header, type: :string, required: true- parameter name: :catalog_id, in: :path, type: :string, required: true-- response '200', 'product terms found' do- let(:'x-spree-api-key') { secret_api_key.plaintext_token }- let(:catalog_id) { catalog.prefixed_id }- let!(:quantity_rule) do- create(:catalog_quantity_rule, catalog: catalog,- variant: create(:variant, product: create(:product, store: store)))- end-- run_test! do |response|- expect(JSON.parse(response.body)['data'].first['minimum_order_quantity']).to eq(48)- end- end- end-- put 'Set catalog terms by product' do+ path '/api/v3/admin/catalogs/{catalog_id}/quantity_rules' do+ put 'Set catalog quantity rules' dotags 'Catalogs'consumes 'application/json'- produces 'application/json'security [api_key: [], bearer_auth: []]- description 'Writes the given products\' terms in one request, keyed by prefixed product id. Both fields null clears that product\'s terms; a product not yet in the assortment is added, since a term with nothing to apply to is not a reachable state. Products absent from the payload are left alone — this is the one catalog-term surface that is not a whole-set replacement, because an agreement may name terms for thousands of SKUs.'+ description 'Writes the given products\' quantity terms in one request, keyed by prefixed product id. The stated pair is written to every variant of the product, which is the grain the database keeps them at. Both fields null clears that product\'s terms; a product not yet in the assortment is added, since a term with nothing to apply to is not a reachable state. Products absent from the payload are left alone — an agreement may name terms for thousands of SKUs. Read them back on the assortment rows: `GET /catalogs/{id}/products?expand=quantity_rule`.'admin_scope :write, :productsparameter name: 'x-spree-api-key', in: :header, type: :string, required: true@@ -535,7 +376,7 @@ RSpec.describe 'Admin Catalogs API', type: :request, swagger_doc: 'api-referencerequired: ['terms']}- response '200', 'product terms set' do+ response '204', 'quantity rules set' dolet(:'x-spree-api-key') { secret_api_key.plaintext_token }let(:catalog_id) { catalog.prefixed_id }let(:product) { create(:product, store: store) }@@ -543,8 +384,8 @@ RSpec.describe 'Admin Catalogs API', type: :request, swagger_doc: 'api-reference{ terms: { product.prefixed_id => { minimum_order_quantity: 48, order_multiple: 24 } } }end- run_test! do |response|- expect(JSON.parse(response.body)['data'].first['minimum_order_quantity']).to eq(48)+ run_test! do+ expect(catalog.quantity_rules.reload.first.minimum_order_quantity).to eq(48)endendend