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.

Drop `Product#stores`, add `Product#store` 1:1 assocation, simplify the model

Damian Legawiecb5bcc0c52914
diff --git a/docs/developer/tutorial/testing.mdx b/docs/developer/tutorial/testing.mdx
index 2f6b1a10bc..1fd7215d2d 100644
--- a/docs/developer/tutorial/testing.mdx
+++ b/docs/developer/tutorial/testing.mdx
@@ -329,7 +329,7 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
include_context 'API v3 Store'
let(:brand) { create(:brand, name: 'Nike') }
- let!(:product) { create(:product, brand: brand, stores: [store], status: 'active') }
+ let!(:product) { create(:product, brand: brand, status: 'active') }
before do
request.headers['X-Spree-Api-Key'] = api_key.token
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index f72313d42a..cfaacacd8c 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -1752,12 +1752,20 @@ export class AdminClient {
/**
* Publishes the listed products on this channel. Idempotent — re-publishing
- * an already-published product just refreshes its publication window.
- * Products from sibling stores are silently dropped server-side.
+ * an already-published product is a no-op for its existing publication
+ * window unless +published_at+ / +unpublished_at+ are explicitly passed.
+ * Cross-store onboarding is allowed: if the caller's API key has update
+ * permission on a product owned by a sibling store, that product is
+ * co-published onto this channel. Products the caller can't update are
+ * silently dropped.
*/
addProducts: (
id: string,
- params: { product_ids: string[]; published_at?: string | null; unpublished_at?: string | null },
+ params: {
+ product_ids: string[]
+ published_at?: string | null
+ unpublished_at?: string | null
+ },
options?: RequestOptions,
): Promise<{ product_count: number }> =>
this.request<{ product_count: number }>('POST', `/channels/${id}/add_products`, {
diff --git a/packages/admin-sdk/src/types/generated/AllowedOrigin.ts b/packages/admin-sdk/src/types/generated/AllowedOrigin.ts
index 4d84bbc58c..d4c81fdb34 100644
--- a/packages/admin-sdk/src/types/generated/AllowedOrigin.ts
+++ b/packages/admin-sdk/src/types/generated/AllowedOrigin.ts
@@ -1,4 +1,4 @@
-// Typelizer digest de5936cbb2fdee661ce38e1b1fc084e0
+// Typelizer digest e490250008d9eb1bb47f35f3e86ab346
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -7,7 +7,6 @@ interface AllowedOrigin {
origin: string;
created_at: string;
updated_at: string;
- store_id: string;
}
export default AllowedOrigin;
diff --git a/packages/admin-sdk/src/types/generated/Channel.ts b/packages/admin-sdk/src/types/generated/Channel.ts
index 91f802550e..1d3de42ee0 100644
--- a/packages/admin-sdk/src/types/generated/Channel.ts
+++ b/packages/admin-sdk/src/types/generated/Channel.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 57c8d7b2d34c72e92d26670043eb28f5
+// Typelizer digest 8a76dd2cfe85bd42b35329b35e86f26d
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -7,10 +7,10 @@ interface Channel {
name: string;
code: string;
active: boolean;
+ default: boolean;
preferred_order_routing_strategy: string | null;
created_at: string;
updated_at: string;
- store_id: string;
}
export default Channel;
diff --git a/packages/admin-sdk/src/types/generated/ProductPublication.ts b/packages/admin-sdk/src/types/generated/ProductPublication.ts
index 894cbb25b0..09a3c27401 100644
--- a/packages/admin-sdk/src/types/generated/ProductPublication.ts
+++ b/packages/admin-sdk/src/types/generated/ProductPublication.ts
@@ -1,4 +1,4 @@
-// Typelizer digest ac9645333ab4b127413398b24fa88432
+// Typelizer digest f331132bbbc13862e947e520a61350a0
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -8,11 +8,8 @@ interface ProductPublication {
unpublished_at: string | null;
product_id: string;
channel_id: string;
- units_sold_count: number;
- revenue: string | null;
created_at: string;
updated_at: string;
- store_id: string;
}
export default ProductPublication;
diff --git a/packages/admin-sdk/src/types/generated/Promotion.ts b/packages/admin-sdk/src/types/generated/Promotion.ts
index d6ae96ebe0..67d8357910 100644
--- a/packages/admin-sdk/src/types/generated/Promotion.ts
+++ b/packages/admin-sdk/src/types/generated/Promotion.ts
@@ -1,4 +1,4 @@
-// Typelizer digest e4c17fb68f77c262bcc9f97f9d04d450
+// Typelizer digest a43a43ce4221e34ed79a548b448b98c4
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -20,7 +20,6 @@ interface Promotion {
metadata: Record<string, unknown>;
created_at: string;
updated_at: string;
- store_ids: Array<string>;
action_ids: Array<string>;
rule_ids: Array<string>;
}
diff --git a/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb
index 3ce717dd8c..448d9075b3 100644
--- a/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb
+++ b/spree/admin/spec/controllers/spree/admin/products_controller_spec.rb
@@ -37,7 +37,7 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
it 'searches by product kind' do
shipping_category = create(:shipping_category, name: 'digital')
- product = create(:product, sku: 'ABC123', stores: [store], shipping_category: shipping_category)
+ product = create(:product, sku: 'ABC123', shipping_category: shipping_category)
get :index, params: { q: { shipping_category_id_eq: shipping_category.id.to_s } }
@@ -215,7 +215,7 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
expect(product.depth).to eq 10
expect(product.dimensions_unit).to eq 'cm'
expect(product.weight_unit).to eq 'kg'
- expect(product.stores).to eq [store]
+ expect(product.store).to eq store
expect(product.shipping_category).to eq shipping_category
expect(product.tax_category).to eq tax_category
@@ -436,39 +436,23 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
end
end
- context 'with multiple stores' do
- let(:store_2) { create(:store) }
-
+ # Multi-store assignment ("assign to many stores at once") has moved to
+ # the `spree_multi_store` extension. Core only assigns to the current
+ # store on create.
+ context 'with empty store_ids' do
let(:product_params) do
{
name: 'Product',
- store_ids: [store.id, store_2.id],
+ store_ids: [],
shipping_category_id: shipping_category.id
}
end
- it 'assigns product to requests stores plus current store' do
+ it 'assigns product to current store' do
subject
product = Spree::Product.last
- expect(product.stores).to eq [store, store_2]
- end
-
- context 'with empty store_ids' do
- let(:product_params) do
- {
- name: 'Product',
- store_ids: [],
- shipping_category_id: shipping_category.id
- }
- end
-
- it 'assigns product to current store' do
- subject
-
- product = Spree::Product.last
- expect(product.stores).to eq [store]
- end
+ expect(product.store).to eq store
end
end
end
@@ -1068,74 +1052,11 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
end
end
- context 'with multi-store taxon preservation' do
- let(:other_store) { create(:store) }
- let(:store_taxonomy) { create(:taxonomy, store: store) }
- let(:other_store_taxonomy) { create(:taxonomy, store: other_store) }
- let(:store_taxon) { create(:taxon, taxonomy: store_taxonomy, name: 'Current Store Category') }
- let(:new_store_taxon) { create(:taxon, taxonomy: store_taxonomy, name: 'New Store Category') }
- let(:other_store_taxon) { create(:taxon, taxonomy: other_store_taxonomy, name: 'Other Store Category') }
-
- before do
- product.update(stores: [store, other_store])
- product.taxons << [store_taxon, other_store_taxon]
- end
-
- let(:product_params) do
- {
- name: 'Updated Product',
- taxon_ids: [new_store_taxon.id]
- }
- end
-
- it 'preserves taxons from other stores when updating' do
- expect(product.taxons).to include(store_taxon, other_store_taxon)
-
- send_request
-
- product.reload
- expect(product.taxons).to include(other_store_taxon)
- expect(product.taxons).to include(new_store_taxon)
- expect(product.taxons).not_to include(store_taxon)
- end
-
- context 'when removing all taxons from current store' do
- let(:product_params) do
- {
- name: 'Updated Product',
- taxon_ids: ['']
- }
- end
-
- it 'preserves taxons from other stores' do
- send_request
-
- product.reload
- expect(product.taxons).to include(other_store_taxon)
- expect(product.taxons).not_to include(store_taxon)
- end
- end
-
- context 'with multiple other stores' do
- let(:third_store) { create(:store) }
- let(:third_store_taxonomy) { create(:taxonomy, store: third_store) }
- let(:third_store_taxon) { create(:taxon, taxonomy: third_store_taxonomy, name: 'Third Store Category') }
-
- before do
- product.stores << third_store
- product.taxons << third_store_taxon
- end
-
- it 'preserves taxons from all other stores' do
- send_request
-
- product.reload
- expect(product.taxons).to include(other_store_taxon, third_store_taxon, new_store_taxon)
- expect(product.taxons).not_to include(store_taxon)
- expect(product.taxons.count).to eq 3
- end
- end
- end
+ # Multi-store taxon preservation (editing a product attached to multiple
+ # stores without clobbering other stores' taxon assignments) has moved to
+ # the `spree_multi_store` extension along with the rest of the multi-store
+ # surface. Core's Product belongs to a single store, so the cross-store
+ # merging logic doesn't apply here.
it 'will successfully update product' do
send_request
@@ -1220,7 +1141,7 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
describe 'PUT #clone' do
subject(:clone_request) { put :clone, params: { id: product.to_param } }
- let!(:product) { create(:product, name: 'Product to clone', stores: [store], status: 'active') }
+ let!(:product) { create(:product, name: 'Product to clone', status: 'active') }
let(:cloned_product) { Spree::Product.find_by(name: 'COPY OF Product to clone') }
context 'when cloning succeeds' do
@@ -1251,7 +1172,7 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
end
describe 'POST #bulk_status_update' do
- let(:products) { create_list(:product, 3, stores: [store], status: status) }
+ let(:products) { create_list(:product, 3, status: status) }
let(:status) { :draft }
let(:send_request) { put :bulk_status_update, params: { ids: products.pluck(:id), status: 'active' } }
@@ -1281,7 +1202,7 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
end
describe 'PUT #bulk_add_tags' do
- let(:products) { create_list(:product, 2, stores: [store], status: :active) }
+ let(:products) { create_list(:product, 2, status: :active) }
let(:send_request) do
put :bulk_add_tags, params: { ids: products.pluck(:id), tags: ['tag1', 'tag2', 'tag3'] }
end
@@ -1302,7 +1223,7 @@ RSpec.describe Spree::Admin::ProductsController, type: :controller do
end
describe 'PUT #bulk_remove_tags' do
- let(:products) { create_list(:product, 2, stores: [store], status: :active, tag_list: ['tag1', 'tag2', 'tag3']) }
+ let(:products) { create_list(:product, 2, status: :active, tag_list: ['tag1', 'tag2', 'tag3']) }
let(:send_request) do
put :bulk_remove_tags, params: { ids: products.pluck(:id), tags: ['tag1', 'tag2', 'tag3'] }
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 5928fc78f5..7d722a9288 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
@@ -44,7 +44,7 @@ module Spree
end
def permitted_params
- params.permit(:name, :code, :active, preferences: {})
+ params.permit(:name, :code, :active, :default, preferences: {})
end
private
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index 436802f4bf..53ff9ed250 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -114,7 +114,7 @@ module Spree
def scope_includes
[
:tax_category,
- :product_publications,
+ product_publications: :channel,
primary_media: [attachment_attachment: :blob],
master: [:prices, stock_items: [:stock_location, :active_stock_reservations]],
variants: [:prices, stock_items: [:stock_location, :active_stock_reservations]]
diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
index 19f7899cb7..5047b5be43 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -107,7 +107,8 @@ module Spree
model_class.new(permitted_params)
end
resource.store = current_store if resource.respond_to?(:store_id) && resource.store_id.blank?
- resource.store_ids = [current_store.id] if resource.respond_to?(:store_ids) && resource.store_ids.blank? && !resource.respond_to?(:channels)
+ # very ugly code we need to still support for promotion/payment_method until we migrate them into single store in spree 6.0
+ resource.store_ids = [current_store.id] if resource.respond_to?(:store_ids) && resource.store_ids.blank? && !resource.respond_to?(:store_id)
resource.created_by = try_spree_current_user if resource.respond_to?(:created_by_id)
resource
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/allowed_origin_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/allowed_origin_serializer.rb
index 7f903f292f..3edde7f5de 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/allowed_origin_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/allowed_origin_serializer.rb
@@ -5,16 +5,9 @@ module Spree
module V3
module Admin
class AllowedOriginSerializer < V3::BaseSerializer
- typelize origin: :string,
- store_id: :string
+ typelize origin: :string
attributes :origin, created_at: :iso8601, updated_at: :iso8601
-
- # All rows share `current_store` because `Spree::AllowedOrigin`
- # is a `SingleStoreResource` — avoid the per-row association load.
- attribute :store_id do |_allowed_origin|
- current_store&.prefixed_id
- 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 700fe6d269..308218d51c 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
@@ -8,10 +8,6 @@ module Spree
attributes :preferred_order_routing_strategy,
created_at: :iso8601, updated_at: :iso8601
-
- attribute :store_id do |channel|
- channel.store&.prefixed_id
- end
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/product_publication_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/product_publication_serializer.rb
index 5c267e0af5..4856563d6e 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/product_publication_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/product_publication_serializer.rb
@@ -3,16 +3,7 @@ module Spree
module V3
module Admin
class ProductPublicationSerializer < V3::ProductPublicationSerializer
- typelize store_id: :string,
- units_sold_count: :number,
- revenue: [:string, nullable: true]
-
- attributes :units_sold_count, :revenue,
- created_at: :iso8601, updated_at: :iso8601
-
- attribute :store_id do |publication|
- publication.store&.prefixed_id
- end
+ attributes created_at: :iso8601, updated_at: :iso8601
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
index 7533dbe5f0..ec0f932d48 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
@@ -76,12 +76,10 @@ module Spree
if: proc { expand?('custom_fields') }
many :product_publications,
- proc { |product_publications, params| product_publications.select { |p| p.store_id == params[:store].id } },
resource: Spree.api.admin_product_publication_serializer,
if: proc { expand?('product_publications') }
many :channels,
- proc { |channels, params| channels.select { |c| c.store_id == params[:store].id } },
resource: Spree.api.admin_channel_serializer,
if: proc { expand?('channels') }
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb
index 10930c356a..b63e1612b3 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/promotion_serializer.rb
@@ -19,7 +19,6 @@ module Spree
code_prefix: [:string, nullable: true],
promotion_category_id: [:string, nullable: true],
metadata: 'Record<string, unknown>',
- store_ids: 'string[]',
action_ids: 'string[]',
rule_ids: 'string[]'
@@ -28,10 +27,6 @@ module Spree
:promotion_category_id, :metadata,
created_at: :iso8601, updated_at: :iso8601
- attribute :store_ids do |promotion|
- promotion.stores.map(&:prefixed_id)
- end
-
attribute :action_ids do |promotion|
promotion.promotion_actions.map(&:prefixed_id)
end
diff --git a/spree/api/app/serializers/spree/api/v3/channel_serializer.rb b/spree/api/app/serializers/spree/api/v3/channel_serializer.rb
index 609d574bd3..9e71075798 100644
--- a/spree/api/app/serializers/spree/api/v3/channel_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/channel_serializer.rb
@@ -4,9 +4,10 @@ module Spree
class ChannelSerializer < BaseSerializer
typelize name: :string,
code: :string,
- active: :boolean
+ active: :boolean,
+ default: :boolean
- attributes :name, :code, :active
+ attributes :name, :code, :active, :default
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb
index 4e9f8725a7..f1856b233d 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/channels_controller_spec.rb
@@ -53,7 +53,7 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller do
it 'co-publishes a product from another store onto this channel' do
other_store = create(:store)
- cross_store = create(:product, channels: [other_store.default_channel])
+ cross_store = create(:product, store: other_store)
post :add_products, params: {
id: channel.prefixed_id, product_ids: [cross_store.prefixed_id]
@@ -141,7 +141,7 @@ RSpec.describe Spree::Api::V3::Admin::ChannelsController, type: :controller do
it 'is a no-op for products that have no publication on this channel' do
other_store = create(:store)
- foreign = create(:product, channels: [other_store.default_channel])
+ foreign = create(:product, store: other_store)
expect do
post :remove_products, params: {
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb
index 1095c887a7..b7311cc941 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/prices_controller_spec.rb
@@ -131,7 +131,7 @@ RSpec.describe Spree::Api::V3::Admin::PricesController, type: :controller do
it 'excludes prices from other stores' do
other_store = create(:store)
- other_product = create(:product, stores: [other_store])
+ other_product = create(:product, store: other_store)
other_price = other_product.master.prices.find_by!(currency: 'USD', price_list_id: nil)
get :index, as: :json
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb
index 4738959e92..6a1a12e6b4 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb
@@ -23,7 +23,7 @@ RSpec.describe Spree::Api::V3::Admin::MediaController, type: :controller do
context 'with product from another store' do
let(:other_store) { create(:store) }
- let(:other_product) { create(:product, channels: [other_store.default_channel]) }
+ let(:other_product) { create(:product, store: other_store) }
it 'returns 404' do
get :index, params: { product_id: other_product.prefixed_id }, as: :json
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
index 8a0e39e14c..fc1928e379 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/variants_controller_spec.rb
@@ -22,7 +22,7 @@ RSpec.describe Spree::Api::V3::Admin::Products::VariantsController, type: :contr
context 'with product from another store' do
let(:other_store) { create(:store) }
- let(:other_product) { create(:product, channels: [other_store.default_channel]) }
+ let(:other_product) { create(:product, store: other_store) }
it 'returns 404' do
get :index, params: { product_id: other_product.prefixed_id }, as: :json
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
index 8ed62af1fb..2162265edb 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
@@ -562,7 +562,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
describe 'POST #bulk_status_update' do
let!(:second_product) { create(:product, status: 'draft') }
let(:other_store) { create(:store) }
- let!(:other_store_product) { create(:product, channels: [other_store.default_channel], status: 'active') }
+ let!(:other_store_product) { create(:product, store: other_store, status: 'active') }
before { request.headers.merge!(headers) }
@@ -717,7 +717,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
it 'silently drops products from other stores' do
other_store = create(:store)
- other_store_product = create(:product, channels: [other_store.default_channel])
+ other_store_product = create(:product, store: other_store)
post :bulk_add_to_categories, params: {
ids: [product.prefixed_id, other_store_product.prefixed_id],
@@ -1022,7 +1022,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
it 'silently drops products from other stores' do
other_store = create(:store)
- other_store_product = create(:product, channels: [other_store.default_channel])
+ other_store_product = create(:product, store: other_store)
post :bulk_add_to_channels, params: {
ids: [product.prefixed_id, other_store_product.prefixed_id],
@@ -1116,7 +1116,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
it 'silently drops products from other stores' do
other_store = create(:store)
- other_store_product = create(:product, channels: [other_store.default_channel])
+ other_store_product = create(:product, store: other_store)
post :bulk_add_tags, params: {
ids: [product.prefixed_id, other_store_product.prefixed_id],
@@ -1231,7 +1231,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
it 'silently drops products from other stores' do
other_store = create(:store)
- other_store_product = create(:product, channels: [other_store.default_channel])
+ other_store_product = create(:product, store: other_store)
delete :bulk_destroy, params: {
ids: [product.prefixed_id, other_store_product.prefixed_id]
@@ -1260,7 +1260,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
it 'returns 0 when the only IDs reference unreachable products' do
other_store = create(:store)
- other_store_product = create(:product, channels: [other_store.default_channel])
+ other_store_product = create(:product, store: other_store)
delete :bulk_destroy, params: {
ids: [other_store_product.prefixed_id]
diff --git a/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb
index 16f8f001c5..b8ac40dd0b 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb
@@ -33,7 +33,7 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARC
# Products with different attributes
let!(:cheap_red_shirt) do
- p = create(:product, name: 'Red Cotton Shirt', status: 'active', stores: [store], taxons: [clothing_category])
+ p = create(:product, name: 'Red Cotton Shirt', status: 'active', store: store, taxons: [clothing_category])
p.option_types << color_option
p.option_types << size_option
v = create(:variant, product: p, option_values: [red, small])
@@ -42,7 +42,7 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARC
end
let!(:expensive_blue_shirt) do
- p = create(:product, name: 'Blue Silk Shirt', status: 'active', stores: [store], taxons: [clothing_category])
+ p = create(:product, name: 'Blue Silk Shirt', status: 'active', store: store, taxons: [clothing_category])
p.option_types << color_option
v = create(:variant, product: p, option_values: [blue, large])
v.prices.find_or_create_by!(currency: 'USD').update!(amount: 89.99)
@@ -50,7 +50,7 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARC
end
let!(:blue_shoes) do
- p = create(:product, name: 'Blue Running Shoes', status: 'active', stores: [store], taxons: [shoes_category])
+ p = create(:product, name: 'Blue Running Shoes', status: 'active', store: store, taxons: [shoes_category])
p.option_types << color_option
p.option_types << size_option
v = create(:variant, product: p, option_values: [blue, small])
diff --git a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
index 81c9ca5dce..111702d3eb 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
@@ -9,7 +9,7 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
let!(:product2) { create(:product, status: 'active') }
let!(:draft_product) { create(:product, status: 'draft') }
let!(:other_store) { create(:store) }
- let!(:other_store_product) { create(:product, channels: [other_store.default_channel]) }
+ let!(:other_store_product) { create(:product, store: other_store) }
before do
request.headers['X-Spree-Api-Key'] = api_key.token
@@ -233,8 +233,8 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
end
it 'sorts by best selling' do
- Spree::ProductPublication.find_by(product: product, store: store).update!(units_sold_count: 10, revenue: 100)
- Spree::ProductPublication.find_by(product: product2, store: store).update!(units_sold_count: 50, revenue: 500)
+ product.update!(units_sold_count: 10, revenue: 100)
+ product2.update!(units_sold_count: 50, revenue: 500)
get :index, params: { sort: 'best_selling' }
diff --git a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
index 3ab60ad315..5a7282dd9b 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/products_spec.rb
@@ -373,7 +373,7 @@ RSpec.describe 'Admin Products API', type: :request, swagger_doc: 'api-reference
response '200', 'cross-store products silently dropped' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
- let(:other_store_product) { create(:product, stores: [create(:store)]) }
+ let(:other_store_product) { create(:product, store: create(:store)) }
let(:body) { { ids: [other_store_product.prefixed_id], status: 'archived' } }
run_test! do |response|
diff --git a/spree/api/spec/integration/spree/api/v3/store/products_spec.rb b/spree/api/spec/integration/spree/api/v3/store/products_spec.rb
index b1ea8bc5ca..5ac26e7412 100644
--- a/spree/api/spec/integration/spree/api/v3/store/products_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/products_spec.rb
@@ -22,7 +22,7 @@ RSpec.describe 'Products API', type: :request, swagger_doc: 'api-reference/store
let!(:product2) { create(:product, status: 'active', taxons: [child_taxon]) }
let!(:draft_product) { create(:product, status: 'draft') }
let!(:other_store) { create(:store) }
- let!(:other_store_product) { create(:product, channels: [other_store.default_channel]) }
+ let!(:other_store_product) { create(:product, store: other_store) }
path '/api/v3/store/products' do
get 'List products' do
diff --git a/spree/core/app/jobs/spree/products/refresh_metrics_job.rb b/spree/core/app/jobs/spree/products/refresh_metrics_job.rb
index 17d03dd760..d8322da5ff 100644
--- a/spree/core/app/jobs/spree/products/refresh_metrics_job.rb
+++ b/spree/core/app/jobs/spree/products/refresh_metrics_job.rb
@@ -3,11 +3,22 @@ module Spree
class RefreshMetricsJob < Spree::BaseJob
queue_as Spree.queues.products
- def perform(product_id, store_id)
- publication = Spree::ProductPublication.find_by(product_id: product_id, store_id: store_id)
- return unless publication
+ def perform(product_id)
+ product = Spree::Product.find_by(id: product_id)
+ return unless product
- publication.refresh_metrics!
+ completed_order_ids = product.completed_orders.select(:id)
+ variant_ids = product.variants_including_master.ids
+
+ line_items = Spree::LineItem.joins(:order)
+ .where(spree_orders: { id: completed_order_ids })
+ .where(variant_id: variant_ids)
+
+ # update columns to skip callbacks
+ product.update_columns(
+ units_sold_count: line_items.sum(:quantity),
+ revenue: line_items.sum(:pre_tax_amount)
+ )
end
end
end
diff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rb
index 041c8401b3..7498f760ad 100644
--- a/spree/core/app/models/concerns/spree/product_scopes.rb
+++ b/spree/core/app/models/concerns/spree/product_scopes.rb
@@ -363,19 +363,18 @@ module Spree
group('spree_products.id').joins(:taxons).where(Taxon.arel_table[:name].eq(name))
end
- # Orders products by best selling based on units_sold_count and revenue
- # from spree_product_publications (already joined via store.products).
- #
- # Uses Arel::Nodes::As so that ORDER BY expressions appear in SELECT
- # and work with DISTINCT (same pattern as the price sorting scopes).
+ # Orders products by best-selling metrics (+units_sold_count+, +revenue+)
+ # tracked directly on +spree_products+. Uses Arel::Nodes::As so that
+ # ORDER BY expressions appear in SELECT and work with DISTINCT (same
+ # pattern as the price sorting scopes).
scope :by_best_selling, ->(order_direction = :desc) {
- sp_table = ProductPublication.table_name
- units_expr = Arel.sql("COALESCE(#{sp_table}.units_sold_count, 0)")
- revenue_expr = Arel.sql("COALESCE(#{sp_table}.revenue, 0)")
+ p_table = Product.table_name
+ units_expr = Arel.sql("COALESCE(#{p_table}.units_sold_count, 0)")
+ revenue_expr = Arel.sql("COALESCE(#{p_table}.revenue, 0)")
order_dir = order_direction == :desc ? :desc : :asc
- select("#{Product.table_name}.*").
+ select("#{p_table}.*").
select(Arel::Nodes::As.new(units_expr, Arel.sql('best_selling_units'))).
select(Arel::Nodes::As.new(revenue_expr, Arel.sql('best_selling_revenue'))).
order(units_expr.send(order_dir)).
diff --git a/spree/core/app/models/concerns/spree/search_indexable.rb b/spree/core/app/models/concerns/spree/search_indexable.rb
index 2e8a30fc04..fa3c13efab 100644
--- a/spree/core/app/models/concerns/spree/search_indexable.rb
+++ b/spree/core/app/models/concerns/spree/search_indexable.rb
@@ -68,14 +68,15 @@ module Spree
false
end
+ # Stores against which this record should be indexed/removed. By default
+ # we use the record's own +store_id+ (Product, Customer, Order, …). The
+ # multi-store extension overrides this to fan out across every store the
+ # record is attached to. Falling back to +Spree::Store.default+ covers
+ # records like categories/taxonomies that don't have a +store_id+ column.
def store_ids_for_indexing
- if respond_to?(:store_ids)
- store_ids
- elsif respond_to?(:store_id)
- [store_id].compact
- else
- Spree::Store.pluck(:id)
- end
+ return [store_id] if respond_to?(:store_id) && store_id.present?
+
+ Array(Spree::Store.default&.id)
end
end
end
diff --git a/spree/core/app/models/spree/base.rb b/spree/core/app/models/spree/base.rb
index d11d8d655f..930ccfe3bf 100644
--- a/spree/core/app/models/spree/base.rb
+++ b/spree/core/app/models/spree/base.rb
@@ -59,6 +59,10 @@ class Spree::Base < ApplicationRecord
true
end
+ def mysql_adapter?
+ ActiveRecord::Base.connection.adapter_name.downcase.include?('mysql')
+ end
+
def self.json_api_columns
column_names.reject { |c| c.match(/_id$|id|preferences|(.*)password|(.*)token|(.*)api_key|^original_(.*)/) }
end
diff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rb
index 93f2693376..f425460c07 100644
--- a/spree/core/app/models/spree/channel.rb
+++ b/spree/core/app/models/spree/channel.rb
@@ -18,23 +18,30 @@ module Spree
has_many :orders, class_name: 'Spree::Order', inverse_of: :channel, dependent: :nullify
has_many :order_routing_rules, class_name: 'Spree::OrderRoutingRule', dependent: :destroy
- has_many :product_publications, class_name: 'Spree::ProductPublication', dependent: :destroy
- has_many :products, through: :product_publications, class_name: 'Spree::Product'
+ has_many :publications, class_name: 'Spree::ProductPublication', dependent: :destroy
+ has_many :products, through: :publications, class_name: 'Spree::Product'
attribute :active, :boolean, default: true
normalizes :code, with: ->(value) { value.to_s.parameterize.presence }
before_validation :backfill_code_from_name, if: -> { code.blank? && name.present? }
+ before_validation :promote_first_channel_to_default
validates :name, :store, presence: true
validates :code, presence: true, uniqueness: { scope: spree_base_uniqueness_scope + [:store_id] }
+ # Model-level guard mirroring the partial unique index. Necessary on
+ # MySQL (no partial indexes); harmless duplication of the DB constraint
+ # on Postgres/SQLite, giving a friendlier validation error.
+ validates :default, uniqueness: { scope: spree_base_uniqueness_scope + [:store_id], if: :default? }
+ after_save :demote_other_defaults, if: -> { default? && saved_change_to_default? }
after_create :ensure_default_order_routing_rules
scope :active, -> { where(active: true) }
+ scope :default, -> { where(default: true) }
- self.whitelisted_ransackable_attributes = %w[name code active store_id]
+ self.whitelisted_ransackable_attributes = %w[name code active default store_id]
# Publishes the given products on this channel by creating/upserting ProductPublications.
# Optionally sets the publication window; if not given, the products will be published immediately
@@ -48,24 +55,38 @@ module Spree
return 0 if product_ids.empty?
now = Time.current
- records_to_upsert = product_ids.map do |product_id|
- {
- channel_id: id,
- store_id: store_id,
- product_id: product_id,
- published_at: published_at,
- unpublished_at: unpublished_at,
- created_at: now,
- updated_at: now
- }
- end
-
- opts = { update_only: %i[published_at unpublished_at], on_duplicate: :update }
+ # Only include window columns in the upsert payload when the caller
+ # explicitly passed a value. Leaving them out keeps existing
+ # publication schedules intact on re-publish — otherwise +on_duplicate:
+ # :update+ + +update_only+ would rewrite scheduled +published_at+ /
+ # +unpublished_at+ to NULL whenever the bulk action re-runs without
+ # dates.
+ base = { channel_id: id, created_at: now, updated_at: now }
+ base[:published_at] = published_at unless published_at.nil?
+ base[:unpublished_at] = unpublished_at unless unpublished_at.nil?
+
+ records_to_upsert = product_ids.map { |product_id| base.merge(product_id: product_id) }
+
+ # Only update the window columns the caller passed. When neither was
+ # passed, treat re-publish as a no-op (+on_duplicate: :skip+ → MySQL
+ # +INSERT IGNORE+, PG/SQLite +ON CONFLICT DO NOTHING+).
+ update_columns = []
+ update_columns << :published_at unless published_at.nil?
+ update_columns << :unpublished_at unless unpublished_at.nil?
+ opts = if update_columns.empty?
+ { on_duplicate: :skip }
+ else
+ { record_timestamps: false, update_only: update_columns, on_duplicate: :update }
+ end
# MySQL infers the conflict target from the table's unique constraints
# and rejects an explicit +unique_by+; PostgreSQL/SQLite require it.
- opts[:unique_by] = %i[channel_id product_id store_id] unless ActiveRecord::Base.connection.adapter_name == 'Mysql2'
+ opts[:unique_by] = %i[product_id channel_id] unless mysql_adapter?
Spree::ProductPublication.upsert_all(records_to_upsert, **opts)
+
+ products = Spree::Product.where(id: product_ids)
+ products.touch_all
+ products.each(&:enqueue_search_index)
touch
records_to_upsert.size
@@ -78,7 +99,12 @@ module Spree
product_ids = Array(product_ids).map(&:to_s).uniq
return 0 if product_ids.empty?
- count = product_publications.where(product_id: product_ids).destroy_all.size
+ count = publications.where(product_id: product_ids).destroy_all.size
+
+ products = Spree::Product.where(id: product_ids)
+ products.touch_all
+ products.each(&:enqueue_search_index)
+
touch if count.positive?
count
end
@@ -89,6 +115,21 @@ module Spree
self.code = name
end
+ # First channel on a store becomes the default. Lets the
+ # +Stores::Channels#ensure_default_channel+ seed path and the legacy
+ # admin "create channel" form both produce a sensible default without
+ # the caller having to know.
+ def promote_first_channel_to_default
+ return if default
+ return unless new_record? && store_id.present?
+
+ self.default = true unless Spree::Channel.where(store_id: store_id).exists?
+ end
+
+ def demote_other_defaults
+ Spree::Channel.where(store_id: store_id, default: true).where.not(id: id).update_all(default: false)
+ end
+
# Default ordering: preferred location wins, then minimize splits, then
# fall back to StockLocation.default. See docs/plans/6.0-order-routing.md.
def ensure_default_order_routing_rules
diff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rb
index 4b37c3ab11..c496468bd8 100644
--- a/spree/core/app/models/spree/price_list.rb
+++ b/spree/core/app/models/spree/price_list.rb
@@ -270,7 +270,7 @@ module Spree
return true if records_to_upsert.empty?
opts = { update_only: [:amount, :compare_at_amount], on_duplicate: :update }
- opts[:unique_by] = :id unless ActiveRecord::Base.connection.adapter_name == 'Mysql2'
+ opts[:unique_by] = :id unless mysql_adapter?
Spree::Price.upsert_all(records_to_upsert, **opts)
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index b17468b5e9..827165f4ad 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -34,6 +34,7 @@ module Spree
include Spree::Product::Webhooks
include Spree::Product::Slugs
include Spree::Product::Channels
+ include Spree::Product::LegacyMultiStoreSupport unless defined?(SpreeMultiStore)
include Spree::SearchIndexable
if defined?(Spree::VendorConcern)
include Spree::VendorConcern
@@ -152,7 +153,7 @@ module Spree
validate :discontinue_on_must_be_later_than_make_active_at, if: -> { make_active_at && discontinue_on }
- scope :for_store, ->(store) { joins(:product_publications).where(ProductPublication.table_name => { store_id: store.id }) }
+ scope :for_store, ->(store) { where(store_id: store.id) }
scope :draft, -> { where(status: 'draft') }
scope :archived, -> { where(status: 'archived') }
scope :not_archived, -> { where.not(status: 'archived') }
@@ -234,7 +235,7 @@ module Spree
end
self.whitelisted_ransackable_attributes = %w[description name slug discontinue_on status available_on created_at updated_at]
- self.whitelisted_ransackable_associations = %w[taxons categories stores channels variants_including_master master variants tags labels
+ self.whitelisted_ransackable_associations = %w[taxons categories store channels variants_including_master master variants tags labels
shipping_category classifications option_types]
self.whitelisted_ransackable_scopes = %w[not_discontinued search_by_name in_taxon in_category in_categories price_between
price_lte price_gte
@@ -600,15 +601,13 @@ module Spree
def auto_match_taxons
return if deleted?
return if archived?
-
- store = stores.find_by(default: true) || stores.first
return if store.nil? || store.taxons.automatic.none?
Spree::Products::AutoMatchTaxonsJob.set(wait: 30.seconds).perform_later(id)
end
def to_csv(store = nil)
- store ||= stores.default || stores.first
+ store ||= self.store
properties_for_csv = if respond_to?(:product_properties) && Spree::Config.respond_to?(:product_properties_enabled) && Spree::Config[:product_properties_enabled]
Spree::Property.order(:position).flat_map do |property|
[
@@ -729,7 +728,7 @@ module Spree
values = option_values_hash.values
values = values.inject(values.shift) { |memo, value| memo.product(value).map(&:flatten) }
- default_currency = stores.first&.default_currency || Spree::Store.default.default_currency
+ default_currency = store&.default_currency || Spree::Store.default.default_currency
master_price = master.price_in(default_currency).amount
values.each do |ids|
diff --git a/spree/core/app/models/spree/product/channels.rb b/spree/core/app/models/spree/product/channels.rb
index 7c6be2acab..1467936abb 100644
--- a/spree/core/app/models/spree/product/channels.rb
+++ b/spree/core/app/models/spree/product/channels.rb
@@ -8,47 +8,23 @@ module Spree
discontinue_on: :unpublished_at
}.freeze
- # Intercepts +product.stores << store+ so the deprecated stores API still
- # produces correctly-channelled publications (with any legacy
- # +available_on+/+discontinue_on+ values applied).
- #
- # AR's default +has_many :through+ +<<+ would build a half-formed join
- # row missing the channel and the legacy dates; this extension owns the
- # build so we get a complete record.
- module StoresCollectionExtension
- def <<(*stores)
- Spree::Deprecation.warn(
- 'Assigning stores via Spree::Product#stores<< is deprecated; ' \
- 'use #product_publications= with explicit channel references instead. ' \
- 'This bridge is removed in Spree 6.0.'
- )
- product = proxy_association.owner
- stores.flatten.each { |store| product.send(:build_publication_for_store, store) }
- self
- end
- alias_method :push, :<<
- alias_method :append, :<<
- alias_method :concat, :<<
- end
-
included do
+ belongs_to :store, class_name: 'Spree::Store', optional: true
+
# No +dependent: :destroy+: Product uses +acts_as_paranoid+, so destroy
- # soft-deletes and publications outlive the product (refresh_metrics
- # handles the orphan case).
+ # soft-deletes and publications outlive the product.
has_many :product_publications, class_name: 'Spree::ProductPublication', autosave: true
has_many :channels, -> { distinct }, through: :product_publications, class_name: 'Spree::Channel'
- # @deprecated Alias of {#product_publications}. Remove in Spree 6.0.
- has_many :store_products, class_name: 'Spree::ProductPublication'
- # +unscope(:order)+ drops +Spree::Store+'s +default_scope { order(:created_at) }+
- # so the +DISTINCT+ stays compatible with strict SQL modes (Postgres,
- # MySQL ONLY_FULL_GROUP_BY). Same reason +channels+ doesn't need it —
- # +Spree::Channel+ has no default ordering.
- has_many :stores, -> { unscope(:order).distinct },
- through: :store_products, class_name: 'Spree::Store',
- extend: StoresCollectionExtension
-
- before_validation :set_default_publication, if: :set_default_publication?
+ # +accepts_nested_attributes_for+ enables the legacy Rails admin form
+ # to submit publication windows via +product_publications_attributes=+.
+ # The SPA's API path uses the explicit hash-array setter defined below
+ # (+product_publications=+); the two coexist on different keys.
+ accepts_nested_attributes_for :product_publications,
+ allow_destroy: true,
+ reject_if: ->(attrs) { attrs[:channel_id].blank? }
+
+ before_validation :assign_default_store, if: -> { store.nil? }
after_create :apply_pending_publications, if: :pending_publications?
DEPRECATED_DATE_TO_PUBLICATION_FIELD.each do |legacy_attr, publication_attr|
@@ -61,14 +37,14 @@ module Spree
product_publications.each { |publication| publication.public_send("#{publication_attr}=", value) }
end
- # Reading +available_on+/+discontinue_on+/+make_active_at+ prefers the
- # current-channel publication's date and falls back to the legacy
- # Product column. Lets serializers and scopes stay one-liners while
- # the publication is the source of truth.
+ # Reading +available_on+/+discontinue_on+ prefers the current-channel
+ # publication's date and falls back to the legacy Product column
+ # whenever the publication's value is nil. This 5.5 transition
+ # behavior is dropped in 6.0 when the legacy columns are removed.
define_method(legacy_attr) do
channel = Spree::Current.channel
publication = channel && publication_for(channel)
- publication&.public_send(publication_attr) || super()
+ (publication && publication.public_send(publication_attr)) || super()
end
end
end
@@ -86,45 +62,6 @@ module Spree
end
end
- # Returns the publications for the given store, or an empty array if the product isn't published there.
- # @param store [Spree::Store] the store to find publications for
- # @return [Array<Spree::ProductPublication>] the publications for the store, or an empty array if not published
- def publications_for_store(store)
- return [] unless store
-
- if product_publications.loaded?
- product_publications.select { |p| p.store_id == store.id }
- else
- product_publications.where(store_id: store.id)
- end
- end
-
- # @deprecated Assigning stores directly is replaced by setting
- # +product_publications=+ with explicit channels. Will be removed in
- # Spree 6.0. The bridge clears any existing publications and rebuilds
- # one per store on that store's +default_channel+.
- def stores=(stores)
- Spree::Deprecation.warn(
- 'Assigning stores via Spree::Product#stores= is deprecated; ' \
- 'use #channels= instead. ' \
- 'This bridge is removed in Spree 6.0.'
- )
- product_publications.clear unless new_record?
- association(:stores).reset
- Array(stores).each { |store| build_publication_for_store(store) }
- end
-
- def store_ids=(ids)
- Spree::Deprecation.warn(
- 'Assigning stores via Spree::Product#store_ids= is deprecated; ' \
- 'use #channel_ids= instead. ' \
- 'This bridge is removed in Spree 6.0.'
- )
- product_publications.clear unless new_record?
- association(:stores).reset
- Spree::Store.where(id: Array(ids).compact_blank).each { |store| build_publication_for_store(store) }
- end
-
# Syncs product publications from an array of hashes.
# Creates new publications, updates existing ones (matched by :id), and removes
# ones absent from the payload. Mirrors +Product#variants=+.
@@ -143,41 +80,8 @@ module Spree
private
- def build_publication_for_store(store)
- return if store.default_channel.nil?
- return if publications_for_store(store).any?
-
- product_publications.build(
- { store: store, channel: store.default_channel }.merge(legacy_date_attributes)
- )
- end
-
- def set_default_publication?
- new_record? && product_publications.empty? && @pending_publications_params.blank?
- end
-
- def set_default_publication
- store = Spree::Current.store || Spree::Store.default
- return unless store
- channel = store.default_channel
- return unless channel
-
- product_publications.build(
- { channel: channel, store: store }.merge(legacy_date_attributes)
- )
- # If +stores=+ already populated the through cache with an empty array,
- # a freshly-built publication wouldn't show up on +product.stores+.
- association(:stores).reset
- end
-
- # Pulls available_on / discontinue_on / make_active_at written via the
- # deprecated Product setters into publication-side keys, so a publication
- # built later in the save cycle still carries the user's intent.
- def legacy_date_attributes
- DEPRECATED_DATE_TO_PUBLICATION_FIELD.each_with_object({}) do |(legacy, publication_attr), acc|
- value = read_attribute(legacy)
- acc[publication_attr] = value if value.present?
- end
+ def assign_default_store
+ self.store ||= Spree::Current.store || Spree::Store.default
end
def pending_publications?
@@ -191,32 +95,42 @@ module Spree
@pending_publications_params = nil
end
+ # SPA write contract for +product.product_publications=+: the caller
+ # sends the FULL desired set of publications. Rows present become
+ # creates/updates; rows absent get destroyed. Mass-delete is safe
+ # because the only caller (+<PublishingCard>+ in the dashboard) drives
+ # the array via +useFieldArray+ and always submits the complete state.
+ # The Rails admin uses +product_publications_attributes=+ (nested
+ # attributes) instead — that path uses explicit +_destroy: '1'+ flags
+ # and never reaches this method.
def apply_product_publications(publications_params)
publication_ids_in_payload = []
publications_params.each do |publication_data|
publication_data = publication_data.to_h.with_indifferent_access
publication_id = publication_data.delete(:id)
- channel_id = publication_data.delete(:channel_id)
if publication_id.present?
- publication = product_publications.find_by_param!(publication_id)
- publication.update!(publication_data)
- publication_ids_in_payload << publication.id
- elsif channel_id.present?
- channel = Spree::Channel.find_by_param!(channel_id)
- # Find-or-create on (product, channel) — auto-created publications from
- # +StoreScopedResource#set_default_store+ get reused rather than
- # colliding with the uniqueness validation.
- publication = product_publications.find_or_initialize_by(channel: channel)
- publication.store ||= channel.store
- publication.assign_attributes(publication_data)
- publication.save!
+ decoded_id = Spree::PrefixedId.prefixed_id?(publication_id) ?
+ Spree::PrefixedId.decode_prefixed_id(publication_id) :
+ publication_id
+ publication = product_publications.find_by(id: decoded_id)
+ next unless publication
+
+ # Channel is immutable on a publication — silently drop any
+ # caller attempt to rebind it. Re-publish on a different channel
+ # is a destroy + create, not an update.
+ publication.update!(publication_data.slice(:published_at, :unpublished_at))
publication_ids_in_payload << publication.id
+ elsif publication_data[:channel_id].present?
+ new_publication = product_publications.create!(
+ publication_data.slice(:channel_id, :published_at, :unpublished_at)
+ )
+ publication_ids_in_payload << new_publication.id
end
end
- product_publications.where.not(id: publication_ids_in_payload).destroy_all if publication_ids_in_payload.any?
+ product_publications.where.not(id: publication_ids_in_payload).destroy_all
end
end
end
diff --git a/spree/core/app/models/spree/product/legacy_multi_store_support.rb b/spree/core/app/models/spree/product/legacy_multi_store_support.rb
new file mode 100644
index 0000000000..04af66f268
--- /dev/null
+++ b/spree/core/app/models/spree/product/legacy_multi_store_support.rb
@@ -0,0 +1,40 @@
+module Spree
+ class Product
+ # Legacy multi-store support. In Spree 5.5+ the +Spree::ProductPublication+ model
+ # handles the Product↔Store relation, so this module only provides a fallback
+ # for legacy code that still references +Spree::Product#stores+.
+ module LegacyMultiStoreSupport
+ extend ActiveSupport::Concern
+
+ included do
+ def stores
+ Spree::Deprecation.warn(
+ "Spree::Product#stores is deprecated. Please use Spree::Product.store instead. If you want to continue using multiple stores please install spree_multi_store gem"
+ )
+ store ? [store] : []
+ end
+
+ def store_ids
+ Spree::Deprecation.warn(
+ "Spree::Product#store_ids is deprecated. Please use Spree::Product.store_id instead. If you want to continue using multiple stores please install spree_multi_store gem"
+ )
+ store_id ? [store_id] : []
+ end
+
+ def stores=(stores)
+ Spree::Deprecation.warn(
+ "Spree::Product#stores= is deprecated. Please use Spree::Product.store= instead. If you want to continue using multiple stores please install spree_multi_store gem"
+ )
+ self.store = Array(stores).compact.first
+ end
+
+ def store_ids=(store_ids)
+ Spree::Deprecation.warn(
+ "Spree::Product#store_ids= is deprecated. Please use Spree::Product.store_id= instead. If you want to continue using multiple stores please install spree_multi_store gem"
+ )
+ self.store_id = Array(store_ids).compact_blank.first
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/product_publication.rb b/spree/core/app/models/spree/product_publication.rb
index a199f8cf01..072d5f80b9 100644
--- a/spree/core/app/models/spree/product_publication.rb
+++ b/spree/core/app/models/spree/product_publication.rb
@@ -1,62 +1,39 @@
module Spree
+ # Per-channel publication record. A Product is "published" on a Channel when
+ # a ProductPublication exists for that pair; the optional window
+ # (+published_at+/+unpublished_at+) gates customer visibility.
+ #
+ # The owning Store is derived via +channel.store+ — no +store_id+ column
+ # lives on this table. Historic core had a +spree_products_stores+ join that
+ # also carried the Product↔Store relation; in 5.5+ that responsibility moves
+ # onto +Spree::Product#store_id+ directly, leaving this table single-purpose.
class ProductPublication < Spree.base_class
has_prefix_id :pp
- # 5.5 transitional: table keeps the legacy +spree_products_stores+ name
- # while the class moves to +ProductPublication+. The rename will happen
- # in 6.0; see docs/plans/6.0-channels-catalogs-b2b.md.
- self.table_name = 'spree_products_stores'
-
belongs_to :product, class_name: 'Spree::Product', touch: true
- belongs_to :store, class_name: 'Spree::Store'
- belongs_to :channel, class_name: 'Spree::Channel', optional: true
+ belongs_to :channel, class_name: 'Spree::Channel'
- validates :product, :store, :channel, presence: true
- validates :product_id, uniqueness: { scope: spree_base_uniqueness_scope + %i[channel_id store_id] }
+ validates :product, :channel, presence: true
+ validates :product_id, uniqueness: { scope: :channel_id }
validate :unpublished_at_after_published_at, if: -> { published_at && unpublished_at }
- before_validation :assign_channel_from_store, if: -> { channel_id.nil? && store_id.present? }
- before_validation :assign_store_from_channel, if: -> { store_id.nil? && channel_id.present? }
-
scope :published, lambda {
where('published_at IS NULL OR published_at <= ?', Time.current)
.where('unpublished_at IS NULL OR unpublished_at > ?', Time.current)
}
- self.whitelisted_ransackable_attributes = %w[product_id store_id channel_id published_at unpublished_at]
- self.whitelisted_ransackable_associations = %w[product store channel]
+ self.whitelisted_ransackable_attributes = %w[product_id channel_id published_at unpublished_at]
+ self.whitelisted_ransackable_associations = %w[product channel]
+
+ delegate :store, :store_id, to: :channel
def published?
(published_at.nil? || published_at <= Time.current) &&
(unpublished_at.nil? || unpublished_at > Time.current)
end
- def refresh_metrics!
- return if product.nil?
-
- completed_order_ids = product.completed_orders.where(store_id: store_id).select(:id)
- variant_ids = product.variants_including_master.ids
-
- line_items = Spree::LineItem.joins(:order)
- .where(spree_orders: { id: completed_order_ids })
- .where(variant_id: variant_ids)
-
- update!(
- units_sold_count: line_items.sum(:quantity),
- revenue: line_items.sum(:pre_tax_amount)
- )
- end
-
private
- def assign_channel_from_store
- self.channel = store.default_channel
- end
-
- def assign_store_from_channel
- self.store = channel.store
- end
-
def unpublished_at_after_published_at
return if unpublished_at > published_at
diff --git a/spree/core/app/models/spree/promotion/actions/create_line_items.rb b/spree/core/app/models/spree/promotion/actions/create_line_items.rb
index d1698e1195..950ff0f796 100644
--- a/spree/core/app/models/spree/promotion/actions/create_line_items.rb
+++ b/spree/core/app/models/spree/promotion/actions/create_line_items.rb
@@ -119,7 +119,7 @@ module Spree
return if rows.empty?
opts = {}
- opts[:unique_by] = [:promotion_action_id, :variant_id] unless ActiveRecord::Base.connection.adapter_name == 'Mysql2'
+ opts[:unique_by] = [:promotion_action_id, :variant_id] unless mysql_adapter?
promotion_action_line_items.upsert_all(
rows.map do |params|
diff --git a/spree/core/app/models/spree/stock_item.rb b/spree/core/app/models/spree/stock_item.rb
index 78ef3d749e..3331334c1a 100644
--- a/spree/core/app/models/spree/stock_item.rb
+++ b/spree/core/app/models/spree/stock_item.rb
@@ -49,9 +49,7 @@ module Spree
# without inheriting `Spree::Store#stock_items`'s extra joins or
# the variant default ordering.
scope :for_store, ->(store) {
- joins(variant: { product: :stores }).
- where(spree_stores: { id: store.id }).
- distinct
+ joins(variant: :product).where(spree_products: { store_id: store.id })
}
def backordered_inventory_units
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 65cf19a236..5a6388c1c8 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -76,11 +76,8 @@ module Spree
has_many :store_payment_methods, class_name: 'Spree::StorePaymentMethod'
has_many :payment_methods, through: :store_payment_methods, class_name: 'Spree::PaymentMethod'
- has_many :product_publications, class_name: 'Spree::ProductPublication', dependent: :destroy
- has_many :products, -> { distinct }, through: :product_publications, class_name: 'Spree::Product'
-
- # @deprecated Alias of {#product_publications}. Remove in Spree 6.0.
- has_many :store_products, class_name: 'Spree::StoreProduct'
+ has_many :products, class_name: 'Spree::Product', dependent: :nullify
+ has_many :product_publications, through: :channels, source: :publications, class_name: 'Spree::ProductPublication'
has_many :variants, through: :products, class_name: 'Spree::Variant', source: :variants_including_master
has_many :stock_items, through: :variants, class_name: 'Spree::StockItem'
has_many :prices, through: :variants, class_name: 'Spree::Price'
diff --git a/spree/core/app/models/spree/store_product.rb b/spree/core/app/models/spree/store_product.rb
deleted file mode 100644
index 0b8cff1eb9..0000000000
--- a/spree/core/app/models/spree/store_product.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-module Spree
- # @deprecated Use {Spree::ProductPublication}. Will be removed in Spree 6.0.
- #
- # Subclasses +ProductPublication+ rather than aliasing the constant so
- # Zeitwerk can resolve +Spree::StoreProduct+ via standard autoload. STI's
- # type column is disabled — the two classes are operationally identical.
- class StoreProduct < Spree::ProductPublication
- self.inheritance_column = nil
- end
-end
diff --git a/spree/core/app/presenters/spree/csv/product_variant_presenter.rb b/spree/core/app/presenters/spree/csv/product_variant_presenter.rb
index cc68bd23c9..46e4b0faa8 100644
--- a/spree/core/app/presenters/spree/csv/product_variant_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/product_variant_presenter.rb
@@ -53,7 +53,7 @@ module Spree
@index = index
@properties = properties
@taxons = taxons
- @store = store || product.stores.first
+ @store = store || product.store
@currency = currency || @store.default_currency
@price_only = @currency != @store.default_currency
@metafields = metafields
@@ -100,8 +100,8 @@ module Spree
variant.dimensions_unit,
variant.weight,
variant.weight_unit,
- variant.available_on&.strftime('%Y-%m-%d %H:%M:%S'),
- (variant.discontinue_on || product.discontinue_on)&.strftime('%Y-%m-%d %H:%M:%S'),
+ publication_available_on&.strftime('%Y-%m-%d %H:%M:%S'),
+ (variant.discontinue_on || publication_discontinue_on)&.strftime('%Y-%m-%d %H:%M:%S'),
variant.track_inventory?,
total_on_hand == BigDecimal::INFINITY ? '∞' : total_on_hand,
variant.backorderable?,
@@ -137,6 +137,26 @@ module Spree
private
+ # Default-channel publication for the export's store. 5.5 transitional:
+ # fall back to the legacy Product columns when the publication dates are
+ # NULL (pre-backfill). 6.0 drops the Product-column fallback.
+ def default_publication
+ return @default_publication if defined?(@default_publication)
+
+ channel_id = store&.default_channel&.id
+ @default_publication = channel_id && product.product_publications.find do |p|
+ p.store_id == store.id && p.channel_id == channel_id
+ end
+ end
+
+ def publication_available_on
+ default_publication&.published_at || product.available_on
+ end
+
+ def publication_discontinue_on
+ default_publication&.unpublished_at || product.discontinue_on
+ end
+
def price_only_row
csv = Array.new(CSV_HEADERS.size)
csv[CSV_HEADERS.index('sku')] = variant.sku
diff --git a/spree/core/app/presenters/spree/search_provider/product_presenter.rb b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
index 94448aab42..4a6d020789 100644
--- a/spree/core/app/presenters/spree/search_provider/product_presenter.rb
+++ b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
@@ -58,7 +58,7 @@ module Spree
status: product.status,
sku: product.sku,
in_stock: product.in_stock?,
- store_ids: product.store_ids.map(&:to_s),
+ store_ids: Array(product.store_id).map(&:to_s),
channel_ids: channel_ids_for_store,
discontinue_on: product.discontinue_on&.to_i || 0,
category_ids: category_ids_with_ancestors,
@@ -68,7 +68,7 @@ module Spree
option_value_ids: variant_option_value_ids,
option_values: variant_option_values_data.map { |ov| translated(ov, :presentation, fallback_locale) }.uniq,
tags: product.tag_list || [],
- units_sold_count: store_publications.sum(:units_sold_count) || 0,
+ units_sold_count: product.units_sold_count || 0,
available_on: product.available_on&.iso8601,
created_at: product.created_at&.iso8601,
updated_at: product.updated_at&.iso8601
@@ -108,14 +108,12 @@ module Spree
@compare_at_cache[currency]
end
- # Returns the product publications for this store
- # @return [Array<Spree::ProductPublication>] the product publications for this store
- def store_publications
- @store_publications ||= product.publications_for_store(store)
- end
-
def channel_ids_for_store
- @channel_ids_for_store ||= store_publications.pluck(:channel_id).map(&:to_s)
+ @channel_ids_for_store ||= product.product_publications
+ .joins(:channel)
+ .where(spree_channels: { store_id: store.id })
+ .pluck(:channel_id)
+ .map(&:to_s)
end
def category_ids_with_ancestors
diff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
index 604ce84abe..b2fcf48e33 100644
--- a/spree/core/app/services/spree/imports/row_processors/product_variant.rb
+++ b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
@@ -98,6 +98,7 @@ module Spree
if product.new_record?
product.slug = attributes['slug']
product.sku = attributes['sku'] if attributes['sku'].present? && options.empty?
+ product.store = store
end
product.name = attributes['name'] if attributes['name'].present?
diff --git a/spree/core/app/services/spree/products/prepare_nested_attributes.rb b/spree/core/app/services/spree/products/prepare_nested_attributes.rb
index b05b253cfe..bdd6f32c8f 100644
--- a/spree/core/app/services/spree/products/prepare_nested_attributes.rb
+++ b/spree/core/app/services/spree/products/prepare_nested_attributes.rb
@@ -67,14 +67,8 @@ module Spree
end
end
- # ensure there is at least one store
- params[:store_ids] = [store.id] if params[:store_ids].blank?
-
- # Preserve taxon associations from other stores
- # Only merge taxon_ids from other stores if taxon_ids are being updated
- if params.key?(:taxon_ids)
- params[:taxon_ids] = merge_taxons_from_other_stores(params[:taxon_ids])
- end
+ # ensure the product is owned by a store
+ params[:store_id] = store.id if params[:store_id].blank? && product.store_id.blank?
# Add empty list for option_type_ids and mark variants as removed if there are no variants and options
if params[:variants_attributes].blank? && variants_to_remove.any? && !params.key?(:option_type_ids)
@@ -186,28 +180,6 @@ module Spree
attributes
end
- # Merges taxon IDs from other stores with submitted taxon IDs from current store.
- #
- # This prevents the loss of taxon associations from other stores when a product
- # is edited in one store. Each store's taxonomy is independent, so editing
- # categories in Store A should not affect categories in Store B.
- #
- # @param submitted_taxon_ids [Array<String>] Taxon IDs from the current store
- # @return [Array<String>] Combined unique taxon IDs
- def merge_taxons_from_other_stores(submitted_taxon_ids)
- return submitted_taxon_ids if product.new_record?
-
- # Get taxon IDs from other stores that should be preserved
- other_stores_taxon_ids = product.taxons
- .joins(:taxonomy)
- .where.not(spree_taxonomies: { store_id: store.id })
- .pluck(:id)
- .map(&:to_s)
-
- # Merge with submitted taxon IDs from current store and remove duplicates
- (submitted_taxon_ids + other_stores_taxon_ids).uniq
- end
-
def update_option_value_variants(option_value_params, existing_variant)
return {} unless option_value_params.present?
return {} unless can_manage_option_types?
diff --git a/spree/core/app/services/spree/sample_data/loader.rb b/spree/core/app/services/spree/sample_data/loader.rb
index 2ea08cd75c..21a29291be 100644
--- a/spree/core/app/services/spree/sample_data/loader.rb
+++ b/spree/core/app/services/spree/sample_data/loader.rb
@@ -15,6 +15,9 @@ module Spree
puts 'Loading sample markets...'
load_ruby_file('markets')
+ puts 'Loading sample channels...'
+ load_ruby_file('channels')
+
puts 'Loading sample metafield definitions...'
load_ruby_file('metafield_definitions')
@@ -24,6 +27,9 @@ module Spree
puts 'Loading sample products...'
load_products
+ puts 'Publishing sample products on the default channel...'
+ publish_sample_products
+
puts 'Loading sample categories...'
load_categories
@@ -70,6 +76,11 @@ module Spree
Spree::SampleData::ImportRunner.call(csv_path: csv_path, import_class: Spree::Imports::Products)
end
+ def publish_sample_products
+ store = Spree::Store.default
+ store.default_channel.add_products(store.product_ids)
+ end
+
def load_categories
store = Spree::Store.default
csv_path = sample_data_path.join('products.csv')
diff --git a/spree/core/app/services/spree/taxons/remove_products.rb b/spree/core/app/services/spree/taxons/remove_products.rb
index 4198e5342a..26da0cad44 100644
--- a/spree/core/app/services/spree/taxons/remove_products.rb
+++ b/spree/core/app/services/spree/taxons/remove_products.rb
@@ -36,7 +36,7 @@ module Spree
if classifications_params.any?
opts = {}
- opts[:unique_by] = :index_spree_products_taxons_on_product_id_and_taxon_id unless ActiveRecord::Base.connection.adapter_name == 'Mysql2'
+ opts[:unique_by] = :index_spree_products_taxons_on_product_id_and_taxon_id unless mysql_adapter?
Spree::Classification.upsert_all(
classifications_params,
@@ -58,6 +58,12 @@ module Spree
success(true)
end
+
+ private
+
+ def mysql_adapter?
+ ActiveRecord::Base.connection.adapter_name.downcase.include?('mysql')
+ end
end
end
end
diff --git a/spree/core/app/subscribers/spree/product_metrics_subscriber.rb b/spree/core/app/subscribers/spree/product_metrics_subscriber.rb
index 854da77f29..e1066a2957 100644
--- a/spree/core/app/subscribers/spree/product_metrics_subscriber.rb
+++ b/spree/core/app/subscribers/spree/product_metrics_subscriber.rb
@@ -1,11 +1,8 @@
# frozen_string_literal: true
module Spree
- # Handles order completion events to update product metrics.
- #
- # When an order is completed, this subscriber enqueues background jobs
- # to refresh the metrics (units_sold_count, revenue) for each product
- # in the order.
+ # Handles order completion events to update product metrics
+ # (+units_sold_count+, +revenue+).
class ProductMetricsSubscriber < Spree::Subscriber
subscribes_to 'order.completed'
@@ -17,12 +14,11 @@ module Spree
order = Spree::Order.find_by_param(order_id)
return unless order
- return unless order.store_id
product_ids = order.line_items.includes(:variant).map { |li| li.variant.product_id }.uniq
return if product_ids.empty?
- jobs = product_ids.map { |product_id| Spree::Products::RefreshMetricsJob.new(product_id, order.store_id) }
+ jobs = product_ids.map { |product_id| Spree::Products::RefreshMetricsJob.new(product_id) }
ActiveJob.perform_all_later(jobs)
end
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 7be29d6990..1f43eb8c02 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -323,10 +323,10 @@ en:
cannot_destroy_if_attached_to_line_items: Cannot delete Products that are added to placed Orders. In such cases, please discontinue them.
discontinue_on:
invalid_date_range: must be later than available date
- spree/product_listing:
+ spree/product_publication:
attributes:
- unlisted_at:
- must_be_after_listed_at: must be after listed at
+ unpublished_at:
+ must_be_after_published_at: must be after published date
spree/promotion:
attributes:
expires_at:
diff --git a/spree/core/db/migrate/20260508204040_create_spree_channels.rb b/spree/core/db/migrate/20260508204040_create_spree_channels.rb
index 1126d982bf..f8bdb3f49a 100644
--- a/spree/core/db/migrate/20260508204040_create_spree_channels.rb
+++ b/spree/core/db/migrate/20260508204040_create_spree_channels.rb
@@ -11,9 +11,8 @@ class CreateSpreeChannels < ActiveRecord::Migration[7.2]
add_index :spree_channels, %i[store_id code], unique: true
- # backfill / create default channel for existing stores
- Spree::Store.find_each do |store|
- store.send(:ensure_default_market)
- end
+ # Default-channel backfill for existing stores lives in
+ # +rake spree:channels:create_defaults+ (data transformations don't belong
+ # in migrations per Spree's guidelines).
end
end
diff --git a/spree/core/db/migrate/20260522000001_add_channel_to_spree_products_stores.rb b/spree/core/db/migrate/20260522000001_add_channel_to_spree_products_stores.rb
deleted file mode 100644
index 99d847c672..0000000000
--- a/spree/core/db/migrate/20260522000001_add_channel_to_spree_products_stores.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-class AddChannelToSpreeProductsStores < ActiveRecord::Migration[7.2]
- def up
- add_reference :spree_products_stores, :channel
- add_column :spree_products_stores, :published_at, :datetime
- add_column :spree_products_stores, :unpublished_at, :datetime
-
- Spree::Store.includes(:default_channel).find_each do |store|
- Spree::ProductPublication.where(store_id: store.id).update_all(channel_id: store.default_channel_id)
- end
- end
-
- def down
- remove_column :spree_products_stores, :unpublished_at
- remove_column :spree_products_stores, :published_at
- remove_reference :spree_products_stores, :channel
- end
-end
diff --git a/spree/core/db/migrate/20260522000002_add_unique_index_to_spree_products_stores.rb b/spree/core/db/migrate/20260522000002_add_unique_index_to_spree_products_stores.rb
deleted file mode 100644
index 16d798d2ee..0000000000
--- a/spree/core/db/migrate/20260522000002_add_unique_index_to_spree_products_stores.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-class AddUniqueIndexToSpreeProductsStores < ActiveRecord::Migration[7.2]
- def up
- remove_index :spree_products_stores, %i[product_id store_id] if index_exists?(:spree_products_stores, %i[product_id store_id])
-
- add_index :spree_products_stores, %i[channel_id product_id store_id],
- unique: true, name: 'index_spree_products_stores_on_channel_product_store'
- end
-
- def down
- remove_index :spree_products_stores, name: 'index_spree_products_stores_on_channel_product_store'
- add_index :spree_products_stores, %i[product_id store_id], unique: true
- end
-end
diff --git a/spree/core/db/migrate/20260601000001_create_spree_product_publications.rb b/spree/core/db/migrate/20260601000001_create_spree_product_publications.rb
new file mode 100644
index 0000000000..43b19e68d8
--- /dev/null
+++ b/spree/core/db/migrate/20260601000001_create_spree_product_publications.rb
@@ -0,0 +1,14 @@
+class CreateSpreeProductPublications < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_product_publications do |t|
+ t.references :product, null: false
+ t.references :channel, null: false
+ t.datetime :published_at
+ t.datetime :unpublished_at
+ t.timestamps
+ end
+
+ add_index :spree_product_publications, %i[product_id channel_id], unique: true,
+ name: 'index_spree_product_publications_on_product_and_channel'
+ end
+end
diff --git a/spree/core/db/migrate/20260601000002_add_store_id_to_spree_products.rb b/spree/core/db/migrate/20260601000002_add_store_id_to_spree_products.rb
new file mode 100644
index 0000000000..0e49757b37
--- /dev/null
+++ b/spree/core/db/migrate/20260601000002_add_store_id_to_spree_products.rb
@@ -0,0 +1,16 @@
+class AddStoreIdToSpreeProducts < ActiveRecord::Migration[7.2]
+ # NOTE: After running this migration, existing products will have
+ # +store_id IS NULL+ and be invisible to +Product.for_store+. Operators
+ # upgrading from 5.4 MUST run the backfill task immediately afterwards:
+ #
+ # bundle exec rake spree:upgrade:populate_publications
+ #
+ # The backfill is also chained from +spree:channels:upgrade+ so the full
+ # 5.4 → 5.5 channel/publication upgrade is one command.
+ def change
+ add_reference :spree_products, :store, null: true
+ add_column :spree_products, :units_sold_count, :integer, default: 0, null: false
+ add_column :spree_products, :revenue, :decimal, precision: 16, scale: 4, default: 0, null: false
+ add_index :spree_products, %i[store_id units_sold_count]
+ end
+end
diff --git a/spree/core/db/migrate/20260602000001_add_default_to_spree_channels.rb b/spree/core/db/migrate/20260602000001_add_default_to_spree_channels.rb
new file mode 100644
index 0000000000..08aa156b9a
--- /dev/null
+++ b/spree/core/db/migrate/20260602000001_add_default_to_spree_channels.rb
@@ -0,0 +1,14 @@
+class AddDefaultToSpreeChannels < ActiveRecord::Migration[7.2]
+ def change
+ add_column :spree_channels, :default, :boolean, null: false, default: false
+
+ # Partial unique index: one default channel per store. Supported on
+ # Postgres and SQLite; MySQL ignores the +where:+ option, so we fall
+ # back to a model-level uniqueness validation there.
+ unless ActiveRecord::Base.connection.adapter_name.match?(/mysql/i)
+ add_index :spree_channels, :store_id, unique: true,
+ where: '"default" = TRUE',
+ name: 'index_spree_channels_default_per_store'
+ end
+ end
+end
diff --git a/spree/core/db/sample_data/channels.rb b/spree/core/db/sample_data/channels.rb
new file mode 100644
index 0000000000..092b00a520
--- /dev/null
+++ b/spree/core/db/sample_data/channels.rb
@@ -0,0 +1,12 @@
+# Adds two extra channels alongside the seeded 'Online Store' so sample data
+# exercises the channel-aware code paths (publishing, channel filters,
+# channel-scoped order attribution).
+store = Spree::Store.default
+
+store.channels.find_or_create_by!(code: 'pos') do |channel|
+ channel.name = 'Point of Sale'
+end
+
+store.channels.find_or_create_by!(code: 'wholesale') do |channel|
+ channel.name = 'Wholesale'
+end
diff --git a/spree/core/lib/spree/core/controller_helpers/store.rb b/spree/core/lib/spree/core/controller_helpers/store.rb
index 794b5ba8d9..f14600a4d8 100644
--- a/spree/core/lib/spree/core/controller_helpers/store.rb
+++ b/spree/core/lib/spree/core/controller_helpers/store.rb
@@ -23,11 +23,6 @@ module Spree
def ensure_current_store(object)
return if object.nil?
- # Models that channel themselves (Product via Spree::Product::Channels)
- # handle store/channel attachment through +set_default_publication+.
- # Skip the legacy +stores << current_store+ shim so we don't build a
- # duplicate publication on the same +(channel, product, store)+.
- return if object.class.method_defined?(:channels)
if object.has_attribute?(:store_id)
if object.store.present? && object.store != current_store
diff --git a/spree/core/lib/spree/testing_support/factories/product_factory.rb b/spree/core/lib/spree/testing_support/factories/product_factory.rb
index a03705b1ed..2007289f3a 100644
--- a/spree/core/lib/spree/testing_support/factories/product_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/product_factory.rb
@@ -7,6 +7,7 @@ FactoryBot.define do
deleted_at { nil }
shipping_category { |r| Spree::ShippingCategory.first || r.association(:shipping_category) }
status { 'active' }
+ store { Spree::Store.default || association(:store) }
transient do
price { 19.99 }
@@ -14,11 +15,8 @@ FactoryBot.define do
currency { nil }
end
- # ensure stock item will be created for this products master
- # also attach this product to the default store if no stores are passed in
before(:create) do |_product|
create(:stock_location) unless Spree::StockLocation.any?
- create(:store, default: true) unless Spree::Store.any?
end
after(:create) do |product, evaluator|
existing_location_ids = product.master.stock_items.pluck(:stock_location_id)
@@ -27,9 +25,23 @@ FactoryBot.define do
end
if evaluator.price.present?
- price_currency = evaluator.currency || product.stores.first&.default_currency || 'USD'
+ price_currency = evaluator.currency || product.store&.default_currency || 'USD'
product.master.set_price(price_currency, evaluator.price, evaluator.compare_at_price)
end
+
+ # Test convenience only: auto-publish each product on its store's
+ # default channel so legacy spec assertions that depend on
+ # current-channel visibility (.active, .available, .not_discontinued)
+ # keep passing. Production callers must publish explicitly via the
+ # Admin SDK / Dashboard create form.
+ if product.store&.default_channel && product.product_publications.empty?
+ Spree::ProductPublication.create!(
+ product: product,
+ channel: product.store.default_channel,
+ published_at: product.available_on,
+ unpublished_at: product.discontinue_on
+ )
+ end
end
factory :custom_product do
diff --git a/spree/core/lib/spree/testing_support/factories/product_publication_factory.rb b/spree/core/lib/spree/testing_support/factories/product_publication_factory.rb
index b5771bdd5e..7d3a0f3736 100644
--- a/spree/core/lib/spree/testing_support/factories/product_publication_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/product_publication_factory.rb
@@ -1,7 +1,6 @@
FactoryBot.define do
factory :product_publication, class: Spree::ProductPublication do
product
- store { product&.stores&.first || Spree::Store.default || association(:store) }
- channel { store&.default_channel }
+ channel { product&.store&.default_channel || association(:channel) }
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/store_product_factory.rb b/spree/core/lib/spree/testing_support/factories/store_product_factory.rb
deleted file mode 100644
index 5fee39c335..0000000000
--- a/spree/core/lib/spree/testing_support/factories/store_product_factory.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-FactoryBot.define do
- factory :store_product, class: Spree::StoreProduct do
- store
- product
- end
-end
diff --git a/spree/core/lib/spree/testing_support/factories/variant_factory.rb b/spree/core/lib/spree/testing_support/factories/variant_factory.rb
index 522e0fe183..82904f6eef 100644
--- a/spree/core/lib/spree/testing_support/factories/variant_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/variant_factory.rb
@@ -35,7 +35,7 @@ FactoryBot.define do
end
if evaluator.price.present?
- price_currency = evaluator.currency || variant.product&.stores&.first&.default_currency || 'USD'
+ price_currency = evaluator.currency || variant.product&.store&.default_currency || 'USD'
variant.set_price(price_currency, evaluator.price, evaluator.compare_at_price)
end
end
diff --git a/spree/core/lib/tasks/channels.rake b/spree/core/lib/tasks/channels.rake
index e757f0cf0b..6fe19e1dee 100644
--- a/spree/core/lib/tasks/channels.rake
+++ b/spree/core/lib/tasks/channels.rake
@@ -1,5 +1,19 @@
namespace :spree do
namespace :channels do
+ desc 'Create the default channel for every existing store (idempotent — calls Store#ensure_default_channel).'
+ task create_defaults: :environment do
+ created = 0
+ Spree::Store.find_each do |store|
+ next if store.default_channel
+
+ store.ensure_default_channel
+ created += 1
+ puts " Created default channel for store '#{store.name}'"
+ end
+
+ puts created.zero? ? ' All stores already have a default channel.' : " Created #{created} default channel(s)."
+ end
+
desc 'Backfill spree_orders.channel_id from the legacy spree_orders.channel string column'
task backfill_order_channel_ids: :environment do
# Idempotent: only touches orders where channel_id is nil. Safe to
@@ -51,17 +65,27 @@ namespace :spree do
products_with_dates.find_each(batch_size: 500) do |product|
publications = Spree::ProductPublication.where(product_id: product.id)
+ # Read raw columns — +product.available_on+ / +product.discontinue_on+
+ # go through +Product::Channels+'s reader override which prefers the
+ # current-channel publication's date (which is nil pre-backfill).
+ legacy_available_on = product[:available_on]
+ legacy_discontinue_on = product[:discontinue_on]
- published += publications.where(published_at: nil).update_all(published_at: product.available_on) if product.available_on
- unpublished += publications.where(unpublished_at: nil).update_all(unpublished_at: product.discontinue_on) if product.discontinue_on
+ published += publications.where(published_at: nil).update_all(published_at: legacy_available_on) if legacy_available_on
+ unpublished += publications.where(unpublished_at: nil).update_all(unpublished_at: legacy_discontinue_on) if legacy_discontinue_on
end
total = published + unpublished
puts total.zero? ? ' All product-publication dates already populated.' : " Backfilled dates on #{published} published_at + #{unpublished} unpublished_at column(s)."
end
- desc 'Run the full 5.4 → 5.5 channel upgrade: create defaults, backfill order channels, backfill product-publication channel ids and dates'
- task upgrade: %i[backfill_order_channel_ids backfill_product_publication_dates]
+ desc 'Run the full 5.4 → 5.5 channel upgrade: create default channels, backfill products to store_id and publications, backfill order channels, backfill publication date windows'
+ task upgrade: [
+ :create_defaults,
+ 'spree:upgrade:populate_publications',
+ :backfill_order_channel_ids,
+ :backfill_product_publication_dates
+ ]
def legacy_channel_column?
ActiveRecord::Base.connection.column_exists?(:spree_orders, :channel)
diff --git a/spree/core/lib/tasks/products.rake b/spree/core/lib/tasks/products.rake
index d0af635d5e..70d902ccaa 100644
--- a/spree/core/lib/tasks/products.rake
+++ b/spree/core/lib/tasks/products.rake
@@ -19,21 +19,19 @@ namespace :spree do
puts "\nDone!"
end
- desc 'Enqueue background jobs to populate product metrics for all store products'
+ desc 'Enqueue background jobs to populate product metrics for every product'
task populate_metrics: :environment do
total_count = 0
- Spree::ProductPublication.in_batches(of: 100) do |batch|
- jobs = batch.pluck(:product_id, :store_id).map do |product_id, store_id|
- Spree::Products::RefreshMetricsJob.new(product_id, store_id)
- end
+ Spree::Product.in_batches(of: 100) do |batch|
+ jobs = batch.pluck(:id).map { |product_id| Spree::Products::RefreshMetricsJob.new(product_id) }
ActiveJob.perform_all_later(jobs)
total_count += jobs.size
print '.'
end
if total_count.zero?
- puts 'No store products found.'
+ puts 'No products found.'
else
puts "\nEnqueued #{total_count} jobs to refresh product metrics."
end
diff --git a/spree/core/lib/tasks/publications.rake b/spree/core/lib/tasks/publications.rake
new file mode 100644
index 0000000000..c01f0abe86
--- /dev/null
+++ b/spree/core/lib/tasks/publications.rake
@@ -0,0 +1,85 @@
+namespace :spree do
+ namespace :upgrade do
+ desc <<~DESC
+ Populates +spree_products.store_id+ and +spree_product_publications+ from the legacy
+ +spree_products_stores+ join. Idempotent — re-running skips products that
+ already have a +store_id+ and channels that already have a publication for
+ the product.
+
+ Run once after upgrading to Spree 5.5+. Multi-store merchants must install
+ +spree_multi_store+ before running; running on a multi-store catalog without
+ the extension picks one "home" store per product per the rules below:
+
+ 1. The store flagged +default: true+ if the product is published there
+ 2. Otherwise the first store (by +spree_products_stores.created_at+)
+ DESC
+ task populate_publications: :environment do
+ legacy_table = 'spree_products_stores'
+
+ unless ActiveRecord::Base.connection.table_exists?(legacy_table)
+ puts " #{legacy_table} table not found — nothing to migrate."
+ next
+ end
+
+ products_processed = 0
+ publications_created = 0
+
+ # Legacy +spree_products_stores+ pre-5.5 carries only product_id,
+ # store_id, created_at (plus the +units_sold_count+/+revenue+ columns
+ # we no longer read here). Channel attribution + publication windows
+ # are derived from the destination store's default channel.
+ Spree::Product.where(store_id: nil).find_each do |product|
+ sql = ActiveRecord::Base.sanitize_sql_array([
+ "SELECT store_id, created_at FROM #{legacy_table} WHERE product_id = ? ORDER BY created_at ASC",
+ product.id
+ ])
+ rows = ActiveRecord::Base.connection.select_all(sql).to_a
+
+ next if rows.empty?
+
+ home_store_id = pick_home_store(rows)
+ store_ids = rows.map { |r| r['store_id'] }.uniq
+
+ # Build publications + store_id assignment atomically. If the
+ # publication writes fail (validation, deadlock, etc.) we rollback
+ # so a re-run can retry — the +store_id IS NULL+ filter at the top
+ # of the loop only matches products that didn't finish.
+ ActiveRecord::Base.transaction do
+ store_ids.each do |store_id|
+ channel = Spree::Store.find(store_id).default_channel
+ next unless channel
+
+ publication = Spree::ProductPublication.find_or_initialize_by(
+ product_id: product.id,
+ channel_id: channel.id
+ )
+
+ next if publication.persisted?
+
+ publication.save!
+ publications_created += 1
+ end
+
+ product.update_column(:store_id, home_store_id)
+ end
+
+ products_processed += 1
+ end
+
+ puts " Processed #{products_processed} products"
+ puts " Created #{publications_created} publications"
+ end
+
+ # When a product was attached to multiple stores via the legacy join,
+ # pick the default store if it's in the list — otherwise the earliest
+ # row (rows are pre-sorted by +created_at+).
+ def pick_home_store(rows)
+ default_store_id = Spree::Store.find_by(default: true)&.id
+ if default_store_id && rows.any? { |r| r['store_id'] == default_store_id }
+ default_store_id
+ else
+ rows.first['store_id']
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/finders/spree/variants/option_types_finder_spec.rb b/spree/core/spec/finders/spree/variants/option_types_finder_spec.rb
index 77972142c2..eba5d0744f 100644
--- a/spree/core/spec/finders/spree/variants/option_types_finder_spec.rb
+++ b/spree/core/spec/finders/spree/variants/option_types_finder_spec.rb
@@ -7,7 +7,7 @@ describe Spree::Variants::OptionTypesFinder do
let(:option_type_1) { create :option_type, position: 2 }
let(:option_type_2) { create :option_type, position: 1 }
- let(:product) { create :product, option_types: [option_type_1, option_type_2], stores: [store] }
+ let(:product) { create :product, option_types: [option_type_1, option_type_2], store: store }
let!(:variant_1) { create :variant, product: product, option_values: [option_value_1_1, option_value_2_2] }
let!(:variant_2) { create :variant, product: product, option_values: [option_value_1_2, option_value_2_1] }
diff --git a/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb b/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb
index f26e94d47b..54150c1503 100644
--- a/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb
+++ b/spree/core/spec/jobs/spree/products/refresh_metrics_job_spec.rb
@@ -3,46 +3,33 @@ require 'spec_helper'
RSpec.describe Spree::Products::RefreshMetricsJob, type: :job do
describe '#perform' do
let(:store) { @default_store }
- let(:product) { create(:product) }
- let(:store_product) { product.store_products.find_by(store: store) }
+ let(:product) { create(:product, store: store) }
- subject { described_class.perform_now(product.id, store.id) }
+ subject { described_class.perform_now(product.id) }
- context 'when store_product exists' do
- it 'calls refresh_metrics! on the store_product' do
- expect_any_instance_of(Spree::ProductPublication).to receive(:refresh_metrics!)
+ context 'when the product has completed orders' do
+ let!(:order) { create(:completed_order_with_totals, line_items_price: 50, store: store, variants: [product.master]) }
+ it 'sets +units_sold_count+ and +revenue+ on the product from completed line items' do
subject
+ expect(product.reload.units_sold_count).to be > 0
+ expect(product.reload.revenue).to be > 0
end
end
- context 'when store_product does not exist' do
- subject { described_class.perform_now(product.id, create(:store).id) }
-
- it 'does nothing' do
- expect_any_instance_of(Spree::ProductPublication).not_to receive(:refresh_metrics!)
-
+ context 'when the product has no completed orders' do
+ it 'leaves the metrics at zero' do
subject
+ expect(product.reload.units_sold_count).to eq(0)
+ expect(product.reload.revenue).to eq(0)
end
end
context 'when product_id is invalid' do
- subject { described_class.perform_now('non-existent-id', store.id) }
-
- it 'does nothing' do
- expect_any_instance_of(Spree::ProductPublication).not_to receive(:refresh_metrics!)
-
- subject
- end
- end
-
- context 'when store_id is invalid' do
- subject { described_class.perform_now(product.id, 'non-existent-id') }
+ subject { described_class.perform_now('non-existent-id') }
- it 'does nothing' do
- expect_any_instance_of(Spree::ProductPublication).not_to receive(:refresh_metrics!)
-
- subject
+ it 'is a no-op' do
+ expect { subject }.not_to raise_error
end
end
end
diff --git a/spree/core/spec/lib/tasks/channels_spec.rb b/spree/core/spec/lib/tasks/channels_spec.rb
index b914aed447..6a97008d2e 100644
--- a/spree/core/spec/lib/tasks/channels_spec.rb
+++ b/spree/core/spec/lib/tasks/channels_spec.rb
@@ -27,19 +27,26 @@ describe 'spree:channels:backfill_product_publication_dates' do
)
end
end
+ # The product factory auto-publishes on the store's default channel, so
+ # reuse that publication rather than creating another (which would collide
+ # on the (product, channel) uniqueness index).
let!(:publication) do
- create(:product_publication, product: product, store: store).tap do |l|
+ product.product_publications.first.tap do |l|
l.update_columns(published_at: nil, unpublished_at: nil)
end
end
+ # +product.available_on+ / +product.discontinue_on+ go through the
+ # +Product::Channels+ reader override which prefers the current-channel
+ # publication's date over the legacy column. Read the raw attribute via
+ # +[:column]+ to assert against the legacy value the rake task copies from.
it 'copies available_on into published_at when published_at is NULL' do
- expect { subject.invoke }.to change { publication.reload.published_at }.from(nil).to(product.available_on)
+ expect { subject.invoke }.to change { publication.reload.published_at }.from(nil).to(product[:available_on])
end
it 'copies discontinue_on into unpublished_at when unpublished_at is NULL' do
subject.invoke
- expect(publication.reload.unpublished_at).to eq(product.discontinue_on)
+ expect(publication.reload.unpublished_at).to eq(product[:discontinue_on])
end
it 'preserves publication dates that are already populated' do
diff --git a/spree/core/spec/models/spree/channel_spec.rb b/spree/core/spec/models/spree/channel_spec.rb
index 736b15cb03..145ab7fb3a 100644
--- a/spree/core/spec/models/spree/channel_spec.rb
+++ b/spree/core/spec/models/spree/channel_spec.rb
@@ -134,6 +134,19 @@ RSpec.describe Spree::Channel, type: :model do
expect(publication.published_at).to be_within(1.second).of(future)
end
+ it 'preserves existing publication windows when re-published without dates' do
+ future_start = 1.day.from_now.change(usec: 0)
+ future_end = 1.week.from_now.change(usec: 0)
+ channel.add_products([product.id], published_at: future_start, unpublished_at: future_end)
+
+ # Re-publish without window kwargs — the existing schedule must survive.
+ channel.add_products([product.id])
+
+ publication = Spree::ProductPublication.find_by(channel: channel, product: product)
+ expect(publication.published_at).to be_within(1.second).of(future_start)
+ expect(publication.unpublished_at).to be_within(1.second).of(future_end)
+ end
+
it 'is a no-op when product_ids is empty' do
expect(channel.add_products([])).to eq(0)
end
diff --git a/spree/core/spec/models/spree/order/totals_spec.rb b/spree/core/spec/models/spree/order/totals_spec.rb
index 72bc6e9093..347b208d5a 100644
--- a/spree/core/spec/models/spree/order/totals_spec.rb
+++ b/spree/core/spec/models/spree/order/totals_spec.rb
@@ -7,7 +7,7 @@ module Spree
let(:shirt) { create(:variant) }
context 'adds item to cart and activates promo' do
- let(:promotion) { create(:promotion, name: 'Huhu', stores: [store], kind: :automatic) }
+ let(:promotion) { create(:promotion, name: 'Huhu', kind: :automatic) }
let(:calculator) { Calculator::FlatPercentItemTotal.new(preferred_flat_percent: 10) }
let!(:action) { Promotion::Actions::CreateAdjustment.create(promotion: promotion, calculator: calculator) }
diff --git a/spree/core/spec/models/spree/order_contents_spec.rb b/spree/core/spec/models/spree/order_contents_spec.rb
index 70db5ab1bd..a5861e08a1 100644
--- a/spree/core/spec/models/spree/order_contents_spec.rb
+++ b/spree/core/spec/models/spree/order_contents_spec.rb
@@ -66,7 +66,7 @@ describe Spree::OrderContents, type: :model do
end
context 'running promotions' do
- let(:promotion) { create(:promotion, stores: [store], kind: :automatic) }
+ let(:promotion) { create(:promotion, kind: :automatic, stores: [store]) }
let(:calculator) { Spree::Calculator::FlatRate.new(preferred_amount: 10) }
shared_context 'discount changes order total' do
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 8cf284a7ea..638e688ef6 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -1808,7 +1808,7 @@ describe Spree::Order, type: :model do
let!(:order) { create(:order_with_line_items, line_items_count: 2) }
let!(:credit_card_payment_method) { create(:simple_credit_card_payment_method, display_on: 'both') }
let!(:store_credit_payment_method) { create(:store_credit_payment_method, display_on: 'both') }
- let!(:inactive_payment_method) { create(:simple_credit_card_payment_method, display_on: 'both', stores: [store], active: false) }
+ let!(:inactive_payment_method) { create(:simple_credit_card_payment_method, display_on: 'both', active: false) }
it { expect(order.collect_backend_payment_methods).to include(credit_card_payment_method) }
it { expect(order.collect_backend_payment_methods).not_to include(store_credit_payment_method) }
diff --git a/spree/core/spec/models/spree/product/scopes_spec.rb b/spree/core/spec/models/spree/product/scopes_spec.rb
index df2a6e7789..05835400c9 100644
--- a/spree/core/spec/models/spree/product/scopes_spec.rb
+++ b/spree/core/spec/models/spree/product/scopes_spec.rb
@@ -187,7 +187,7 @@ describe 'Product scopes', type: :model do
let(:another_store) { create(:store) }
before do
- create_list(:product, 3, stores: [another_store])
+ create_list(:product, 3, store: another_store)
end
it 'returns products assigned to a store' do
@@ -274,7 +274,7 @@ describe 'Product scopes', type: :model do
def refresh_all_metrics!
[product_1, product_2, product_3, product_4].each do |p|
- p.store_products.find_by(store: store)&.refresh_metrics!
+ Spree::Products::RefreshMetricsJob.new.perform(p.id)
end
end
@@ -321,8 +321,8 @@ describe 'Product scopes', type: :model do
products = store.products.where(id: test_product_ids).by_best_selling
expect(products.first.name).to eq('Product 1')
- product_1_store_product = product_1.store_products.find_by(store: store)
- product_2_store_product = product_2.store_products.find_by(store: store)
+ product_1_store_product = product_1.reload
+ product_2_store_product = product_2.reload
expect(product_1_store_product.units_sold_count).to eq(2)
expect(product_2_store_product.units_sold_count).to eq(1)
@@ -347,8 +347,8 @@ describe 'Product scopes', type: :model do
expect(products.first.name).to eq('Product 2')
expect(products.second.name).to eq('Product 1')
- product_1_store_product = product_1.store_products.find_by(store: store)
- product_2_store_product = product_2.store_products.find_by(store: store)
+ product_1_store_product = product_1.reload
+ product_2_store_product = product_2.reload
expect(product_2_store_product.revenue).to be > product_1_store_product.revenue
end
@@ -373,8 +373,8 @@ describe 'Product scopes', type: :model do
it 'sums line item quantities for units_sold_count' do
products = store.products.where(id: test_product_ids).by_best_selling
- product_1_store_product = product_1.store_products.find_by(store: store)
- product_2_store_product = product_2.store_products.find_by(store: store)
+ product_1_store_product = product_1.reload
+ product_2_store_product = product_2.reload
# Product 1: 2 + 3 = 5 units
expect(product_1_store_product.units_sold_count).to eq(5)
@@ -408,8 +408,8 @@ describe 'Product scopes', type: :model do
it 'ranks by total units sold across all orders' do
products = store.products.where(id: test_product_ids).by_best_selling
- product_1_store_product = product_1.store_products.find_by(store: store)
- product_2_store_product = product_2.store_products.find_by(store: store)
+ product_1_store_product = product_1.reload
+ product_2_store_product = product_2.reload
# Product 1: 3 + 2 = 5 units sold
expect(product_1_store_product.units_sold_count).to eq(5)
@@ -432,7 +432,7 @@ describe 'Product scopes', type: :model do
expect(products.length).to eq(4)
# All products should be included, those without orders have units_sold_count = 0
[product_1, product_2, product_3, product_4].each do |p|
- store_product = p.store_products.find_by(store: store)
+ store_product = p.reload
expect(store_product.units_sold_count).to eq(0)
expect(store_product.revenue).to eq(0)
end
@@ -462,10 +462,10 @@ describe 'Product scopes', type: :model do
# All products should be included
expect(products.length).to eq(4)
- product_1_sp = product_1.store_products.find_by(store: store)
- product_2_sp = product_2.store_products.find_by(store: store)
- product_3_sp = product_3.store_products.find_by(store: store)
- product_4_sp = product_4.store_products.find_by(store: store)
+ product_1_sp = product_1.reload
+ product_2_sp = product_2.reload
+ product_3_sp = product_3.reload
+ product_4_sp = product_4.reload
# Product 2 has pending orders but no completed orders - count should be 0
expect(product_2_sp.units_sold_count).to eq(0)
@@ -556,7 +556,7 @@ describe 'Product scopes', type: :model do
let(:channel) { store.default_channel }
let!(:active_product) { create(:product, price: 9.99, status: 'active') }
let(:draft_product) { create(:product, price: 9.99, status: 'draft') }
- let(:active_publication) { active_product.product_publications.find_by(store: store, channel: channel) }
+ let(:active_publication) { active_product.product_publications.find_by(channel: channel) }
context '.active(currency) under Spree::Current.channel' do
let!(:pos_channel) { create(:channel, store: store, code: 'pos', name: 'POS') }
@@ -578,7 +578,7 @@ describe 'Product scopes', type: :model do
it 'excludes products that are listed on a different channel only' do
active_publication.destroy
- create(:product_publication, product: active_product, store: store, channel: pos_channel)
+ create(:product_publication, product: active_product, channel: pos_channel)
expect(Spree::Product.active('USD')).not_to include(active_product)
end
end
diff --git a/spree/core/spec/models/spree/product_publication_spec.rb b/spree/core/spec/models/spree/product_publication_spec.rb
index fac6411708..d2cab16a2c 100644
--- a/spree/core/spec/models/spree/product_publication_spec.rb
+++ b/spree/core/spec/models/spree/product_publication_spec.rb
@@ -3,28 +3,30 @@ require 'spec_helper'
RSpec.describe Spree::ProductPublication, type: :model do
let(:store) { @default_store }
let(:channel) { store.default_channel }
- let(:product) { create(:product) }
+ let(:product) { create(:product, store: store) }
- # +StoreScopedResource+ auto-attaches every product to +Store.default+,
- # so tests needing a pristine (product, store) slot use this pair.
let(:other_store) { create(:store, default: false, code: 'other') }
let(:other_channel) { other_store.default_channel }
+ # A second channel on the *same* store as +product+, so we can build a
+ # second publication against the same product without colliding with the
+ # default publication the create-callback already attached.
+ let(:secondary_channel) { create(:channel, store: store, code: 'pos', name: 'POS') }
describe 'validations' do
- it 'is valid with product, store, and channel' do
- publication = build(:product_publication, product: product, store: other_store, channel: other_channel)
+ it 'is valid with product and channel' do
+ publication = build(:product_publication, product: product, channel: secondary_channel)
expect(publication).to be_valid
end
- it 'enforces uniqueness per (product, store)' do
- duplicate = build(:product_publication, product: product, store: store, channel: channel)
+ it 'enforces uniqueness per (product, channel)' do
+ duplicate = build(:product_publication, product: product, channel: channel)
expect(duplicate).not_to be_valid
end
it 'rejects unpublished_at before published_at' do
publication = build(
:product_publication,
- product: product, store: other_store, channel: other_channel,
+ product: product, channel: secondary_channel,
published_at: 1.day.from_now, unpublished_at: 1.hour.from_now
)
expect(publication).not_to be_valid
@@ -32,24 +34,24 @@ RSpec.describe Spree::ProductPublication, type: :model do
end
end
- describe 'channel auto-assignment' do
- it 'derives channel from store.default_channel when only store is given' do
- publication = Spree::ProductPublication.new(product: product, store: other_store)
- publication.valid?
- expect(publication.channel).to eq(other_store.default_channel)
+ describe '#store delegation' do
+ it 'returns the channel.store' do
+ publication = build(:product_publication, product: product, channel: secondary_channel)
+ expect(publication.store).to eq(store)
+ expect(publication.store_id).to eq(store.id)
end
end
describe '.published' do
it 'includes publications with null dates' do
- publication = create(:product_publication, product: product, store: other_store, channel: other_channel)
+ publication = create(:product_publication, product: product, channel: secondary_channel)
expect(described_class.published).to include(publication)
end
it 'excludes publications with future published_at' do
publication = create(
:product_publication,
- product: product, store: other_store, channel: other_channel,
+ product: product, channel: secondary_channel,
published_at: 1.day.from_now
)
expect(described_class.published).not_to include(publication)
@@ -58,7 +60,7 @@ RSpec.describe Spree::ProductPublication, type: :model do
it 'excludes publications with past unpublished_at' do
publication = create(
:product_publication,
- product: product, store: other_store, channel: other_channel,
+ product: product, channel: secondary_channel,
published_at: 2.days.ago, unpublished_at: 1.day.ago
)
expect(described_class.published).not_to include(publication)
@@ -67,18 +69,18 @@ RSpec.describe Spree::ProductPublication, type: :model do
describe '#published?' do
it 'is true when dates are nil' do
- expect(build(:product_publication, product: product, store: other_store, channel: other_channel).published?).to be true
+ expect(build(:product_publication, product: product, channel: secondary_channel).published?).to be true
end
it 'is false when published_at is in the future' do
- publication = build(:product_publication, product: product, store: other_store, channel: other_channel, published_at: 1.day.from_now)
+ publication = build(:product_publication, product: product, channel: secondary_channel, published_at: 1.day.from_now)
expect(publication.published?).to be false
end
it 'is false when unpublished_at is in the past' do
publication = build(
:product_publication,
- product: product, store: other_store, channel: other_channel,
+ product: product, channel: secondary_channel,
published_at: 2.days.ago, unpublished_at: 1.day.ago
)
expect(publication.published?).to be false
@@ -86,14 +88,9 @@ RSpec.describe Spree::ProductPublication, type: :model do
end
describe 'associations on Product' do
- let(:product_with_store) { create(:product) }
-
- it 'reaches stores through product_publications' do
- expect(product_with_store.stores).to include(store)
- end
-
it 'reaches channels through product_publications' do
- expect(product_with_store.channels).to include(channel)
+ product.product_publications.create!(channel: secondary_channel)
+ expect(product.reload.channels).to include(secondary_channel)
end
end
end
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index 927d2a9296..ee92c7d97f 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -19,7 +19,7 @@ describe Spree::Product, type: :model do
let!(:tax_category_2) { create(:tax_category, is_default: true) }
context 'when product is new' do
- let(:product) { described_class.new(stores: [store]) }
+ let(:product) { described_class.new(store: store) }
it 'assigns default tax category' do
expect(product.tax_category.id).to eq(tax_category_2.id)
@@ -113,7 +113,7 @@ describe Spree::Product, type: :model do
describe '#duplicate' do
before do
- allow(product).to receive_messages taxons: [build(:taxon)], stores: [store]
+ allow(product).to receive_messages taxons: [build(:taxon)], store: store
end
it 'duplicates product' do
@@ -125,7 +125,7 @@ describe Spree::Product, type: :model do
expect(clone.slug).to eq("copy-of-#{product.slug}")
expect(clone.master.sku).to eq("COPY OF #{product.master.sku}")
expect(clone.taxons).to eq(product.taxons)
- expect(clone.stores).to eq(product.stores)
+ expect(clone.store).to eq(product.store)
expect(clone.images.size).to eq(product.images.size)
end
@@ -1075,37 +1075,36 @@ describe Spree::Product, type: :model do
end
end
- describe '#ensure_store_presence' do
- let(:product) { create(:product, stores: []) }
-
+ describe 'default store assignment' do
context 'no store passed' do
- it 'auto-assigns store' do
- expect(product.stores).to eq([Spree::Store.default])
+ let(:product) { create(:product, store: nil) }
+
+ it 'auto-assigns the default store' do
+ expect(product.store).to eq(Spree::Store.default)
end
end
context 'store passed' do
- let(:store) { Spree::Store.default }
- let(:product) { create(:product) }
+ let(:product) { create(:product, store: store) }
- it 'does not auto-assign store' do
- expect(product.stores).to eq([store])
+ it 'uses the passed store' do
+ expect(product.store).to eq(store)
end
end
end
describe '#taxons_for_store' do
- let(:store_2) { create(:store) }
- let(:product) { create(:product, stores: [store, store_2], taxons: [taxon, taxon_2]) }
+ let(:product) { create(:product, store: store, taxons: [taxon]) }
let(:taxonomy) { create(:taxonomy, store: store) }
- let(:taxonomy_2) { create(:taxonomy, store: store_2) }
let(:taxon) { create(:taxon, taxonomy: taxonomy) }
- let(:taxon_2) { create(:taxon, taxonomy: taxonomy_2) }
- let(:taxon_3) { create(:taxon, taxonomy: taxonomy) }
- it 'returns product taxons for specified store' do
+ it 'returns product taxons for the matching store' do
expect(product.taxons_for_store(store)).to eq([taxon])
- expect(product.taxons_for_store(store_2)).to eq([taxon_2])
+ end
+
+ it 'returns an empty relation for an unrelated store' do
+ other_store = create(:store)
+ expect(product.taxons_for_store(other_store)).to be_empty
end
end
@@ -1222,14 +1221,7 @@ describe Spree::Product, type: :model do
end
context 'when store is not provided' do
- it 'uses default store' do
- allow(product.stores).to receive(:default).and_return(store)
- expect(product.to_csv).to be_present
- end
-
- it 'falls back to first store if no default' do
- allow(product.stores).to receive(:default).and_return(nil)
- allow(product.stores).to receive(:first).and_return(store)
+ it "uses the product's own store" do
expect(product.to_csv).to be_present
end
end
@@ -1897,7 +1889,7 @@ describe Spree::Product, type: :model do
name: 'Deferred',
price: 10,
shipping_category: shipping_category,
- stores: [store],
+ store: store,
variants: [{ sku: 'DEF-1', options: [{ name: 'Color', value: 'Red' }] }]
)
new_product.save!
@@ -1925,7 +1917,7 @@ describe Spree::Product, type: :model do
name: 'Test',
price: 10,
shipping_category: create(:shipping_category),
- stores: [store],
+ store: store,
tax_category_id: custom_tc.id
)
product.save!
@@ -1938,7 +1930,7 @@ describe Spree::Product, type: :model do
name: 'Test',
price: 10,
shipping_category: create(:shipping_category),
- stores: [store]
+ store: store
)
expect(product.tax_category).to eq(default_tc)
@@ -1946,11 +1938,9 @@ describe Spree::Product, type: :model do
end
context 'Channels' do
- let!(:other_store) { create(:store, code: 'second', default: false) }
- let!(:product_with_two_stores) { create(:product, stores: [store, other_store]) }
-
- let(:publication_a) { product_with_two_stores.product_publications.find_by(store: store) }
- let(:publication_b) { product_with_two_stores.product_publications.find_by(store: other_store) }
+ let!(:product) { create(:product, store: store) }
+ let(:default_channel) { store.default_channel }
+ let(:publication) { product.product_publications.find_by(channel: default_channel) }
let(:target) { 1.week.from_now.change(usec: 0) }
before do
@@ -1958,45 +1948,37 @@ describe Spree::Product, type: :model do
end
context 'associations' do
- it 'exposes product_publications, stores, and channels through the same join' do
- expect(product_with_two_stores.product_publications.count).to eq(2)
- expect(product_with_two_stores.stores).to contain_exactly(store, other_store)
- expect(product_with_two_stores.channels).to contain_exactly(store.default_channel, other_store.default_channel)
- end
-
- it 'aliases store_products to product_publications for back-compat' do
- expect(product_with_two_stores.store_products.count).to eq(product_with_two_stores.product_publications.count)
+ it 'reaches channels through product_publications' do
+ expect(product.reload.channels).to contain_exactly(default_channel)
end
end
context '#available_on=' do
it 'emits a deprecation warning' do
- product_with_two_stores.available_on = target
+ product.available_on = target
expect(Spree::Deprecation).to have_received(:warn).with(/available_on=.*deprecated/)
end
it 'still writes the legacy column for backward-compatible reads' do
- product_with_two_stores.update!(available_on: target)
- expect(product_with_two_stores.reload.available_on).to eq(target)
+ product.update!(available_on: target)
+ expect(product.reload.available_on).to eq(target)
end
it 'cascades to published_at on every publication via autosave' do
- product_with_two_stores.update!(available_on: target)
- expect(publication_a.reload.published_at).to eq(target)
- expect(publication_b.reload.published_at).to eq(target)
+ product.update!(available_on: target)
+ expect(publication.reload.published_at).to eq(target)
end
end
context '#discontinue_on=' do
it 'emits a deprecation warning' do
- product_with_two_stores.discontinue_on = target
+ product.discontinue_on = target
expect(Spree::Deprecation).to have_received(:warn).with(/discontinue_on=.*deprecated/)
end
it 'cascades to unpublished_at on every publication' do
- product_with_two_stores.update!(discontinue_on: target)
- expect(publication_a.reload.unpublished_at).to eq(target)
- expect(publication_b.reload.unpublished_at).to eq(target)
+ product.update!(discontinue_on: target)
+ expect(publication.reload.unpublished_at).to eq(target)
end
end
@@ -2005,36 +1987,34 @@ describe Spree::Product, type: :model do
context 'with hash params' do
it 'creates new publications keyed by channel_id' do
- fresh_product = create(:product)
- existing = fresh_product.product_publications.first
- fresh_product.product_publications = [
- { id: existing.prefixed_id, published_at: target },
+ product.product_publications = [
+ { id: publication.prefixed_id, published_at: target },
{ channel_id: pos_channel.prefixed_id, published_at: target }
]
- expect(fresh_product.product_publications.count).to eq(2)
- expect(fresh_product.product_publications.find_by(channel: pos_channel).published_at).to eq(target)
+ expect(product.product_publications.count).to eq(2)
+ expect(product.product_publications.find_by(channel: pos_channel).published_at).to eq(target)
end
it 'updates existing publications by prefixed id' do
- publication = product_with_two_stores.product_publications.first
- product_with_two_stores.product_publications = [
- { id: publication.prefixed_id, published_at: target },
- { id: product_with_two_stores.product_publications.last.prefixed_id }
+ product.product_publications = [
+ { id: publication.prefixed_id, published_at: target }
]
expect(publication.reload.published_at).to eq(target)
end
it 'removes publications not in the payload' do
- publication_a_id = product_with_two_stores.product_publications.find_by(store: store).id
- product_with_two_stores.product_publications = [{ id: Spree::ProductPublication.find(publication_a_id).prefixed_id }]
+ # Add a second publication on pos_channel, then submit a payload that
+ # only mentions the original — the pos one should be destroyed.
+ product.product_publications.create!(channel: pos_channel)
+ product.product_publications = [{ id: publication.prefixed_id }]
- expect(product_with_two_stores.product_publications.reload.pluck(:id)).to eq([publication_a_id])
+ expect(product.product_publications.reload.pluck(:id)).to eq([publication.id])
end
it 'defers creation on new records' do
- new_product = build(:product, stores: [])
+ new_product = build(:product, store: store)
new_product.product_publications = [{ channel_id: store.default_channel.prefixed_id, published_at: target }]
new_product.save!
@@ -2045,10 +2025,10 @@ describe Spree::Product, type: :model do
context 'with ProductPublication objects' do
it 'passes through to the ActiveRecord setter' do
- fresh = create(:product)
- publication = fresh.product_publications.first
- fresh.product_publications = [publication]
- expect(fresh.product_publications).to include(publication)
+ fresh = create(:product, store: store)
+ pub = fresh.product_publications.first
+ fresh.product_publications = [pub]
+ expect(fresh.product_publications).to include(pub)
end
end
end
diff --git a/spree/core/spec/models/spree/promotion_handler/cart_spec.rb b/spree/core/spec/models/spree/promotion_handler/cart_spec.rb
index 80688d3f11..d21a9ac06a 100644
--- a/spree/core/spec/models/spree/promotion_handler/cart_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/cart_spec.rb
@@ -34,7 +34,7 @@ module Spree
end
context 'promotion has item total rule' do
- let(:shirt) { create(:product, stores: [order.store]) }
+ let(:shirt) { create(:product, store: order.store) }
let!(:rule) { Promotion::Rules::ItemTotal.create(preferred_operator_min: 'gt', preferred_amount_min: 50, preferred_operator_max: 'lt', preferred_amount_max: 150, promotion: promotion) }
before do
@@ -70,7 +70,7 @@ module Spree
end
context 'promotion has item total rule' do
- let(:shirt) { create(:product, stores: [order.store]) }
+ let(:shirt) { create(:product, store: order.store) }
let!(:rule) { Promotion::Rules::ItemTotal.create(preferred_operator_min: 'gt', preferred_amount_min: 50, preferred_operator_max: 'lt', preferred_amount_max: 150, promotion: promotion) }
before do
diff --git a/spree/core/spec/models/spree/promotion_spec.rb b/spree/core/spec/models/spree/promotion_spec.rb
index 38666effa4..39fe4226ba 100644
--- a/spree/core/spec/models/spree/promotion_spec.rb
+++ b/spree/core/spec/models/spree/promotion_spec.rb
@@ -8,7 +8,7 @@ describe Spree::Promotion, type: :model do
let(:promotion) { create(:promotion, kind: :automatic) }
describe 'Validations' do
- let!(:valid_promotion) { build(:promotion, name: 'A promotion', stores: [store], kind: :automatic) }
+ let!(:valid_promotion) { build(:promotion, name: 'A promotion', kind: :automatic) }
it 'valid_promotion is valid' do
expect(valid_promotion).to be_valid
diff --git a/spree/core/spec/models/spree/stock_item_spec.rb b/spree/core/spec/models/spree/stock_item_spec.rb
index 22324c33c7..d4ad573081 100644
--- a/spree/core/spec/models/spree/stock_item_spec.rb
+++ b/spree/core/spec/models/spree/stock_item_spec.rb
@@ -480,9 +480,8 @@ describe Spree::StockItem, type: :model do
describe '.for_store' do
let(:store) { @default_store }
let(:other_store) { create(:store) }
- let(:product_in_store) { create(:product) }
- let(:product_in_other_store) { create(:product, channels: [other_store.default_channel]) }
- let(:product_in_both) { create(:product, channels: [store.default_channel, other_store.default_channel]) }
+ let(:product_in_store) { create(:product, store: store) }
+ let(:product_in_other_store) { create(:product, store: other_store) }
let!(:in_store_item) do
create(:stock_item, variant: product_in_store.master, stock_location: stock_location)
@@ -490,21 +489,14 @@ describe Spree::StockItem, type: :model do
let!(:other_store_item) do
create(:stock_item, variant: product_in_other_store.master, stock_location: stock_location)
end
- let!(:shared_item) do
- create(:stock_item, variant: product_in_both.master, stock_location: stock_location)
- end
- it 'returns stock items for variants of products assigned to the store' do
- expect(described_class.for_store(store)).to include(in_store_item, shared_item)
+ it 'returns stock items for variants of products owned by the store' do
+ expect(described_class.for_store(store)).to include(in_store_item)
end
- it 'excludes stock items for products not assigned to the store' do
+ it 'excludes stock items for products owned by another store' do
expect(described_class.for_store(store)).not_to include(other_store_item)
end
-
- it 'returns each row once even when the product belongs to multiple stores' do
- expect(described_class.for_store(store).where(id: shared_item.id).count).to eq(1)
- end
end
end
end
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index aa36eb0a7b..89ca13037e 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -11,8 +11,8 @@ describe Spree::Store, type: :model, without_global_store: true do
let(:other_store) { create(:store) }
describe '#products' do
- let!(:product) { create(:product, channels: [subject.default_channel]) }
- let!(:product_2) { create(:product, channels: [other_store.default_channel]) }
+ let!(:product) { create(:product, store: subject) }
+ let!(:product_2) { create(:product, store: other_store) }
it { expect(subject.products).to eq([product]) }
@@ -77,8 +77,8 @@ describe Spree::Store, type: :model, without_global_store: true do
end
describe '#inventory_units' do
- let(:product) { create(:product, channels: [subject.default_channel]) }
- let(:product_2) { create(:product, channels: [other_store.default_channel]) }
+ let(:product) { create(:product, store: subject) }
+ let(:product_2) { create(:product, store: other_store) }
let!(:inventory_unit) { create(:inventory_unit, variant: product.master, order: order) }
let!(:inventory_unit_2) { create(:inventory_unit, variant: product_2.master, order: order_2) }
diff --git a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb
index 33b0c07073..32e6e6d1c9 100644
--- a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb
@@ -8,6 +8,7 @@ RSpec.describe Spree::CSV::ProductVariantPresenter do
let(:taxons) { [] }
let(:metafields) { [] }
let(:presenter) { described_class.new(product, variant, 0, properties, taxons, store, metafields) }
+ let(:default_publication) { product.product_publications.find_by(channel: store.default_channel) }
let!(:variant_images) { create_list(:image, 3, viewable: variant) }
@@ -37,8 +38,10 @@ RSpec.describe Spree::CSV::ProductVariantPresenter do
expect(subject[19]).to eq 'in'
expect(subject[20]).to eq variant.weight
expect(subject[21]).to eq 'lb'
- expect(subject[22]).to eq variant.available_on&.strftime('%Y-%m-%d %H:%M:%S')
- expect(subject[23]).to eq variant.discontinue_on&.strftime('%Y-%m-%d %H:%M:%S')
+ expect(subject[22]).to eq default_publication.published_at&.strftime('%Y-%m-%d %H:%M:%S')
+ expect(subject[23]).to eq(
+ (variant.discontinue_on || default_publication.unpublished_at)&.strftime('%Y-%m-%d %H:%M:%S')
+ )
expect(subject[24]).to eq variant.track_inventory?
expect(subject[25]).to eq(variant.total_on_hand == BigDecimal::INFINITY ? '∞' : variant.total_on_hand)
expect(subject[26]).to eq variant.backorderable?
diff --git a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
index c095adab9e..a6ff9f10e4 100644
--- a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
+++ b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
@@ -45,7 +45,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
expect(product.name).to eq 'Denim Shirt'
expect(product.status).to eq 'draft'
expect(product.description).to eq row_data['description']
- expect(product.stores).to include(store)
+ expect(product.store).to eq(store)
expect(product.master).to eq variant
expect(variant.sku).to be_blank
expect(variant.price_in('USD').amount.to_f).to eq 62.99
@@ -814,7 +814,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
let!(:standard_category) { create(:shipping_category, name: 'Standard') }
let!(:digital_category) { create(:shipping_category, name: 'Digital') }
let!(:existing_product) do
- create(:product, slug: 'product-to-update', name: 'Product', stores: [store], shipping_category: standard_category)
+ create(:product, slug: 'product-to-update', name: 'Product', store: store, shipping_category: standard_category)
end
let(:row_data) do
diff --git a/spree/core/spec/services/spree/payments/handle_webhook_spec.rb b/spree/core/spec/services/spree/payments/handle_webhook_spec.rb
index 75121abf9a..5d8c72a451 100644
--- a/spree/core/spec/services/spree/payments/handle_webhook_spec.rb
+++ b/spree/core/spec/services/spree/payments/handle_webhook_spec.rb
@@ -49,7 +49,7 @@ RSpec.describe Spree::Payments::HandleWebhook do
end
context 'with :authorized action and a manual-capture payment method' do
- let(:payment_method) { create(:bogus_payment_method, stores: [store], auto_capture: false) }
+ let(:payment_method) { create(:bogus_payment_method, auto_capture: false) }
it 'creates a payment record in pending state' do
result = subject.call(payment_method: payment_method, action: :authorized, payment_session: payment_session)
diff --git a/spree/core/spec/services/spree/products/duplicator_spec.rb b/spree/core/spec/services/spree/products/duplicator_spec.rb
index fb3893bf68..c37cb4cc7d 100644
--- a/spree/core/spec/services/spree/products/duplicator_spec.rb
+++ b/spree/core/spec/services/spree/products/duplicator_spec.rb
@@ -103,10 +103,10 @@ RSpec.describe Spree::Products::Duplicator do
end
end
- describe 'stores' do
+ describe 'store' do
let!(:new_product) { duplicate.value }
- it { expect(new_product.stores).to eq [store] }
+ it { expect(new_product.store).to eq store }
end
context 'with variants' do
diff --git a/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb b/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb
index 6d1f5df7bc..6a0cfebe76 100644
--- a/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb
+++ b/spree/core/spec/services/spree/products/prepare_nested_attributes_spec.rb
@@ -6,8 +6,7 @@ RSpec.describe Spree::Products::PrepareNestedAttributes do
let(:ability) { Spree::Ability.new(nil) }
let(:store) { @default_store }
- let(:other_store) { create(:store) }
- let(:product) { create(:product, stores: [store, other_store]) }
+ let(:product) { create(:product, store: store) }
let(:params) { ActionController::Parameters.new(raw_params) }
let(:raw_params) { {} }
@@ -15,137 +14,29 @@ RSpec.describe Spree::Products::PrepareNestedAttributes do
ability.can :manage, :all
end
- describe 'taxon preservation across stores' do
- let(:store_taxonomy) { create(:taxonomy, store: store) }
- let(:other_store_taxonomy) { create(:taxonomy, store: other_store) }
- let(:store_taxon) { create(:taxon, taxonomy: store_taxonomy) }
- let(:other_store_taxon) { create(:taxon, taxonomy: other_store_taxonomy) }
-
- context 'when editing a product with taxons from multiple stores' do
- before do
- product.taxons << [store_taxon, other_store_taxon]
- end
-
- context 'when updating taxon_ids from current store' do
- let(:new_store_taxon) { create(:taxon, taxonomy: store_taxonomy) }
- let(:raw_params) do
- {
- name: 'Updated Product',
- taxon_ids: [new_store_taxon.id.to_s]
- }
- end
-
- it 'preserves taxons from other stores' do
- expect(prepared_params[:taxon_ids]).to include(other_store_taxon.id.to_s)
- end
-
- it 'includes the new taxon from current store' do
- expect(prepared_params[:taxon_ids]).to include(new_store_taxon.id.to_s)
- end
-
- it 'removes the old taxon from current store' do
- expect(prepared_params[:taxon_ids]).not_to include(store_taxon.id.to_s)
- end
-
- it 'returns unique taxon IDs' do
- expect(prepared_params[:taxon_ids].uniq).to eq(prepared_params[:taxon_ids])
- end
- end
-
- context 'when removing all taxons from current store' do
- let(:raw_params) do
- {
- name: 'Updated Product',
- taxon_ids: []
- }
- end
-
- it 'preserves taxons from other stores' do
- expect(prepared_params[:taxon_ids]).to include(other_store_taxon.id.to_s)
- end
-
- it 'does not include taxons from current store' do
- expect(prepared_params[:taxon_ids]).not_to include(store_taxon.id.to_s)
- end
- end
-
- context 'when taxon_ids param is not present' do
- let(:raw_params) do
- {
- name: 'Updated Product'
- }
- end
-
- it 'does not add taxon_ids key' do
- expect(prepared_params).not_to have_key(:taxon_ids)
- end
- end
- end
-
- context 'when creating a new product' do
- let(:product) { build(:product) }
- let(:raw_params) do
- {
- name: 'New Product',
- taxon_ids: [store_taxon.id.to_s]
- }
- end
-
- it 'does not merge taxons from other stores' do
- expect(prepared_params[:taxon_ids]).to eq([store_taxon.id.to_s])
- end
-
- it 'only includes submitted taxon IDs' do
- expect(prepared_params[:taxon_ids]).to contain_exactly(store_taxon.id.to_s)
- end
- end
-
- context 'when product has taxons from multiple other stores' do
- let(:third_store) { create(:store) }
- let(:third_store_taxonomy) { create(:taxonomy, store: third_store) }
- let(:third_store_taxon) { create(:taxon, taxonomy: third_store_taxonomy) }
-
- before do
- product.stores << third_store
- product.taxons << [store_taxon, other_store_taxon, third_store_taxon]
- end
-
- let(:new_store_taxon) { create(:taxon, taxonomy: store_taxonomy) }
- let(:raw_params) do
- {
- name: 'Updated Product',
- taxon_ids: [new_store_taxon.id.to_s]
- }
- end
-
- it 'preserves taxons from all other stores' do
- expect(prepared_params[:taxon_ids]).to include(other_store_taxon.id.to_s, third_store_taxon.id.to_s)
- end
-
- it 'includes the new taxon from current store' do
- expect(prepared_params[:taxon_ids]).to include(new_store_taxon.id.to_s)
- end
+ describe 'store_id handling' do
+ context 'on a new product with no store_id' do
+ let(:product) { build(:product, store: nil) }
+ let(:raw_params) { { name: 'Product' } }
- it 'has exactly 3 taxon IDs' do
- expect(prepared_params[:taxon_ids].size).to eq(3)
+ it 'defaults to the current store' do
+ expect(prepared_params[:store_id]).to eq(store.id)
end
end
- end
- describe 'store_ids handling' do
- context 'when store_ids is blank' do
+ context 'when product already has a store_id' do
let(:raw_params) { { name: 'Product' } }
- it 'adds current store to store_ids' do
- expect(prepared_params[:store_ids]).to eq([store.id])
+ it 'does not override the existing store_id' do
+ expect(prepared_params).not_to have_key(:store_id)
end
end
- context 'when store_ids is present' do
- let(:raw_params) { { name: 'Product', store_ids: [store.id, other_store.id] } }
+ context 'when store_id is submitted' do
+ let(:raw_params) { { name: 'Product', store_id: store.id } }
- it 'preserves submitted store_ids' do
- expect(prepared_params[:store_ids]).to eq([store.id, other_store.id])
+ it 'preserves the submitted store_id' do
+ expect(prepared_params[:store_id]).to eq(store.id)
end
end
end
diff --git a/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb b/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb
index 808eff5509..648ae4286e 100644
--- a/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb
+++ b/spree/core/spec/subscribers/spree/product_metrics_subscriber_spec.rb
@@ -46,8 +46,8 @@ RSpec.describe Spree::ProductMetricsSubscriber do
it 'enqueues jobs with correct arguments' do
subscriber.refresh_product_metrics(event)
- expect(Spree::Products::RefreshMetricsJob).to have_been_enqueued.with(product_1.id, store.id)
- expect(Spree::Products::RefreshMetricsJob).to have_been_enqueued.with(product_2.id, store.id)
+ expect(Spree::Products::RefreshMetricsJob).to have_been_enqueued.with(product_1.id)
+ expect(Spree::Products::RefreshMetricsJob).to have_been_enqueued.with(product_2.id)
end
context 'when order_id is missing' do
@@ -65,27 +65,6 @@ RSpec.describe Spree::ProductMetricsSubscriber do
end
end
- context 'when order has no store' do
- let(:order_without_store) do
- create(:completed_order_with_totals, store: store).tap do |o|
- o.update_column(:store_id, nil)
- end
- end
-
- let(:event) do
- Spree::Event.new(
- name: 'order.completed',
- payload: { 'id' => order_without_store.id }
- )
- end
-
- it 'does not enqueue any jobs' do
- expect {
- subscriber.refresh_product_metrics(event)
- }.not_to have_enqueued_job(Spree::Products::RefreshMetricsJob)
- end
- end
-
context 'when order does not exist' do
let(:event) do
Spree::Event.new(