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: charge a company the best price when it has two catalogs (#14661)
Łukasz Adamczykfd125852131f
diff --git a/docs/developer/core-concepts/catalogs.mdx b/docs/developer/core-concepts/catalogs.mdxindex d921df846f..b8408e69ca 100644--- a/docs/developer/core-concepts/catalogs.mdx+++ b/docs/developer/core-concepts/catalogs.mdx@@ -198,7 +198,13 @@ Prices are checked in order, and the first match wins:2. Ordinary price lists whose rules match3. The product's base price-Nearest-first is what lets a subsidiary hold a better-negotiated rate than the group's, without disturbing anyone else.+Nearest-first is what lets a subsidiary hold a better-negotiated rate than the group's, without disturbing anyone else. A nearer node answers even when a catalog further up happens to be cheaper — it's the agreement that buyer is on.++<Note>+**When one company holds several catalogs, the buyer pays the best price among them.** Nothing about two assignments on the same node says which of them a company is on, so neither outranks the other and the cheapest applicable price wins. The order catalogs appear in on the catalogs screen is display order — it never decides money.++Quantity breaks are part of that comparison: the price compared is the one for the quantity being bought, so a catalog with a deep break at 24 units wins from 24 up and may lose below it.+</Note><Warning>A price list owned by a catalog applies **because the catalog applies** — its own rules are not consulted, and it's excluded from ordinary rule matching.diff --git a/docs/plans/6.0-b2b-companies-and-catalogs.md b/docs/plans/6.0-b2b-companies-and-catalogs.mdindex 4d9bb2b383..137e041179 100644--- a/docs/plans/6.0-b2b-companies-and-catalogs.md+++ b/docs/plans/6.0-b2b-companies-and-catalogs.md@@ -164,8 +164,10 @@ existed as far as any upgrade path is concerned.catalog assigned to a company node applies to its **subtree**: effectivecatalogs for a purchase node are the union of assignments on`self_and_ancestors`. Visibility is the union across effective catalogs;- pricing takes the **nearest node's** assignment first, then catalog- position.+ pricing takes the **nearest node's** assignment first, and **within one+ node charges the best price any of its catalogs gives** (amended+ 2026-09-16, V-3635 — catalog position used to break that tie and so+ decided the money).- **No `tax_exempt` boolean anywhere** (reaffirming decisions.md 2026-08-07— exemption is certificates + provider resolution, never a flag).- **No new state machines, no workflows for plain CRUD.** Company,@@ -388,10 +390,10 @@ amendments:`CatalogProduct` purely as a membership filter, and the listing keepswhatever sort the shopper chose. The column, `acts_as_list`, the`reposition` endpoint and the dashboard's drag handle are all removed; the- admin lists an assortment by name. (`Catalog#position` is unaffected — it- still breaks ties when several catalogs apply to one buyer.) Category and- collection membership stays positioned, because those *do* drive storefront- display order.+ admin lists an assortment by name. (`Catalog#position` survives as the+ order of the catalogs screen itself. It stopped deciding prices on+ 2026-09-16 — see Pricing below.) Category and collection membership stays+ positioned, because those *do* drive storefront display order.- **Effective catalogs for a purchase node** = union of assignments on`self_and_ancestors`. The parent assigns the group-wide catalog once; abranch adds its own extra catalog without re-assigning the shared one.@@ -405,10 +407,20 @@ amendments:alternatives, not layers — a buyer whose company subtree carries anycatalog is never also served their customer group's, and trade tiers overa company tree are expressed as company assignments (see decisions.md).-- **Pricing**: `Pricing::Resolver` checks the effective catalogs'- PriceLists in **nearest-node-first** order (the purchase node's own- assignments before its parent's, catalog `position` breaking ties within a- node), then the existing PriceRule matching, then base price.+- **Pricing**: the resolver checks the effective catalogs' PriceLists in+ **nearest-node-first** order (the purchase node's own assignments before+ its parent's), then the existing PriceRule matching, then base price.+ **Amended 2026-09-16 (V-3635):** catalogs assigned to the *same* node rank+ equally and the buyer pays the **best price** among them. Position used to+ break that tie, which meant reordering the store-wide catalogs screen+ silently changed what a company was charged, and a company given two+ catalogs was billed from whichever sorted first rather than the cheaper —+ with no screen anywhere showing that two applied. Precedence *between*+ nodes is unchanged: a division's own agreement still answers over its+ parent's, cheaper or not, because that is an agreement someone negotiated.+ `Spree::Catalog.groups_for_*` return the catalogs grouped by assigning+ node so the resolver can see the rank boundaries; every other reader keeps+ the flat union.- **No Company ↔ CustomerGroup link.** The 6.1 sketch's`spree_companies.customer_group_id` is dropped from the design: catalogassignment targets the company node directly, so the link's only remainingdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 5b25d92f9c..453c186112 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,21 @@+## 2026-09-16: Two catalogs on one company charge the best of them, and every order line says which agreement priced it++**Context:** Nothing stopped an operator assigning a second catalog to a company — the audience picker offered the company again with no warning — and once both were active the buyer was charged from whichever catalog sorted first, not the cheaper one. Reported against a company holding a 5%-off catalog and a contract catalog with a quantity break: at 24 units the buyer paid $2,280.00 where the company's other agreement said $1,200.00, and reversing the two catalogs' order reversed the outcome (V-3635). The tie-break was the documented design — `Catalog#position`, which is the order of the store-wide catalogs screen — so a merchant dragging that list to tidy it changed what companies paid, with no screen anywhere listing a company's catalogs to show it had happened.++**Decision:** Precedence between nodes is real and unchanged: a division's own agreement still answers over its parent's, cheaper or not, because someone negotiated it. Precedence *within* a node is not real, so it is gone — catalogs assigned to the same company node rank equally and the buyer pays the **best price any of them gives**. Equal amounts keep list order, so the answer stays stable. `Spree::Catalog.groups_for_company` / `groups_for_context` / `groups_for_buyer` return the catalogs grouped by assigning node and the flat `for_*` readers are derived from them, so visibility and quantity terms keep the union they always had while pricing alone sees the rank boundaries. `Spree::Current` memoizes the grouped form and derives the flat set from it, so the two cannot disagree about one buyer. Position keeps ordering the catalogs screen and nothing else.++Rejected: refusing the second assignment, which would delete a shipped feature (two catalogs on one company is how an operator unions two assortments) and invalidate stores already doing it; and warning the operator while leaving the money alone, which does not stop the overcharge. Best-price is also the rule a merchant can state in one sentence to the buyer they overcharged.++**Consequences:** The admin line-item serializer gains `price_list_id`, `price_list_name`, `catalog_id` and `catalog_name`, and the dashboard's order item rows link to the agreement that priced them. This is read off the price list the line was stamped with at pricing time, never re-resolved — so it reports what the buyer was actually charged from rather than what would apply today, and it keeps the order read path provider-free (2026-08-30, which is why `catalog_price` on the same serializer is a base price). Provenance stays admin-only, off the store serializers, like `price_source`. The orders controller preloads `line_items: { price_list: :catalog }` so a page of orders does not pay two queries per line.++Deliberately not done: an **effective-price view** on the company or customer page — what a named buyer would pay for a product before any order exists. Raised on the issue after the fix was scoped, with figures: one variant offered at $111.11 by a company catalog, $329.99 by a standalone list and $549.99 as the shop price, with no screen anywhere reconciling the three (the customer page shows groups only, the company page no pricing at all). It is a real gap and a larger one than the original report's "show which catalog applies". The link added above answers only after the fact. A preview needs a new admin endpoint taking company-or-customer plus variant and quantity — the quantity matters, since a break can reverse which agreement wins — and cards on two dashboard pages. `Spree::Pricing::Context` already takes exactly those inputs and the storefront resolves through it per variant, so this is a new surface over an existing resolver, not a second one; the provider-free rule it must respect is about order and listing serializers, not a deliberate preview call. Held out so an urgent money fix is not gated on a feature.++The same walk confirmed the tier order — company catalog, then standalone lists by their own rules, then shop price — is consistent and worth preserving. It is: best-price applies only within one node, never across tiers, and a test over that scenario charges $111.11 at every quantity.++The same first-wins shape remains in `Catalogs::ResolveQuantityRules`, where the fields are minimums and multiples rather than money and "best" has no obvious meaning; V-3592 is the same class of problem on commission rates and is untouched here.++**Plans amended:** `6.0-b2b-companies-and-catalogs.md` (Key Decisions, the `Catalog#position` note, and Pricing).+## 2026-09-12: Reporting scopes money to one currency and never converts; counts are not scoped at all**Context:** Every sales and payments base filtered `currency` unconditionally, so a multi-currency store could not ask how many orders it took — only how many were priced in one currency. That is a wrong answer rather than a partial one. The wider question of cross-currency totals came up at the same time, so both were settled together after looking at how other platforms handle it.diff --git a/packages/admin-sdk/src/types/generated/LineItem.ts b/packages/admin-sdk/src/types/generated/LineItem.tsindex 011819e4b8..2b3a2a6cc5 100644--- a/packages/admin-sdk/src/types/generated/LineItem.ts+++ b/packages/admin-sdk/src/types/generated/LineItem.ts@@ -1,4 +1,4 @@-// Typelizer digest 660ee950edc2969dfc0c517b63e11e7c+// Typelizer digest 1a299642fa00d057e5f02e004b681b65//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Seller, OptionValue, DigitalLink, TaxLine, Variant, TaxCategory} from '@/types'@@ -42,6 +42,10 @@ interface LineItem {created_at: string;updated_at: string;catalog_price: string | null;+ price_list_id: string | null;+ price_list_name: string | null;+ catalog_id: string | null;+ catalog_name: string | null;cost_price: string | null;tax_category_id: string | null;variant?: Variant;diff --git a/packages/dashboard-ui/src/spree/fulfillment-item-list.tsx b/packages/dashboard-ui/src/spree/fulfillment-item-list.tsxindex cd17e62522..0cdca1c143 100644--- a/packages/dashboard-ui/src/spree/fulfillment-item-list.tsx+++ b/packages/dashboard-ui/src/spree/fulfillment-item-list.tsx@@ -1,3 +1,4 @@+import type { ReactNode } from 'react'import { Thumbnail } from '../ui/thumbnail'import { PackageIcon } from './icons'@@ -5,6 +6,9 @@ import { PackageIcon } from './icons'* One row of a fulfillment's item list, already joined to its line item by* the caller. The image and the price are optional: a surface that does not* expose them renders the name and the count alone.+ *+ * `priceSource` is a node because saying where a price came from means+ * linking to it, and routing belongs to the app.*/export type FulfillmentItemRowData = {key: string@@ -12,6 +16,7 @@ export type FulfillmentItemRowData = {optionsText?: string | nullthumbnailUrl?: string | nulldisplayPrice?: string | null+ priceSource?: ReactNodequantity: number}@@ -35,14 +40,15 @@ function ItemRow({ row }: { row: FulfillmentItemRowData }) {)}</div>- <div className="shrink-0 whitespace-nowrap text-right text-muted-foreground text-sm">+ <div className="min-w-0 shrink text-right text-muted-foreground text-sm">{row.displayPrice ? (- <span>+ <span className="whitespace-nowrap">{row.displayPrice} × {row.quantity}</span>) : (- <span>× {row.quantity}</span>+ <span className="whitespace-nowrap">× {row.quantity}</span>)}+ {row.priceSource && <div className="truncate text-xs">{row.priceSource}</div>}</div></div>)diff --git a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsxindex e373c71961..cad3a4f7c0 100644--- a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx+++ b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx@@ -31,6 +31,7 @@ import {FieldGroup,FieldLabel,FulfillmentItemList,+ type FulfillmentItemRowData,FulfillmentPanel,Input,RelativeTime,@@ -63,9 +64,24 @@ import { FulfillmentDeliveryDialog } from './fulfillment-delivery-dialog'import { FulfillmentEditDialog } from './fulfillment-edit-dialog'import { FulfillmentFulfillForm } from './fulfillment-fulfill-form'import { FulfillmentLabelUploadDialog } from './fulfillment-label-upload-dialog'+import { LineItemPriceSource } from './line-item-price-source'import { ShippingDocuments } from './shipping-documents'import { ShippingLabelRow } from './shipping-label-row'+/**+ * Hangs the agreement that priced each line off its row. Looked up by id from+ * the order's items, since the row carries only the narrow shape the grouping+ * reads; a row keyed by variant has no line item and gets nothing.+ */+function withPriceSource(rows: FulfillmentItemRow[], order: Order): FulfillmentItemRowData[] {+ const byId = new Map((order.items ?? []).map((item) => [item.id, item]))++ return rows.map((row) => {+ const lineItem = byId.get(row.key)+ return lineItem ? { ...row, priceSource: <LineItemPriceSource lineItem={lineItem} /> } : row+ })+}+/*** A unit sitting in one fulfillment. Splitting moves units per variant rather* than per line item, because that is what the backend's transfer takes.@@ -596,7 +612,9 @@ function FulfillmentRow({ order, fulfillment }: { order: Order; fulfillment: Ful/>) : (<>- <FulfillmentItemList rows={fulfillmentItemRows(fulfillment, order.items ?? [])} />+ <FulfillmentItemList+ rows={withPriceSource(fulfillmentItemRows(fulfillment, order.items ?? []), order)}+ />{shippable && (<CardFooter className="justify-end gap-2 py-3">@@ -741,7 +759,15 @@ function FulfillmentRow({ order, fulfillment }: { order: Order; fulfillment: Ful* so the eye can compare it against the real ones, minus the status and number* it does not have.*/-function UnfulfilledItems({ rows, canCreate }: { rows: FulfillmentItemRow[]; canCreate: boolean }) {+function UnfulfilledItems({+ rows,+ order,+ canCreate,+}: {+ rows: FulfillmentItemRow[]+ order: Order+ canCreate: boolean+}) {const { t } = useTranslation()const totalUnits = rows.reduce((sum, row) => sum + row.quantity, 0)@@ -762,7 +788,7 @@ function UnfulfilledItems({ rows, canCreate }: { rows: FulfillmentItemRow[]; can</span></div>- <FulfillmentItemList rows={rows} />+ <FulfillmentItemList rows={withPriceSource(rows, order)} /></div>)}@@ -822,7 +848,7 @@ export function FulfillmentsCard({ order }: { order: Order }) {) : (<CardContent className="flex flex-col gap-4">{unfulfilled.length > 0 && (- <UnfulfilledItems rows={unfulfilled} canCreate={canCreate} />+ <UnfulfilledItems rows={unfulfilled} order={order} canCreate={canCreate} />)}{fulfillments.map((fulfillment) => (<FulfillmentRow key={fulfillment.id} order={order} fulfillment={fulfillment} />diff --git a/packages/dashboard/src/components/spree/orders/line-item-price-source.tsx b/packages/dashboard/src/components/spree/orders/line-item-price-source.tsxnew file mode 100644index 0000000000..0247ff2009--- /dev/null+++ b/packages/dashboard/src/components/spree/orders/line-item-price-source.tsx@@ -0,0 +1,44 @@+import type { LineItem } from '@spree/admin-sdk'+import { useStore } from '@spree/dashboard-core'+import { Link } from '@tanstack/react-router'+import { useTranslation } from 'react-i18next'++/**+ * Which agreement priced this line, as a link to it. The price list is the+ * one stamped on the line, never re-resolved; the catalog is that list's+ * current owner.+ */+export function LineItemPriceSource({ lineItem }: { lineItem: LineItem }) {+ const { t } = useTranslation()+ const { storeId } = useStore()++ // A list a catalog owns is the catalog, a standalone list stands for+ // itself, and a shop-price or hand-negotiated line has nothing to point at.+ if (lineItem.catalog_id) {+ return (+ <Link+ to="/$storeId/products/catalogs/$catalogId"+ params={{ storeId, catalogId: lineItem.catalog_id }}+ className="hover:text-foreground hover:underline"+ >+ {t('admin.orders.detail.priced_by', {+ name: lineItem.catalog_name ?? lineItem.catalog_id,+ })}+ </Link>+ )+ } else if (lineItem.price_list_id) {+ return (+ <Link+ to="/$storeId/products/price-lists/$priceListId"+ params={{ storeId, priceListId: lineItem.price_list_id }}+ className="hover:text-foreground hover:underline"+ >+ {t('admin.orders.detail.priced_by', {+ name: lineItem.price_list_name ?? lineItem.price_list_id,+ })}+ </Link>+ )+ } else {+ return null+ }+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex a206e57c34..63625628bc 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2907,6 +2907,7 @@"shared_help": "دُفعت مرة واحدة لسلة تضم عدة بائعين. هذا الطلب له حصة منها.","load_error": "تعذر تحميل مدفوعات هذا الطلب."},+ "priced_by": "التسعير من {{name}}","purchase_order": {"document": "مستند أمر الشراء","document_help": "ملف PDF أو صورة أو Word، بحد أقصى 10 ميغابايت.",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex bf48095cef..4261a322a5 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2890,6 +2890,7 @@"shared_help": "Einmal bezahlt für einen Warenkorb mehrerer Verkäufer. Diese Bestellung hat einen Anteil daran.","load_error": "Die Zahlungen für diese Bestellung konnten nicht geladen werden."},+ "priced_by": "Preis von {{name}}","purchase_order": {"document": "Bestelldokument","document_help": "PDF-, Bild- oder Word-Datei, bis zu 10 MB.",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex f5f0326607..6f632110e5 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2890,6 +2890,7 @@"shared_help": "Paid once for a basket spanning several sellers. This order has a share of it.","load_error": "Could not load the payments for this order."},+ "priced_by": "Priced by {{name}}","purchase_order": {"document": "Purchase order document","document_help": "PDF, image or Word file, up to 10 MB.",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 8057685069..34da68f6ed 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2890,6 +2890,7 @@"shared_help": "Payé en une fois pour un panier réparti entre plusieurs vendeurs. Cette commande en détient une part.","load_error": "Impossible de charger les paiements de cette commande."},+ "priced_by": "Tarifé par {{name}}","purchase_order": {"document": "Document de bon de commande","document_help": "Fichier PDF, image ou Word, jusqu’à 10 Mo.",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 2dbe5569b7..09c221d89b 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2916,6 +2916,7 @@"shared_help": "Zapłacone raz za koszyk obejmujący kilku sprzedawców. To zamówienie ma w nim udział.","load_error": "Nie udało się wczytać płatności tego zamówienia."},+ "priced_by": "Cena z {{name}}","purchase_order": {"document": "Dokument zamówienia zakupu","document_help": "Plik PDF, obraz lub dokument Word, do 10 MB.",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 9317a65b4f..9c76e6ddd4 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2882,6 +2882,7 @@"shared_help": "该购物车横跨多个卖家,只支付了一次。本订单占其中一部分。","load_error": "无法加载此订单的付款信息。"},+ "priced_by": "定价来自 {{name}}","purchase_order": {"document": "采购订单文件","document_help": "PDF、图片或 Word 文件,最大 10 MB。",diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rbindex 5d864878ee..ca946761fa 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb@@ -150,11 +150,13 @@ module Spreeend# Override scope — Order uses SingleStoreResource (for_store).- # Variant prices are preloaded here rather than via scope_includes,- # which this override bypasses; the serializer reads them per row.+ # Variant prices and each line's price list are named here rather+ # than via scope_includes, which this override bypasses; the+ # serializer reads both per row.def scopebase = current_store.orders.accessible_by(current_ability, :show).- includes(line_items: { variant: :prices }).preload_associations_lazily+ includes(line_items: [{ variant: :prices }, { price_list: :catalog }]).+ preload_associations_lazily# Transient completion drafts (status draft + cart_id set) belong# to in-flight checkouts, never to the admin. Admin drafts are the@@ -190,7 +192,10 @@ module Spree# only its id is reported and that comes off the order's own column.# Variant prices ride along because the admin line-item serializer# reads the base catalog price for every row (the negotiated-price- # comparison); without it each line costs its own price query.+ # comparison); without it each line costs its own price query. Each+ # line's price list and its catalog are named for the same reason —+ # stated rather than left to ar_lazy_preload, which happens to cover+ # them today.def collection_includes# `market` is the withdrawal deadline's other input. Fulfillments# are loaded with their selected rate because the freight summary@@ -198,7 +203,8 @@ module Spree# fulfillment for a field that is nil on every parcel order.[:customer, :channel, :seller, :external_references, :cancel_reason,:market, { fulfillments: :selected_delivery_rate },- { line_items: { variant: :prices } }, { po_document_attachment: :blob }]+ { line_items: [{ variant: :prices }, { price_list: :catalog }] },+ { po_document_attachment: :blob }]end# Read through the store's own vocabulary, so a reason belonging todiff --git a/spree/api/app/serializers/spree/api/v3/admin/line_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/line_item_serializer.rbindex d8de9b8936..ef12565c43 100644--- a/spree/api/app/serializers/spree/api/v3/admin/line_item_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/line_item_serializer.rb@@ -20,7 +20,11 @@ module Spreecost_price: [:string, nullable: true],tax_category_id: [:string, nullable: true],price_source: [:string, nullable: true],- catalog_price: [:string, nullable: true]+ catalog_price: [:string, nullable: true],+ price_list_id: [:string, nullable: true],+ price_list_name: [:string, nullable: true],+ catalog_id: [:string, nullable: true],+ catalog_name: [:string, nullable: true]# price_source is operational provenance — admin-only, never on the# store serializer.@@ -33,6 +37,29 @@ module Spreeline_item.variant&.amount_in(line_item.currency)&.to_send+ # Which agreement priced this line. The list id is stamped on the+ # row and never re-resolved (the same reason `catalog_price` above+ # is a base price); the catalog is whichever one owns that list+ # now, so moving a list between catalogs re-labels past orders.+ # Empty on a shop-price or hand-negotiated line. Names ride along+ # beside the ids so a page of lines does not cost a request each to+ # label, as `company_name` already does.+ attribute :price_list_id do |line_item|+ line_item.price_list&.prefixed_id+ end++ attribute :price_list_name do |line_item|+ line_item.price_list&.name+ end++ attribute :catalog_id do |line_item|+ line_item.price_list&.catalog&.prefixed_id+ end++ attribute :catalog_name do |line_item|+ line_item.price_list&.catalog&.name+ end+attribute :cost_price do |line_item|line_item.cost_price&.to_senddiff --git a/spree/api/spec/serializers/spree/api/v3/admin/line_item_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/line_item_serializer_spec.rbindex 3207f9033a..64afaf40c1 100644--- a/spree/api/spec/serializers/spree/api/v3/admin/line_item_serializer_spec.rb+++ b/spree/api/spec/serializers/spree/api/v3/admin/line_item_serializer_spec.rb@@ -54,6 +54,57 @@ RSpec.describe Spree::Api::V3::Admin::LineItemSerializer doendend+ # Which agreement charged this line, so an operator reading an order can+ # open it rather than guessing which of a company's catalogs applied+ # (V-3635).+ describe 'the agreement that priced the line' do+ let(:catalog) { create(:catalog, store: store, name: 'Wholesale tier 2') }+ let(:price_list) { create(:price_list, store: store, name: 'Tier 2 prices', catalog: catalog) }++ it 'names the catalog and its list, with prefixed ids' do+ line_item.update_columns(price_list_id: price_list.id)++ expect(subject['price_list_id']).to eq(price_list.prefixed_id)+ expect(subject['price_list_name']).to eq('Tier 2 prices')+ expect(subject['catalog_id']).to eq(catalog.prefixed_id)+ expect(subject['catalog_name']).to eq('Wholesale tier 2')+ end++ it 'names only the list when it belongs to no catalog' do+ standalone = create(:price_list, store: store, name: 'Clearance')+ line_item.update_columns(price_list_id: standalone.id)++ expect(subject['price_list_name']).to eq('Clearance')+ expect(subject['catalog_id']).to be_nil+ expect(subject['catalog_name']).to be_nil+ end++ it 'is empty for a line charged the shop price' do+ expect(subject['price_list_id']).to be_nil+ expect(subject['catalog_id']).to be_nil+ end++ # Destroying a catalog soft-deletes its owned list, and a paranoid record+ # drops out of its association — which would blank the provenance on every+ # past order the agreement priced, the one thing it exists to keep.+ it 'still names the list after its catalog is deleted' do+ line_item.update_columns(price_list_id: price_list.id)+ catalog.destroy++ expect(subject['price_list_id']).to eq(price_list.prefixed_id)+ expect(subject['price_list_name']).to eq('Tier 2 prices')+ end++ it 'stays off the store serializer, like every other provenance field' do+ line_item.update_columns(price_list_id: price_list.id)++ store_result = Spree::Api::V3::LineItemSerializer.new(line_item, params: base_params).to_h++ expect(store_result).not_to have_key('price_list_id')+ expect(store_result).not_to have_key('catalog_id')+ end+ end+# `seller_id` itself is covered on the store serializer this one extends.describe 'seller expand' doit 'resolves the operator view rather than the public profile' dodiff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rbindex f62627ffa0..092c58c14a 100644--- a/spree/core/app/models/spree/catalog.rb+++ b/spree/core/app/models/spree/catalog.rb@@ -14,8 +14,9 @@ module Spree# catalog to those companies or divisions rather than to a group.## Within whichever audience answered, visibility is the union of its- # catalogs' assortments and pricing takes the price list of the nearest- # assignment first (docs/plans/6.0-b2b-companies-and-catalogs.md).+ # catalogs' assortments; pricing walks the assigning nodes nearest first and+ # within one node charges the best price any of its catalogs gives+ # (docs/plans/6.0-b2b-companies-and-catalogs.md).class Catalog < Spree.base_classhas_prefix_id :cat@@ -97,6 +98,17 @@ module Spree# @param company [Spree::Company, nil]# @return [Array<Spree::Catalog>]def self.for_company(company)+ groups_for_company(company).flatten+ end++ # The same catalogs, grouped by the node that assigns them, nearest first.+ # Only pricing needs the boundaries: catalogs sharing a node rank equally+ # and the best price among them wins, while a nearer node outranks a+ # further one. Everything else takes the flat {.for_company}.+ #+ # @param company [Spree::Company, nil]+ # @return [Array<Array<Spree::Catalog>>]+ def self.groups_for_company(company)return [] if company.nil?nodes = company.self_and_ancestors@@ -110,9 +122,15 @@ module Spreeincludes(:catalog).group_by(&:assignable_id)- nodes.flat_map do |node|- Array(assignments[node.id]).map(&:catalog).select(&:active?).sort_by { |catalog| catalog.position.to_i }- end.uniq+ # A catalog assigned to a node and to an ancestor answers from the nearer.+ seen = Set.new++ nodes.filter_map do |node|+ group = Array(assignments[node.id]).map(&:catalog).+ select { |catalog| catalog.active? && seen.add?(catalog.id) }.+ sort_by { |catalog| catalog.position.to_i }+ group.presence+ endend# The catalogs assigned to any of the given customer groups, by position.@@ -151,18 +169,30 @@ module Spree# @param channel [Spree::Channel, nil]# @return [Array<Spree::Catalog>]def self.for_context(store:, company: nil, user: nil, channel: nil)+ groups_for_context(store: store, company: company, user: user, channel: channel).flatten+ end++ # The same resolution, grouped by precedence rank ({.groups_for_company}).+ # Only the company axis has more than one rank.+ #+ # @return [Array<Array<Spree::Catalog>>]+ def self.groups_for_context(store:, company: nil, user: nil, channel: nil)return [] if store.nil?- catalogs = store.catalogs.for_company(company)+ groups = store.catalogs.groups_for_company(company)+# Only when the company axis found nothing: a buyer purchasing for a# company is on that company's agreement, and adding their personal# segment's catalogs on top would price one buyer under two agreements# at once.- if catalogs.empty? && user- groups = user.try(:customer_groups)&.where(store_id: store.id) || []- catalogs = store.catalogs.for_customer_groups(groups)+ if groups.empty? && user+ customer_groups = user.try(:customer_groups)&.where(store_id: store.id) || []+ groups = [store.catalogs.for_customer_groups(customer_groups).presence].compactend- catalogs = [channel&.default_catalog].compact.select(&:active?) if catalogs.empty?++ groups = [[channel&.default_catalog].compact.select(&:active?).presence].compact if groups.empty?++ catalogs = groups.flatten# Pricing reads each catalog's price list, and the list's contextual# rules decide whether it applies to the quantity being bought; without# this the walk is one query per catalog again, plus one per list.@@ -171,7 +201,7 @@ module Spreerecords: catalogs, associations: { price_list: [:price_rules, :price_adjustment_tiers] }).callend- catalogs+ groupsend# The catalogs applying to a buyer, resolving the company for them when@@ -190,15 +220,22 @@ module Spree# @param channel [Spree::Channel, nil]# @return [Array<Spree::Catalog>]def self.for_buyer(store:, customer: nil, company: nil, channel: nil)+ groups_for_buyer(store: store, customer: customer, company: company, channel: channel).flatten+ end++ # {.for_buyer}, grouped by precedence rank. What pricing walks.+ #+ # @return [Array<Array<Spree::Catalog>>]+ def self.groups_for_buyer(store:, customer: nil, company: nil, channel: nil)return [] if store.nil?if store == Spree::Current.storecompany ||= Spree::Current.standing_company_for(customer)channel ||= Spree::Current.channel- Spree::Current.catalogs_for(company: company, user: customer, channel: channel)+ Spree::Current.catalog_groups_for(company: company, user: customer, channel: channel)elsecompany ||= Spree::Company.sole_standing_for(store: store, customer: customer)- for_context(store: store, company: company, user: customer, channel: channel)+ groups_for_context(store: store, company: company, user: customer, channel: channel)endenddiff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rbindex 996fb63164..8dc8f1d8bd 100644--- a/spree/core/app/models/spree/current.rb+++ b/spree/core/app/models/spree/current.rb@@ -4,7 +4,7 @@ module Spree# All attributes are automatically reset between requests by Rails.# Fallback chains ensure sensible defaults when attributes are not explicitly set.class Current < ::ActiveSupport::CurrentAttributes- attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :applicable_catalogs, :quantity_rules_resolvers, :standing_companies, :global_pricing_context, :provider_cache, :integrations+ attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :applicable_catalogs, :applicable_catalog_groups, :quantity_rules_resolvers, :standing_companies, :global_pricing_context, :provider_cache, :integrations# Scratch space for provider strategies to memoize a call across the# request — part of the delivery rate provider contract (nothing in core@@ -103,16 +103,22 @@ module Spree# @param channel [Spree::Channel, nil]# @return [Array<Spree::Catalog>]def catalogs_for(company: nil, user: nil, channel: nil)- channel ||= self.channel- # Normalized before the key is built, not just before the query: the- # key is an id, so an admin and a customer sharing one would otherwise- # share an entry and whichever resolved first would decide for both.- # Only a customer has customer-group catalogs to resolve.- user = nil unless user.is_a?(Spree.customer_class)-- key = [store&.id, company&.id, user&.id, channel&.id]- applicable_catalogs[key] ||= Spree::Catalog.for_context(- store: store, company: company, user: user, channel: channel+ key = catalog_memo_key(company: company, user: user, channel: channel)+ applicable_catalogs[key] ||= catalog_groups_for(company: company, user: user, channel: channel).flatten+ end++ # The same catalogs grouped by precedence rank, which is what pricing+ # walks ({Spree::Catalog.groups_for_company}). The resolved form — the+ # flat set above is a cached flattening of it, never a second resolution.+ #+ # @param company [Spree::Company, nil]+ # @param user [Object, nil]+ # @param channel [Spree::Channel, nil]+ # @return [Array<Array<Spree::Catalog>>]+ def catalog_groups_for(company: nil, user: nil, channel: nil)+ key = catalog_memo_key(company: company, user: user, channel: channel)+ applicable_catalog_groups[key] ||= Spree::Catalog.groups_for_context(+ store: store, company: company, user: normalized_catalog_user(user), channel: channel || self.channel)end@@ -121,6 +127,11 @@ module Spreesuper || (self.applicable_catalogs = {})end+ # @return [Hash]+ def applicable_catalog_groups+ super || (self.applicable_catalog_groups = {})+ end+# The quantity-rule resolver for a buyer in this request, keyed the same# way their catalogs are.#@@ -133,8 +144,7 @@ module Spree# @param channel [Spree::Channel, nil]# @return [Spree::Catalogs::ResolveQuantityRules]def quantity_rules_resolver_for(company: nil, user: nil, channel: nil)- channel ||= self.channel- key = [store&.id, company&.id, user&.id, channel&.id]+ key = catalog_memo_key(company: company, user: user, channel: channel)quantity_rules_resolvers[key] ||= Spree::Catalogs::ResolveQuantityRules.new(catalogs_for(company: company, user: user, channel: channel))@@ -176,6 +186,7 @@ module Spree# @return [void]def reset_catalog_memosself.applicable_catalogs = nil+ self.applicable_catalog_groups = nilself.quantity_rules_resolvers = nilself.standing_companies = nilself.price_lists = nil@@ -194,5 +205,22 @@ module Spree)endend++ private++ # One key for every buyer-derived memo, so they cannot drift apart.+ #+ # @return [Array]+ def catalog_memo_key(company: nil, user: nil, channel: nil)+ [store&.id, company&.id, normalized_catalog_user(user)&.id, (channel || self.channel)&.id]+ end++ # Normalized before the key is built, not just before the query: the key+ # is an id, so an admin and a customer sharing one would share an entry.+ #+ # @return [Object, nil]+ def normalized_catalog_user(user)+ user if user.is_a?(Spree.customer_class)+ endendenddiff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rbindex 99c43fd277..9003db067d 100644--- a/spree/core/app/models/spree/line_item.rb+++ b/spree/core/app/models/spree/line_item.rb@@ -17,7 +17,7 @@ module Spreebelongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'endbelongs_to :tax_category, -> { with_deleted }, class_name: 'Spree::TaxCategory', optional: true- belongs_to :price_list, class_name: 'Spree::PriceList', optional: true+ belongs_to :price_list, -> { with_deleted }, class_name: 'Spree::PriceList', optional: true# Snapshotted from the variant when the line is added — see copy_seller.# Nil is the operator's own first-party item.belongs_to :seller, class_name: 'Spree::Seller', optional: truediff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rbindex 7b469d2fd0..d3456508fa 100644--- a/spree/core/app/models/spree/pricing_provider/internal.rb+++ b/spree/core/app/models/spree/pricing_provider/internal.rb@@ -45,7 +45,12 @@ module Spree# back to base.# @return [Spree::Price]def find_price_from_lists- (catalog_price_lists + applicable_price_lists).each do |price_list|+ catalog_price_list_groups.each do |price_lists|+ price = best_price_among(price_lists)+ return price if price+ end++ applicable_price_lists.each do |price_list|price = find_price_for_list(price_list)return price if priceend@@ -53,12 +58,25 @@ module Spreenilend- # Price lists reached through the buyer's effective catalogs, in- # catalog resolution order — the company subtree, or failing that the- # customer's groups, or failing that the channel's default catalog.- # The same chain visibility uses, and its steps are alternatives: a- # company buyer is priced by their company's agreement and never- # also by their customer group's ({Spree::Catalog.for_context}).+ # The cheapest price one node's lists give, nil when none prices this+ # variant. Catalogs sharing a node rank equally, so taking the first to+ # answer charged a company from whichever sorted first rather than the+ # cheaper (docs/plans/6.0-b2b-companies-and-catalogs.md). Equal amounts+ # keep list order, so the answer is stable.+ #+ # @param price_lists [Array<Spree::PriceList>]+ # @return [Spree::Price, nil]+ def best_price_among(price_lists)+ price_lists.filter_map { |price_list| find_price_for_list(price_list) }.min_by(&:amount)+ end++ # Price lists reached through the buyer's effective catalogs, grouped+ # by the node that assigns them and ordered nearest node first — the+ # company subtree, or failing that the customer's groups, or failing+ # that the channel's default catalog. The same chain visibility uses,+ # and its steps are alternatives: a company buyer is priced by their+ # company's agreement and never also by their customer group's+ # ({Spree::Catalog.groups_for_context}).## A catalog-attached list applies because the catalog applies: its# audience rules are not consulted, since the assignment already@@ -68,10 +86,13 @@ module Spree# volume pricing is (docs/plans/6.0-price-list-automatic-pricing.md).# Status and dates gate the list as before.#- # @return [Array<Spree::PriceList>]- def catalog_price_lists- @catalog_price_lists ||= catalogs_for_context.filter_map(&:price_list).uniq.select do |price_list|- price_list.currently_active? && price_list.contextual_rules_applicable?(context)+ # @return [Array<Array<Spree::PriceList>>]+ def catalog_price_list_groups+ @catalog_price_list_groups ||= catalog_groups_for_context.filter_map do |catalogs|+ lists = catalogs.filter_map(&:price_list).select do |price_list|+ price_list.currently_active? && price_list.contextual_rules_applicable?(context)+ end+ lists.presenceendend@@ -89,11 +110,12 @@ module Spree# Catalogs that apply to this buyer, through the one entry point# visibility and quantity terms also use — what a buyer is shown, what# they pay and how much they must take have to come from the same- # agreement. Reuses the request-scoped set for the current store, so a+ # agreement. Grouped by assigning node, since that is where precedence+ # lives. Reuses the request-scoped set for the current store, so a# listing does not re-resolve the same buyer per variant.- # @return [Array<Spree::Catalog>]- def catalogs_for_context- Spree::Catalog.for_buyer(+ # @return [Array<Array<Spree::Catalog>>]+ def catalog_groups_for_context+ Spree::Catalog.groups_for_buyer(store: context.store, customer: context.user,company: context.company, channel: context.channel)diff --git a/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb b/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rbindex f05ebb976a..ec0c7e48eb 100644--- a/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb+++ b/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb@@ -13,9 +13,9 @@ describe 'catalog-aware pricing' doprice_listend- def resolve(company: nil, user: nil)+ def resolve(company: nil, user: nil, quantity: nil)context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', store: store,- user: user, company: company)+ user: user, company: company, quantity: quantity)Spree::Pricing::PriceResolution.call(context)end@@ -43,6 +43,79 @@ describe 'catalog-aware pricing' doexpect(resolve(company: company).amount).to eq(90)end+ # A division's own agreement is the one it negotiated, so it answers even+ # when the group-wide catalog above it happens to be cheaper. Precedence+ # between nodes is real; precedence within a node is not (see below).+ it 'keeps the nearest node even when the parent catalog is cheaper' do+ parent_catalog = create(:catalog, store: store, price_list: price_list_with_price(70))+ own_catalog = create(:catalog, store: store, price_list: price_list_with_price(90))+ create(:catalog_assignment, catalog: parent_catalog, assignable: company)+ create(:catalog_assignment, catalog: own_catalog, assignable: division)++ expect(resolve(company: division).amount).to eq(90)+ end++ # Two catalogs on one node rank equally: nothing about either assignment+ # says which agreement a company is on, so the buyer pays the better of the+ # two. Catalog position orders the admin listing and must not decide money —+ # it used to, so reordering that screen silently overcharged a company+ # (V-3635).+ context 'when one company carries two catalogs' do+ let!(:shallow) do+ catalog = create(:catalog, store: store, price_list: price_list_with_price(95), position: 1)+ create(:catalog_assignment, catalog: catalog, assignable: company)+ catalog+ end++ let!(:deep) do+ price_list = price_list_with_price(85)+ create(:price, variant: variant, currency: 'USD', amount: 50, min_quantity: 24, price_list: price_list)+ catalog = create(:catalog, store: store, price_list: price_list, position: 2)+ create(:catalog_assignment, catalog: catalog, assignable: company)+ catalog+ end++ it 'charges the best price either of them gives' do+ expect(resolve(company: company).amount).to eq(85)+ expect(resolve(company: company, quantity: 24).amount).to eq(50)+ end++ it 'answers the same whichever catalog sorts first' do+ before_swap = resolve(company: company, quantity: 24).amount++ shallow.update!(position: 2)+ deep.update!(position: 1)+ Spree::Current.reset_catalog_memos++ expect(resolve(company: company, quantity: 24).amount).to eq(before_swap)+ end++ # The cheaper catalog prices this variant and the dearer one does not, so+ # there is nothing to compare — the node still answers rather than falling+ # through to the base price.+ it 'answers from the only catalog that prices the variant' do+ deep.price_list.prices.destroy_all++ expect(resolve(company: company, quantity: 24).amount).to eq(95)+ end+ end++ it 'charges the best price across several customer group catalogs' do+ customer = create(:customer)+ dearer_group = create(:customer_group, store: store)+ cheaper_group = create(:customer_group, store: store)+ dearer_group.customer_group_users.create!(customer: customer)+ cheaper_group.customer_group_users.create!(customer: customer)+ create(:catalog_assignment,+ catalog: create(:catalog, store: store, price_list: price_list_with_price(90), position: 1),+ assignable: dearer_group)+ create(:catalog_assignment,+ catalog: create(:catalog, store: store, price_list: price_list_with_price(75), position: 2),+ assignable: cheaper_group)++ expect(resolve(user: customer).amount).to eq(75)+ end+# A price list attached to a catalog is audience-scoped by the catalog; a# rule-less one must not leak to every shopper through the generic matcher.it 'hides a catalog price list from buyers outside the audience' do