Skip to content

armgit / spree

Public Imported from GitHub
0

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

Add catalogs: assortment plus optional price list, assigned to audiences

Damian Legawiec6ee0a071d290
diff --git a/spree/api/app/controllers/spree/api/v3/admin/catalog_assignments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalog_assignments_controller.rb
new file mode 100644
index 0000000000..5df943b32e
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/catalog_assignments_controller.rb
@@ -0,0 +1,27 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Withdrawing a catalog from an audience, addressed by assignment id.
+ class CatalogAssignmentsController < ResourceController
+ scoped_resource :products
+
+ protected
+
+ def model_class
+ Spree::CatalogAssignment
+ end
+
+ def serializer_class
+ Spree.api.admin_catalog_assignment_serializer
+ end
+
+ def scope
+ Spree::CatalogAssignment.where(catalog_id: current_store.catalogs.select(:id)).
+ accessible_by(current_ability, ability_action_for_request)
+ end
+ end
+ end
+ end
+ end
+end
diff --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.rb
new file mode 100644
index 0000000000..f8ea09a69f
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/catalogs/products_controller.rb
@@ -0,0 +1,93 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Catalogs
+ # The products curated into a catalog's assortment. Listing is
+ # ordered by the CatalogProduct position so the merchant's manual
+ # ordering round-trips; +reposition+ persists a drag-to-reorder.
+ class ProductsController < ResourceController
+ include Spree::Api::V3::Admin::ProductListing
+
+ scoped_resource :products
+
+ # Skip the base single-resource load — membership actions resolve
+ # the product against the catalog's scope themselves.
+ skip_before_action :set_resource
+ before_action :set_product, only: [:destroy, :reposition]
+
+ # POST /api/v3/admin/catalogs/:catalog_id/products
+ # Body: { product_ids: ['prod_…', …] } — bulk add, skipping rows
+ # already present.
+ def create
+ product_ids = Array(params.require(:product_ids)).map do |id|
+ Spree::Product.decode_prefixed_id(id) || id
+ end
+ added = @parent_catalog.add_products(product_scope.where(id: product_ids).ids)
+
+ render json: { added_count: added }, status: :created
+ end
+
+ # DELETE /api/v3/admin/catalogs/:catalog_id/products/:id
+ def destroy
+ @parent_catalog.catalog_products.where(product_id: @product.id).destroy_all
+ head :no_content
+ end
+
+ # PATCH /api/v3/admin/catalogs/:catalog_id/products/:id/reposition
+ # Body: { new_position: 0 } — 0-based index within the assortment.
+ def reposition
+ position = integer_param(:new_position)
+ return render_invalid_position if position.nil?
+
+ @parent_catalog.catalog_products.find_by(product_id: @product.id).insert_at(position + 1)
+ head :no_content
+ end
+
+ protected
+
+ def model_class
+ Spree::Product
+ end
+
+ def serializer_class
+ Spree.api.admin_product_serializer
+ end
+
+ # The catalog's assortment, in the merchant's manual order.
+ def scope
+ product_scope.
+ joins(:catalog_products).
+ where(Spree::CatalogProduct.table_name => { catalog_id: @parent_catalog.id }).
+ order(Spree::CatalogProduct.table_name => { position: :asc })
+ end
+
+ # A product is curated at most once per catalog (unique
+ # [catalog_id, product_id]), so the join can't duplicate rows —
+ # DISTINCT is unnecessary and breaks Postgres ordering by position.
+ def collection_distinct?
+ false
+ end
+
+ def set_parent
+ @parent_catalog = current_store.catalogs.
+ accessible_by(current_ability, parent_ability_action).
+ find_by_prefix_id!(params[:catalog_id])
+ authorize_parent!(@parent_catalog)
+ end
+
+ private
+
+ def set_product
+ @product = scope.find_by_prefix_id!(params[:id])
+ end
+
+ def product_scope
+ current_store.products.accessible_by(current_ability, :show)
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb
new file mode 100644
index 0000000000..037e429e5f
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/catalogs_controller.rb
@@ -0,0 +1,81 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Catalogs — assortment + optional price list, shown to an audience
+ # through assignments. Merchandising data, so it answers to the
+ # products scopes.
+ class CatalogsController < ResourceController
+ scoped_resource :products
+
+ before_action :set_resource, only: [:show, :update, :destroy, :assign]
+
+ # POST /api/v3/admin/catalogs/:id/assign — { assignable_type, assignable_id }
+ def assign
+ authorize! :update, @resource
+
+ assignment = @resource.catalog_assignments.new(assignable: find_assignable)
+
+ if assignment.save
+ render json: Spree.api.admin_catalog_assignment_serializer.new(
+ assignment, params: serializer_params
+ ).to_h, status: :created
+ else
+ render_validation_error(assignment.errors)
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::Catalog
+ end
+
+ def serializer_class
+ Spree.api.admin_catalog_serializer
+ end
+
+ def scope
+ super.for_store(current_store)
+ end
+
+ def collection_includes
+ [:catalog_products, :price_list]
+ end
+
+ def permitted_params
+ permitted = params.permit(*model_additional_permitted_attributes,
+ :name, :active, :position, :price_list_id, metadata: {})
+ if permitted.key?(:price_list_id)
+ permitted[:price_list_id] =
+ if permitted[:price_list_id].present?
+ current_store.price_lists.find_by_prefix_id!(permitted[:price_list_id]).id
+ else
+ nil
+ end
+ end
+ permitted
+ end
+
+ private
+
+ # The audience vocabulary is closed; each type resolves through the
+ # store so another tenant's record is a 404, never an assignment.
+ ASSIGNABLE_SCOPES = {
+ 'company' => ->(store) { store.companies },
+ 'channel' => ->(store) { store.channels },
+ 'customer_group' => ->(store) { Spree::CustomerGroup.for_store(store) },
+ 'market' => ->(store) { store.markets }
+ }.freeze
+
+ def find_assignable
+ scope_builder = ASSIGNABLE_SCOPES[params.require(:assignable_type).to_s]
+ raise ActiveRecord::RecordNotFound if scope_builder.nil?
+
+ scope_builder.call(current_store).find_by_prefix_id!(params.require(:assignable_id))
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
index 8a56f13598..55a4b4388a 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/channels_controller.rb
@@ -67,6 +67,7 @@ module Spree
def permitted_params
params.permit(*model_additional_permitted_attributes, :name, :code, :active, :default, :preferred_order_routing_strategy,
:preferred_storefront_access, :preferred_guest_checkout,
+ :default_catalog_id,
stock_location_ids: [])
end
@@ -76,6 +77,16 @@ module Spree
def assignable_params
attributes = permitted_params.except(:stock_location_ids)
+ # An incidental lookup like any other: a foreign catalog 404s.
+ if attributes.key?(:default_catalog_id)
+ attributes[:default_catalog_id] =
+ if attributes[:default_catalog_id].present?
+ current_store.catalogs.find_by_prefix_id!(attributes[:default_catalog_id]).id
+ else
+ nil
+ end
+ end
+
if params.key?(:stock_location_ids)
attributes[:stock_locations] = Array(params[:stock_location_ids]).map do |id|
current_store.stock_locations.accessible_by(current_ability, :show).find_by_prefix_id!(id)
diff --git a/spree/api/app/serializers/spree/api/v3/admin/catalog_assignment_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/catalog_assignment_serializer.rb
new file mode 100644
index 0000000000..efbafa9d7c
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/catalog_assignment_serializer.rb
@@ -0,0 +1,32 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class CatalogAssignmentSerializer < V3::BaseSerializer
+ typelize catalog_id: :string, assignable_type: :string, assignable_id: :string,
+ assignable_name: [:string, nullable: true]
+
+ attributes created_at: :iso8601
+
+ attribute :catalog_id do |assignment|
+ assignment.catalog.prefixed_id
+ end
+
+ # The client-facing type vocabulary: 'company', 'channel',
+ # 'customer_group', 'market' — never Ruby class names.
+ attribute :assignable_type do |assignment|
+ assignment.assignable_type.demodulize.underscore
+ end
+
+ attribute :assignable_id do |assignment|
+ assignment.assignable&.prefixed_id
+ end
+
+ attribute :assignable_name do |assignment|
+ assignment.assignable.try(:name)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rb
new file mode 100644
index 0000000000..e0eda60760
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/catalog_serializer.rb
@@ -0,0 +1,31 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Admin-only: catalogs are merchandising configuration with no
+ # storefront surface — buyers see their effects, never the record.
+ class CatalogSerializer < V3::BaseSerializer
+ typelize name: :string, active: :boolean, position: [:number, nullable: true],
+ price_list_id: [:string, nullable: true],
+ products_count: :number,
+ metadata: 'Record<string, unknown> | null'
+
+ attributes :name, :active, :position, :metadata,
+ created_at: :iso8601, updated_at: :iso8601
+
+ attribute :price_list_id do |catalog|
+ catalog.price_list&.prefixed_id
+ end
+
+ attribute :products_count do |catalog|
+ catalog.catalog_products.size
+ end
+
+ many :catalog_assignments, key: :assignments,
+ resource: proc { Spree.api.admin_catalog_assignment_serializer },
+ if: proc { expand?('assignments') }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb
index e72d147b5e..92f47bae91 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb
@@ -7,7 +7,8 @@ module Spree
preferred_order_routing_strategy: [:string, nullable: true],
preferred_storefront_access: [:string, nullable: true],
preferred_guest_checkout: [:boolean, nullable: true],
- stock_location_ids: [:string, multi: true]
+ stock_location_ids: [:string, multi: true],
+ default_catalog_id: [:string, nullable: true]
attributes :preferred_order_routing_strategy,
:preferred_storefront_access,
@@ -19,6 +20,12 @@ module Spree
attribute :stock_location_ids do |record|
record.stock_locations.map(&:prefixed_id)
end
+
+ # When set, only the default catalog's products are visible on this
+ # channel; unset means every publication.
+ attribute :default_catalog_id do |record|
+ record.default_catalog&.prefixed_id
+ end
end
end
end
diff --git a/spree/api/config/initializers/typelizer.rb b/spree/api/config/initializers/typelizer.rb
index ccbe24a6de..a17dee4d1a 100644
--- a/spree/api/config/initializers/typelizer.rb
+++ b/spree/api/config/initializers/typelizer.rb
@@ -26,7 +26,6 @@ Rails.application.config.after_initialize do
StockLevel StockMovement StockTransfer
Report Export Import ImportRow
TaxCategory Exchange ExchangeLineItem
- Company
].to_set
# Store SDK — no prefix, package provides namespace
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/catalog_assignments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/catalog_assignments_controller_spec.rb
new file mode 100644
index 0000000000..cff02bd073
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/catalog_assignments_controller_spec.rb
@@ -0,0 +1,29 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::CatalogAssignmentsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let(:catalog) { create(:catalog, store: store) }
+ let!(:assignment) { create(:catalog_assignment, catalog: catalog) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'DELETE #destroy' do
+ it 'withdraws the catalog from the audience' do
+ delete :destroy, params: { id: assignment.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(catalog.catalog_assignments.reload).to be_empty
+ end
+
+ it '404s an assignment of another store catalog' do
+ foreign = create(:catalog_assignment, catalog: create(:catalog, store: create(:store)))
+
+ delete :destroy, params: { id: foreign.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --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.rb
new file mode 100644
index 0000000000..cf9af6635d
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/catalogs/products_controller_spec.rb
@@ -0,0 +1,74 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::Catalogs::ProductsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:catalog) { create(:catalog, store: store) }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'lists the assortment in manual order' do
+ first = create(:catalog_product, catalog: catalog)
+ second = create(:catalog_product, catalog: catalog)
+ second.move_to_top
+
+ get :index, params: { catalog_id: catalog.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |row| row['id'] }).
+ to eq([second.product.prefixed_id, first.product.prefixed_id])
+ end
+
+ it '404s under another store catalog' 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
+
+ describe 'POST #create' do
+ it 'adds store products in bulk by prefixed id' do
+ product = create(:product, store: store)
+
+ post :create, params: { catalog_id: catalog.prefixed_id, product_ids: [product.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['added_count']).to eq(1)
+ expect(catalog.products.reload).to contain_exactly(product)
+ end
+
+ it 'silently drops products of another store' do
+ foreign = create(:product, store: create(:store))
+
+ post :create, params: { catalog_id: catalog.prefixed_id, product_ids: [foreign.prefixed_id] }, as: :json
+
+ expect(json_response['added_count']).to eq(0)
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'removes one product from the assortment' do
+ entry = create(:catalog_product, catalog: catalog)
+
+ delete :destroy, params: { catalog_id: catalog.prefixed_id, id: entry.product.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(catalog.catalog_products.reload).to be_empty
+ end
+ end
+
+ describe 'PATCH #reposition' do
+ it 'persists a drag-to-reorder' do
+ first = create(:catalog_product, catalog: catalog)
+ second = create(:catalog_product, catalog: catalog)
+
+ patch :reposition, params: { catalog_id: catalog.prefixed_id, id: second.product.prefixed_id, new_position: 0 }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(catalog.catalog_products.order(:position).map(&:id)).to eq([second.id, first.id])
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rb
new file mode 100644
index 0000000000..bb71a3e5e3
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/catalogs_controller_spec.rb
@@ -0,0 +1,109 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::CatalogsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:catalog) { create(:catalog, store: store, name: 'Wholesale') }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'lists the store catalogs with product counts' do
+ create(:catalog_product, catalog: catalog)
+
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ row = json_response['data'].first
+ expect(row['id']).to start_with('cat_')
+ expect(row['name']).to eq('Wholesale')
+ expect(row['products_count']).to eq(1)
+ end
+
+ it 'hides catalogs belonging to another store' do
+ other = create(:catalog, store: create(:store))
+
+ get :index, as: :json
+
+ expect(json_response['data'].map { |row| row['id'] }).not_to include(other.prefixed_id)
+ end
+ end
+
+ describe 'POST #create' do
+ it 'creates a catalog with a price list' do
+ price_list = create(:price_list, store: store)
+
+ post :create, params: { name: 'VIP', price_list_id: price_list.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['price_list_id']).to eq(price_list.prefixed_id)
+ end
+
+ it '404s a price list from another store' do
+ foreign = create(:price_list, store: create(:store))
+
+ post :create, params: { name: 'VIP', price_list_id: foreign.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'POST #assign' do
+ it 'assigns the catalog to a company node' do
+ company = create(:company, store: store)
+
+ post :assign, params: { id: catalog.prefixed_id, assignable_type: 'company', assignable_id: company.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['assignable_type']).to eq('company')
+ expect(json_response['assignable_id']).to eq(company.prefixed_id)
+ expect(json_response['assignable_name']).to eq(company.name)
+ end
+
+ it 'assigns to a customer group' do
+ group = create(:customer_group, store: store)
+
+ post :assign, params: { id: catalog.prefixed_id, assignable_type: 'customer_group', assignable_id: group.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:created)
+ end
+
+ it '404s an audience from another store' do
+ foreign = create(:company, store: create(:store))
+
+ post :assign, params: { id: catalog.prefixed_id, assignable_type: 'company', assignable_id: foreign.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it '404s an unknown audience type' do
+ post :assign, params: { id: catalog.prefixed_id, assignable_type: 'order', assignable_id: 'x' }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'rejects a duplicate assignment' do
+ company = create(:company, store: store)
+ create(:catalog_assignment, catalog: catalog, assignable: company)
+
+ post :assign, params: { id: catalog.prefixed_id, assignable_type: 'company', assignable_id: company.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'removes the catalog with its assortment and assignments' do
+ create(:catalog_product, catalog: catalog)
+ create(:catalog_assignment, catalog: catalog, assignable: create(:company, store: store))
+
+ delete :destroy, params: { id: catalog.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(Spree::CatalogProduct.count).to eq(0)
+ expect(Spree::CatalogAssignment.count).to eq(0)
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/catalogs_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/catalogs_spec.rb
new file mode 100644
index 0000000000..2fae7c79d9
--- /dev/null
+++ b/spree/api/spec/integration/spree/api/v3/admin/catalogs_spec.rb
@@ -0,0 +1,114 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+RSpec.describe 'Admin Catalogs API', type: :request, swagger_doc: 'api-reference/admin.yaml' do
+ include_context 'API v3 Admin'
+
+ let(:Authorization) { "Bearer #{admin_jwt_token}" }
+ let!(:catalog) { create(:catalog, store: store, name: 'Wholesale') }
+
+ path '/api/v3/admin/catalogs' do
+ get 'List catalogs' do
+ tags 'Catalogs'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description 'Returns the store catalogs — product assortments with an optional price list, shown to audiences through assignments.'
+ admin_scope :read, :products
+
+ admin_sdk_example 'catalogs/list'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+
+ response '200', 'catalogs found' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['data'].pluck('id')).to include(catalog.prefixed_id)
+ end
+ end
+ end
+
+ post 'Create a catalog' do
+ tags 'Catalogs'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description 'Creates a catalog. Add products and assign audiences (channel, customer group, market, or company subtree) afterwards.'
+ admin_scope :write, :products
+
+ admin_sdk_example 'catalogs/create'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ properties: {
+ name: { type: :string, example: 'VIP Assortment' },
+ active: { type: :boolean, example: true },
+ price_list_id: { type: :string, nullable: true,
+ description: 'Price list pricing this catalog; omit for assortment-only (base prices).',
+ example: 'pl_86Rf07xd4z' }
+ },
+ required: ['name']
+ }
+
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+
+ response '201', 'catalog created' do
+ let(:body) { { name: 'VIP Assortment' } }
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['name']).to eq('VIP Assortment')
+ end
+ end
+
+ response '422', 'invalid request' do
+ let(:body) { { active: true } }
+
+ run_test!
+ end
+ end
+ end
+
+ path '/api/v3/admin/catalogs/{id}/assign' do
+ post 'Assign a catalog to an audience' do
+ tags 'Catalogs'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description 'Shows the catalog to an audience. A company assignment covers the node and its whole subtree.'
+ admin_scope :write, :products
+
+ admin_sdk_example 'catalogs/assign'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :id, in: :path, type: :string, required: true
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ properties: {
+ assignable_type: { type: :string, enum: %w[channel customer_group market company],
+ example: 'company' },
+ assignable_id: { type: :string, example: 'comp_86Rf07xd4z' }
+ },
+ required: %w[assignable_type assignable_id]
+ }
+
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { catalog.prefixed_id }
+
+ response '201', 'catalog assigned' do
+ let!(:company) { create(:company, store: store) }
+ let(:body) { { assignable_type: 'company', assignable_id: company.prefixed_id } }
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['assignable_type']).to eq('company')
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rb
new file mode 100644
index 0000000000..82d3f8674a
--- /dev/null
+++ b/spree/core/app/models/spree/catalog.rb
@@ -0,0 +1,96 @@
+module Spree
+ # A product assortment with an optional pricing override, shown to a
+ # specific audience — a B2B tier, a VIP group, a regional selection.
+ #
+ # Who sees it is a {Spree::CatalogAssignment} (Channel, CustomerGroup,
+ # Market, or Company — where it covers the node's subtree). Visibility
+ # across several applicable catalogs is their union; pricing takes the
+ # attached price list of the nearest assignment first
+ # (docs/plans/6.0-b2b-companies-and-catalogs.md).
+ class Catalog < Spree.base_class
+ has_prefix_id :cat
+
+ include Spree::SingleStoreResource
+ include Spree::HasCustomFields
+ include Spree::Metadata
+
+ publishes_lifecycle_events
+
+ acts_as_list scope: :store_id
+
+ attribute :active, :boolean, default: true
+
+ belongs_to :store, class_name: 'Spree::Store', inverse_of: :catalogs
+ # nil = assortment-only; base prices apply.
+ belongs_to :price_list, class_name: 'Spree::PriceList', optional: true
+
+ has_many :catalog_products, class_name: 'Spree::CatalogProduct', dependent: :destroy,
+ inverse_of: :catalog
+ has_many :products, through: :catalog_products, class_name: 'Spree::Product'
+ has_many :catalog_assignments, class_name: 'Spree::CatalogAssignment', dependent: :destroy,
+ inverse_of: :catalog
+
+ validates :name, presence: true
+ validate :price_list_in_same_store
+
+ scope :active, -> { where(active: true) }
+ scope :by_position, -> { order(position: :asc) }
+
+ self.whitelisted_ransackable_attributes = %w[name active]
+
+ # The catalogs that apply to a purchase node, nearest node first: the
+ # node's own assignments before its parent's, catalog position breaking
+ # ties within a node. A parent's assignment covers the whole subtree, so a
+ # branch adds its own extra catalog without re-assigning the shared one.
+ #
+ # @param company [Spree::Company, nil]
+ # @return [Array<Spree::Catalog>]
+ def self.effective_for_company(company)
+ return [] if company.nil?
+
+ nodes = company.self_and_ancestors
+ assignments = Spree::CatalogAssignment.
+ where(assignable_type: 'Spree::Company', assignable_id: nodes.map(&:id)).
+ includes(: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
+ end
+
+ # The catalogs assigned to any of the given customer groups, by position.
+ #
+ # @param customer_groups [Enumerable<Spree::CustomerGroup>]
+ # @return [Array<Spree::Catalog>]
+ def self.effective_for_customer_groups(customer_groups)
+ ids = Array(customer_groups).map(&:id)
+ return [] if ids.empty?
+
+ Spree::CatalogAssignment.
+ where(assignable_type: 'Spree::CustomerGroup', assignable_id: ids).
+ includes(:catalog).
+ map(&:catalog).select(&:active?).sort_by { |catalog| catalog.position.to_i }.uniq
+ end
+
+ # Adds products to the assortment, appending to the manual order and
+ # skipping ones already present.
+ #
+ # @param product_ids [Array<Integer>] raw product PKs
+ # @return [Integer] how many were added
+ def add_products(product_ids)
+ product_ids = store.products.where(id: product_ids).ids - catalog_products.pluck(:product_id)
+ product_ids.each { |product_id| catalog_products.create!(product_id: product_id) }
+ product_ids.size
+ end
+
+ private
+
+ def price_list_in_same_store
+ return if price_list.nil? || store_id.nil?
+ return if price_list.store_id == store_id
+
+ errors.add(:price_list, :invalid)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/catalog_assignment.rb b/spree/core/app/models/spree/catalog_assignment.rb
new file mode 100644
index 0000000000..7dda6c654a
--- /dev/null
+++ b/spree/core/app/models/spree/catalog_assignment.rb
@@ -0,0 +1,34 @@
+module Spree
+ # Who gets a catalog. Polymorphic, but the assignable set is small and
+ # closed: Channel, CustomerGroup, Market, Company. A company-node assignment
+ # applies to the node's subtree.
+ #
+ # The assignment direction is "who gets this catalog", not "what catalogs
+ # does this entity have" — resolution queries by catalog.
+ class CatalogAssignment < Spree.base_class
+ has_prefix_id :cata
+
+ ASSIGNABLE_TYPES = %w[Spree::Channel Spree::CustomerGroup Spree::Market Spree::Company].freeze
+
+ belongs_to :catalog, class_name: 'Spree::Catalog', inverse_of: :catalog_assignments
+ belongs_to :assignable, polymorphic: true
+
+ validates :assignable_type, inclusion: { in: ASSIGNABLE_TYPES }
+ validates :catalog_id, uniqueness: { scope: [:assignable_type, :assignable_id, *spree_base_uniqueness_scope] }
+ validate :assignable_in_same_store
+
+ delegate :store, :store_id, to: :catalog
+
+ private
+
+ # Every assignable type is store-scoped, so a cross-store assignment
+ # would show one merchant's catalog to another's audience.
+ def assignable_in_same_store
+ return if assignable.nil? || catalog.nil?
+ return unless assignable.respond_to?(:store_id)
+ return if assignable.store_id == catalog.store_id
+
+ errors.add(:assignable, :invalid)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/catalog_product.rb b/spree/core/app/models/spree/catalog_product.rb
new file mode 100644
index 0000000000..e15ac50d84
--- /dev/null
+++ b/spree/core/app/models/spree/catalog_product.rb
@@ -0,0 +1,25 @@
+module Spree
+ # Membership of one product in a catalog's assortment, manually ordered.
+ class CatalogProduct < Spree.base_class
+ has_prefix_id :catp
+
+ acts_as_list scope: :catalog_id
+
+ belongs_to :catalog, class_name: 'Spree::Catalog', touch: true, inverse_of: :catalog_products
+ belongs_to :product, class_name: 'Spree::Product'
+
+ validates :product_id, uniqueness: { scope: [:catalog_id, *spree_base_uniqueness_scope] }
+ validate :product_in_same_store
+
+ delegate :store, :store_id, to: :catalog
+
+ private
+
+ def product_in_same_store
+ return if product.nil? || catalog.nil?
+ return if product.store_id == catalog.store_id
+
+ errors.add(:product, :invalid)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rb
index bfe5b5664d..97b8e51b35 100644
--- a/spree/core/app/models/spree/channel.rb
+++ b/spree/core/app/models/spree/channel.rb
@@ -22,6 +22,12 @@ module Spree
has_many :order_routing_rules, class_name: 'Spree::OrderRoutingRule', dependent: :destroy
has_many :publications, class_name: 'Spree::ProductPublication', dependent: :destroy
has_many :products, through: :publications, class_name: 'Spree::Product'
+ # When set, only the default catalog's products are visible on this
+ # channel; unset means all publications.
+ belongs_to :default_catalog, class_name: 'Spree::Catalog', optional: true
+ has_many :catalog_assignments, as: :assignable, class_name: 'Spree::CatalogAssignment',
+ dependent: :destroy
+ has_many :catalogs, through: :catalog_assignments, class_name: 'Spree::Catalog'
has_many :api_keys, class_name: 'Spree::ApiKey', dependent: :nullify
# Optional fulfillment-origin allowlist: no rows means every store
# location serves this channel (docs/plans/6.0-channel-delivery.md).
diff --git a/spree/core/app/models/spree/customer_group.rb b/spree/core/app/models/spree/customer_group.rb
index 1ad89f9d18..27749b5b8a 100644
--- a/spree/core/app/models/spree/customer_group.rb
+++ b/spree/core/app/models/spree/customer_group.rb
@@ -12,6 +12,9 @@ module Spree
belongs_to :store, class_name: 'Spree::Store', inverse_of: :customer_groups
has_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', dependent: :destroy
has_many :users, through: :customer_group_users, source: :customer, source_type: Spree.customer_class.to_s
+ has_many :catalog_assignments, as: :assignable, class_name: 'Spree::CatalogAssignment',
+ dependent: :destroy
+ has_many :catalogs, through: :catalog_assignments, class_name: 'Spree::Catalog'
# `customers` is the public name across the v3 API; declaring it as its
# own association (rather than `alias_method`) is what lets `customer_ids=`
# exist and what makes the `PrefixedId` auto-decoder in `assign_attributes`
diff --git a/spree/core/app/models/spree/market.rb b/spree/core/app/models/spree/market.rb
index 8491378752..64f7eb2c4a 100644
--- a/spree/core/app/models/spree/market.rb
+++ b/spree/core/app/models/spree/market.rb
@@ -12,6 +12,9 @@ module Spree
#
belongs_to :store, class_name: 'Spree::Store', touch: true, inverse_of: :markets
has_many :market_countries, class_name: 'Spree::MarketCountry', dependent: :destroy, autosave: true
+ has_many :catalog_assignments, as: :assignable, class_name: 'Spree::CatalogAssignment',
+ dependent: :destroy
+ has_many :catalogs, through: :catalog_assignments, class_name: 'Spree::Catalog'
# Countries are reference data, so this reads the join rows' codes back
# through the registry rather than being a has_many :through.
diff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rb
index 82d19f1083..a27f448348 100644
--- a/spree/core/app/models/spree/price_list.rb
+++ b/spree/core/app/models/spree/price_list.rb
@@ -14,6 +14,9 @@ module Spree
has_many :price_rules, class_name: 'Spree::PriceRule', autosave: true, dependent: :destroy
alias rules price_rules
has_many :prices, class_name: 'Spree::Price', dependent: :destroy_async
+ # Catalogs that price through this list. Nullify: deleting the list turns
+ # them back into assortment-only catalogs.
+ has_many :catalogs, class_name: 'Spree::Catalog', dependent: :nullify
has_many :variants, -> { distinct }, through: :prices, source: :variant
has_many :products, -> { distinct }, through: :variants, source: :product
alias price_list_products products
diff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rb
index cf7a98fea7..32315e3bee 100644
--- a/spree/core/app/models/spree/pricing_provider/internal.rb
+++ b/spree/core/app/models/spree/pricing_provider/internal.rb
@@ -39,10 +39,13 @@ module Spree
private
- # Returns the price from applicable price lists
+ # Returns the price from applicable price lists. Catalog-attached
+ # lists come first — the catalog is the audience, resolved nearest
+ # node first — then the rule-matched lists, then the caller falls
+ # back to base.
# @return [Spree::Price]
def find_price_from_lists
- applicable_price_lists.each do |price_list|
+ (catalog_price_lists + applicable_price_lists).each do |price_list|
price = find_price_for_list(price_list)
return price if price
end
@@ -50,10 +53,42 @@ module Spree
nil
end
- # Returns the price lists that are applicable to the context
+ # Price lists reached through the buyer's effective catalogs, in
+ # catalog resolution order. A catalog-attached list applies because
+ # the catalog applies — its own rules are not consulted, only its
+ # status and dates.
+ # @return [Array<Spree::PriceList>]
+ def catalog_price_lists
+ @catalog_price_lists ||= begin
+ catalogs = Spree::Catalog.effective_for_company(context.company)
+ if catalogs.empty? && context.user && context.store
+ groups = context.user.try(:customer_groups)&.where(store_id: context.store.id) || []
+ catalogs = Spree::Catalog.effective_for_customer_groups(groups)
+ end
+
+ catalogs.filter_map(&:price_list).uniq.select(&:currently_active?)
+ end
+ end
+
+ # Returns the price lists that are applicable to the context.
+ # Catalog-attached lists are excluded here: they are audience-scoped
+ # by their catalog, and a rule-less list would otherwise apply to
+ # everyone.
# @return [Array<Spree::PriceList>]
def applicable_price_lists
- @applicable_price_lists ||= price_lists_for_context.select { |list| list.applicable?(context) }
+ @applicable_price_lists ||= price_lists_for_context.
+ reject { |list| catalog_bound_price_list_ids.include?(list.id) }.
+ select { |list| list.applicable?(context) }
+ end
+
+ def catalog_bound_price_list_ids
+ @catalog_bound_price_list_ids ||=
+ if context.store
+ Spree::Catalog.where(store_id: context.store.id).where.not(price_list_id: nil).
+ distinct.pluck(:price_list_id).to_set
+ else
+ Set.new
+ end
end
# Returns the price lists for the context's store
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 0b69bede77..3943129219 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -103,6 +103,8 @@ module Spree
has_many :product_collections, class_name: 'Spree::ProductCollection', dependent: :destroy_async, inverse_of: :product
has_many :collections, through: :product_collections
+ has_many :catalog_products, class_name: 'Spree::CatalogProduct', dependent: :destroy_async, inverse_of: :product
+ has_many :catalogs, through: :catalog_products
# Dropped with the product so a deleted product stops excluding itself from
# delivery methods. Destroyed inline rather than async — a product sits in
diff --git a/spree/core/app/services/spree/products/for_context.rb b/spree/core/app/services/spree/products/for_context.rb
new file mode 100644
index 0000000000..ca136b0803
--- /dev/null
+++ b/spree/core/app/services/spree/products/for_context.rb
@@ -0,0 +1,62 @@
+module Spree
+ module Products
+ # Resolves which products a buyer may see: the channel's publications,
+ # narrowed by the catalogs that apply to them.
+ #
+ # Precedence, per docs/plans/6.0-b2b-companies-and-catalogs.md:
+ # 1. A buyer resolving to a company node with effective catalogs sees the
+ # union of those catalogs' assortments.
+ # 2. Otherwise, a customer whose groups carry catalogs sees their union.
+ # 3. Otherwise, every channel listing — narrowed to the channel's default
+ # catalog when one is set.
+ #
+ # Gated storefront access (login_required) runs before this resolver — a
+ # gated guest never reaches it.
+ class ForContext
+ prepend Spree::ServiceModule::Base
+
+ # @param store [Spree::Store]
+ # @param channel [Spree::Channel]
+ # @param customer [Object, nil]
+ # @param company [Spree::Company, nil] the purchase node; defaults to
+ # the customer's sole standing within the store
+ # @param base [ActiveRecord::Relation, nil] the already-scoped listing
+ # to narrow; defaults to the channel's publications
+ # @return [Spree::ServiceModule::Result] value is a Product relation
+ def call(store:, channel:, customer: nil, company: nil, base: nil)
+ base ||= store.products.for_channel(channel)
+ company ||= sole_standing_company(store, customer)
+
+ catalogs = Spree::Catalog.effective_for_company(company)
+ catalogs = customer_group_catalogs(store, customer) if catalogs.empty?
+ catalogs = [channel&.default_catalog].compact.select(&:active?) if catalogs.empty?
+
+ return success(base) if catalogs.empty?
+
+ success(base.where(
+ id: Spree::CatalogProduct.where(catalog_id: catalogs.map(&:id)).select(:product_id)
+ ))
+ end
+
+ private
+
+ def sole_standing_company(store, customer)
+ return nil if customer.nil?
+
+ memberships = customer.company_memberships.
+ joins(:company).
+ merge(Spree::Company.where(store_id: store.id)).
+ to_a.uniq
+
+ memberships.one? ? memberships.first.company : nil
+ end
+
+ def customer_group_catalogs(store, customer)
+ return [] if customer.nil?
+
+ groups = customer.customer_groups.where(store_id: store.id)
+ Spree::Catalog.effective_for_customer_groups(groups)
+ end
+ end
+ end
+end
diff --git a/spree/core/db/migrate/20260825000001_create_spree_catalogs.rb b/spree/core/db/migrate/20260825000001_create_spree_catalogs.rb
new file mode 100644
index 0000000000..a439c5640a
--- /dev/null
+++ b/spree/core/db/migrate/20260825000001_create_spree_catalogs.rb
@@ -0,0 +1,40 @@
+class CreateSpreeCatalogs < ActiveRecord::Migration[8.1]
+ def change
+ create_table :spree_catalogs do |t|
+ t.references :store, null: false
+ t.references :price_list # nil = assortment-only, base prices
+ t.string :name, null: false
+ t.boolean :active, null: false, default: true
+ t.integer :position
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
+ t.timestamps
+ end
+
+ create_table :spree_catalog_products do |t|
+ t.references :catalog, null: false
+ t.references :product, null: false
+ t.integer :position
+ t.timestamps
+ end
+
+ add_index :spree_catalog_products, [:catalog_id, :product_id], unique: true,
+ name: 'idx_catalog_products_on_catalog_and_product'
+
+ # Who sees a catalog: Channel, CustomerGroup, Market, or Company (where it
+ # applies to the node's subtree).
+ create_table :spree_catalog_assignments do |t|
+ t.references :catalog, null: false
+ t.references :assignable, polymorphic: true, null: false
+ t.timestamps
+ end
+
+ add_index :spree_catalog_assignments, [:catalog_id, :assignable_type, :assignable_id],
+ unique: true, name: 'idx_catalog_assignments_uniqueness'
+
+ add_reference :spree_channels, :default_catalog
+ end
+end
diff --git a/spree/core/lib/spree/core/pricing/context.rb b/spree/core/lib/spree/core/pricing/context.rb
index 2e36ba4909..a5e97d9162 100644
--- a/spree/core/lib/spree/core/pricing/context.rb
+++ b/spree/core/lib/spree/core/pricing/context.rb
@@ -1,7 +1,7 @@
module Spree
module Pricing
class Context
- attr_reader :variant, :currency, :store, :country, :market, :channel, :user, :quantity, :date, :order
+ attr_reader :variant, :currency, :store, :country, :market, :channel, :user, :quantity, :date, :order, :company
# Initializes the context
# @param variant [Spree::Variant]
@@ -14,7 +14,9 @@ module Spree
# @param quantity [Integer]
# @param date [Time]
# @param order [Spree::Order]
- def initialize(variant: nil, currency:, store: nil, country: nil, market: nil, channel: nil, user: nil, quantity: nil, date: nil, order: nil)
+ # @param company [Spree::Company] the purchase node — catalog-attached
+ # price lists resolve through it, nearest node first
+ def initialize(variant: nil, currency:, store: nil, country: nil, market: nil, channel: nil, user: nil, quantity: nil, date: nil, order: nil, company: nil)
@variant = variant
@currency = currency
@store = store || Spree::Current.store
@@ -25,6 +27,7 @@ module Spree
@quantity = quantity
@date = date || Time.current
@order = order
+ @company = company
end
# The destination as a code. Rules compare against this rather than the
@@ -58,7 +61,8 @@ module Spree
channel: order.channel,
user: order.user,
quantity: quantity || order.line_items.find_by(variant: variant)&.quantity,
- order: order
+ order: order,
+ company: order.resolved_company
)
end
@@ -76,6 +80,7 @@ module Spree
market&.id,
channel&.id,
user&.id,
+ company&.id,
quantity,
date&.to_i
].compact.join('/')
diff --git a/spree/core/lib/spree/testing_support/factories/catalog_factory.rb b/spree/core/lib/spree/testing_support/factories/catalog_factory.rb
new file mode 100644
index 0000000000..a360797d40
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/catalog_factory.rb
@@ -0,0 +1,16 @@
+FactoryBot.define do
+ factory :catalog, class: Spree::Catalog do
+ sequence(:name) { |n| "Wholesale Catalog #{n}" }
+ store { Spree::Store.default || create(:store) }
+ end
+
+ factory :catalog_product, class: Spree::CatalogProduct do
+ catalog
+ product { association(:product, store: catalog.store) }
+ end
+
+ factory :catalog_assignment, class: Spree::CatalogAssignment do
+ catalog
+ assignable { association(:company, store: catalog.store) }
+ end
+end
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.rb
new file mode 100644
index 0000000000..9355928b2e
--- /dev/null
+++ b/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb
@@ -0,0 +1,71 @@
+require 'spec_helper'
+
+describe 'catalog-aware pricing' do
+ let(:store) { @default_store }
+ let(:product) { create(:product, store: store, price: 100) }
+ let(:variant) { product.default_variant }
+ let(:company) { create(:company, store: store) }
+ let(:division) { create(:company, store: store, kind: 'division', parent: company) }
+
+ def price_list_with_price(amount)
+ price_list = create(:price_list, store: store, status: 'active')
+ create(:price, variant: variant, currency: 'USD', amount: amount, price_list: price_list)
+ price_list
+ end
+
+ def resolve(company: nil, user: nil)
+ context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', store: store,
+ user: user, company: company)
+ Spree::Pricing::PriceResolution.call(context)
+ end
+
+ it 'prices from the catalog price list for a member of the audience' do
+ catalog = create(:catalog, store: store, price_list: price_list_with_price(80))
+ create(:catalog_assignment, catalog: catalog, assignable: company)
+
+ expect(resolve(company: company).amount).to eq(80)
+ end
+
+ it 'reaches the parent assignment from a division' do
+ catalog = create(:catalog, store: store, price_list: price_list_with_price(80))
+ create(:catalog_assignment, catalog: catalog, assignable: company)
+
+ expect(resolve(company: division).amount).to eq(80)
+ end
+
+ it 'prefers the nearest node when both assign priced catalogs' do
+ parent_catalog = create(:catalog, store: store, price_list: price_list_with_price(90))
+ own_catalog = create(:catalog, store: store, price_list: price_list_with_price(70))
+ create(:catalog_assignment, catalog: parent_catalog, assignable: company)
+ create(:catalog_assignment, catalog: own_catalog, assignable: division)
+
+ expect(resolve(company: division).amount).to eq(70)
+ expect(resolve(company: company).amount).to eq(90)
+ 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
+ catalog = create(:catalog, store: store, price_list: price_list_with_price(80))
+ create(:catalog_assignment, catalog: catalog, assignable: company)
+
+ expect(resolve.amount).to eq(100)
+ end
+
+ it 'prices through a customer group catalog' do
+ customer = create(:customer)
+ group = create(:customer_group, store: store)
+ group.customer_group_users.create!(customer: customer)
+ catalog = create(:catalog, store: store, price_list: price_list_with_price(85))
+ create(:catalog_assignment, catalog: catalog, assignable: group)
+
+ expect(resolve(user: customer).amount).to eq(85)
+ end
+
+ it 'falls back to base price when the catalog has no price list' do
+ catalog = create(:catalog, store: store)
+ create(:catalog_assignment, catalog: catalog, assignable: company)
+
+ expect(resolve(company: company).amount).to eq(100)
+ end
+end
diff --git a/spree/core/spec/models/spree/catalog_spec.rb b/spree/core/spec/models/spree/catalog_spec.rb
new file mode 100644
index 0000000000..0933fbff18
--- /dev/null
+++ b/spree/core/spec/models/spree/catalog_spec.rb
@@ -0,0 +1,109 @@
+require 'spec_helper'
+
+describe Spree::Catalog, type: :model do
+ it_behaves_like 'metadata'
+
+ let(:store) { @default_store }
+
+ it 'requires a name and binds to a store' do
+ expect(build(:catalog, store: store, name: nil)).not_to be_valid
+ expect(create(:catalog, store: store).store).to eq(store)
+ end
+
+ it 'refuses a price list from another store' do
+ foreign_list = create(:price_list, store: create(:store))
+
+ expect(build(:catalog, store: store, price_list: foreign_list)).not_to be_valid
+ end
+
+ describe '#add_products' do
+ let(:catalog) { create(:catalog, store: store) }
+
+ it 'adds store products once, skipping duplicates and foreign rows' do
+ product = create(:product, store: store)
+ foreign = create(:product, store: create(:store))
+ catalog.add_products([product.id, foreign.id])
+
+ expect(catalog.add_products([product.id])).to eq(0)
+ expect(catalog.products.reload).to contain_exactly(product)
+ end
+ end
+
+ describe '.effective_for_company' do
+ let(:root) { create(:company, store: store) }
+ let(:division) { create(:company, store: store, kind: 'division', parent: root) }
+
+ it 'is empty with no node' do
+ expect(described_class.effective_for_company(nil)).to eq([])
+ end
+
+ it 'collects assignments up the ancestor chain, nearest node first' do
+ parent_catalog = create(:catalog, store: store)
+ own_catalog = create(:catalog, store: store)
+ create(:catalog_assignment, catalog: parent_catalog, assignable: root)
+ create(:catalog_assignment, catalog: own_catalog, assignable: division)
+
+ expect(described_class.effective_for_company(division)).to eq([own_catalog, parent_catalog])
+ # The parent's own resolution sees only its own assignment.
+ expect(described_class.effective_for_company(root)).to eq([parent_catalog])
+ end
+
+ it 'ignores inactive catalogs and sibling assignments' do
+ inactive = create(:catalog, store: store, active: false)
+ create(:catalog_assignment, catalog: inactive, assignable: division)
+ sibling = create(:company, store: store, kind: 'division', parent: root)
+ create(:catalog_assignment, catalog: create(:catalog, store: store), assignable: sibling)
+
+ expect(described_class.effective_for_company(division)).to eq([])
+ end
+
+ it 'orders several catalogs on one node by position' do
+ second = create(:catalog, store: store)
+ first = create(:catalog, store: store)
+ first.update!(position: 1)
+ second.update!(position: 2)
+ create(:catalog_assignment, catalog: second, assignable: division)
+ create(:catalog_assignment, catalog: first, assignable: division)
+
+ expect(described_class.effective_for_company(division)).to eq([first, second])
+ end
+ end
+
+ describe 'assignments' do
+ let(:catalog) { create(:catalog, store: store) }
+
+ it 'accepts the four assignable types' do
+ expect(build(:catalog_assignment, catalog: catalog,
+ assignable: create(:company, store: store))).to be_valid
+ expect(build(:catalog_assignment, catalog: catalog,
+ assignable: create(:customer_group, store: store))).to be_valid
+ expect(build(:catalog_assignment, catalog: catalog, assignable: store.default_market)).to be_valid
+ expect(build(:catalog_assignment, catalog: catalog, assignable: store.default_channel)).to be_valid
+ end
+
+ it 'refuses anything else' do
+ expect(build(:catalog_assignment, catalog: catalog, assignable: create(:product, store: store))).not_to be_valid
+ end
+
+ it 'refuses a cross-store assignment' do
+ expect(build(:catalog_assignment, catalog: catalog,
+ assignable: create(:company, store: create(:store)))).not_to be_valid
+ end
+
+ it 'is unique per catalog and assignable' do
+ company = create(:company, store: store)
+ create(:catalog_assignment, catalog: catalog, assignable: company)
+
+ expect(build(:catalog_assignment, catalog: catalog, assignable: company)).not_to be_valid
+ end
+ end
+
+ it 'keeps the catalog when its price list is deleted' do
+ price_list = create(:price_list, store: store)
+ catalog = create(:catalog, store: store, price_list: price_list)
+
+ price_list.destroy
+
+ expect(catalog.reload.price_list_id).to be_nil
+ end
+end
diff --git a/spree/core/spec/services/spree/products/for_context_spec.rb b/spree/core/spec/services/spree/products/for_context_spec.rb
new file mode 100644
index 0000000000..c57696185d
--- /dev/null
+++ b/spree/core/spec/services/spree/products/for_context_spec.rb
@@ -0,0 +1,80 @@
+require 'spec_helper'
+
+describe Spree::Products::ForContext do
+ let(:store) { @default_store }
+ let(:channel) { store.default_channel }
+ let!(:listed) { create(:product, store: store) }
+ let!(:also_listed) { create(:product, store: store) }
+ let(:customer) { create(:customer) }
+
+ def resolve(**arguments)
+ described_class.call(store: store, channel: channel, **arguments).value
+ end
+
+ it 'returns every channel listing for an anonymous buyer' do
+ expect(resolve).to contain_exactly(listed, also_listed)
+ end
+
+ context 'with a company catalog' do
+ let(:company) { create(:company, store: store) }
+ let(:catalog) { create(:catalog, store: store) }
+
+ before do
+ create(:catalog_assignment, catalog: catalog, assignable: company)
+ catalog.add_products([listed.id])
+ end
+
+ it 'narrows an explicit node to its effective catalogs' do
+ expect(resolve(company: company)).to contain_exactly(listed)
+ end
+
+ it 'resolves the node from a sole membership' do
+ create(:company_membership, company: company, customer: customer)
+
+ expect(resolve(customer: customer)).to contain_exactly(listed)
+ end
+
+ it 'covers the subtree of the assignment node' do
+ division = create(:company, store: store, kind: 'division', parent: company)
+
+ expect(resolve(company: division)).to contain_exactly(listed)
+ end
+
+ it 'takes the union across effective catalogs' do
+ extra = create(:catalog, store: store)
+ create(:catalog_assignment, catalog: extra, assignable: company)
+ extra.add_products([also_listed.id])
+
+ expect(resolve(company: company)).to contain_exactly(listed, also_listed)
+ end
+
+ it 'refuses to narrow for a buyer with several memberships and no explicit node' do
+ create(:company_membership, company: company, customer: customer)
+ create(:company_membership, company: create(:company, store: store), customer: customer)
+
+ expect(resolve(customer: customer)).to contain_exactly(listed, also_listed)
+ end
+ end
+
+ context 'with a customer group catalog' do
+ it 'narrows to the group catalog when no company applies' do
+ group = create(:customer_group, store: store)
+ group.customer_group_users.create!(customer: customer)
+ catalog = create(:catalog, store: store)
+ create(:catalog_assignment, catalog: catalog, assignable: group)
+ catalog.add_products([also_listed.id])
+
+ expect(resolve(customer: customer)).to contain_exactly(also_listed)
+ end
+ end
+
+ context 'with a channel default catalog' do
+ it 'narrows anonymous browsing to it' do
+ catalog = create(:catalog, store: store)
+ catalog.add_products([listed.id])
+ channel.update!(default_catalog: catalog)
+
+ expect(resolve).to contain_exactly(listed)
+ end
+ end
+end