Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added store argument to sample data loading (#14700)
Damian Legawiec66cba505cec4
diff --git a/spree/api/app/controllers/spree/api/v3/admin/setup_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/setup_controller.rbindex 0160dcd721..ddf0407e24 100644--- a/spree/api/app/controllers/spree/api/v3/admin/setup_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/setup_controller.rb@@ -65,7 +65,7 @@ module Spree# Outside the lock: the loader needs the admin committed, and it# runs for minutes, so it is queued rather than awaited.- Spree::SampleData::LoadJob.perform_later if sample_data_requested?+ Spree::SampleData::LoadJob.perform_later(store.id) if sample_data_requested?refresh_token = Spree::RefreshToken.create_for(user, audience: JWT_AUDIENCE_ADMIN, request_env: request_env_for_token)set_refresh_cookie(refresh_token)diff --git a/spree/api/spec/controllers/spree/api/v3/admin/setup_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/setup_controller_spec.rbindex 553ae65150..70c91ba141 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/setup_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/setup_controller_spec.rb@@ -144,9 +144,9 @@ RSpec.describe Spree::Api::V3::Admin::SetupController, type: :controller doexpect(store.default_currency).to eq('EUR')end- it 'queues the sample data load only when asked to' do+ it 'queues the sample data load into the adopted store only when asked to' doexpect { post :create, params: valid_params.merge(sample_data: true) }- .to have_enqueued_job(Spree::SampleData::LoadJob)+ .to have_enqueued_job(Spree::SampleData::LoadJob).with(@default_store.id)endit 'does not queue sample data by default' dodiff --git a/spree/core/app/jobs/spree/sample_data/load_job.rb b/spree/core/app/jobs/spree/sample_data/load_job.rbindex 0562060b7b..e2a75e7842 100644--- a/spree/core/app/jobs/spree/sample_data/load_job.rb+++ b/spree/core/app/jobs/spree/sample_data/load_job.rb@@ -5,8 +5,13 @@ module Spree# loader needs an admin to own its imports and downloads product images,# so it can neither run before setup nor inside the setup request.class LoadJob < Spree::BaseJob- def perform- Spree::SampleData::Loader.call+ # @param store_id [String, Integer, nil] the store to load into; the+ # default store when omitted+ def perform(store_id = nil)+ return Spree::SampleData::Loader.call if store_id.nil?++ store = Spree::Store.find_by(id: store_id)+ Spree::SampleData::Loader.call(store: store) if storeendendenddiff --git a/spree/core/app/models/concerns/spree/has_number.rb b/spree/core/app/models/concerns/spree/has_number.rbindex 6fa4d0018a..0be5aae86d 100644--- a/spree/core/app/models/concerns/spree/has_number.rb+++ b/spree/core/app/models/concerns/spree/has_number.rb@@ -99,9 +99,10 @@ module Spree# Advisory only — a concurrent writer can take the number between this# check and the insert, which is what the unique-index rescue below is- # for. Unscoped because the index is global.+ # for. Checked on the base class, unscoped, because the index is global —+ # it spans every STI subclass and soft-deleted row.def number_taken?(candidate)- self.class.unscoped.exists?(number: candidate)+ self.class.base_class.unscoped.exists?(number: candidate)end# Last line of defence. The pre-check and the uniqueness validation bothdiff --git a/spree/core/app/models/spree/number_generators/sequential.rb b/spree/core/app/models/spree/number_generators/sequential.rbindex 5b311156be..cf85b8d75f 100644--- a/spree/core/app/models/spree/number_generators/sequential.rb+++ b/spree/core/app/models/spree/number_generators/sequential.rb@@ -50,7 +50,7 @@ module Spreeenddef taken?(record, candidate)- record.class.unscoped.exists?(number: candidate)+ record.class.base_class.unscoped.exists?(number: candidate)enddef next_free_value(record, from)@@ -58,7 +58,7 @@ module Spreeloop docandidates = (value + 1..value + SCAN_BATCH_SIZE).index_by { |v| compose(record, v) }- taken = record.class.unscoped.where(number: candidates.keys).pluck(:number)+ taken = record.class.base_class.unscoped.where(number: candidates.keys).pluck(:number)free = (candidates.keys - taken).firstreturn candidates.fetch(free) if freediff --git a/spree/core/app/services/spree/imports/row_processors/product_translation.rb b/spree/core/app/services/spree/imports/row_processors/product_translation.rbindex 9361b9a29f..5337fdd1d2 100644--- a/spree/core/app/services/spree/imports/row_processors/product_translation.rb+++ b/spree/core/app/services/spree/imports/row_processors/product_translation.rb@@ -37,7 +37,7 @@ module Spreeprivatedef product_scope- Spree::Product.accessible_by(import.current_ability, :manage)+ store.products.accessible_by(import.current_ability, :manage)endendenddiff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rbindex f8c117d0b2..df5e08c085 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@@ -125,15 +125,17 @@ module Spree# Which products this import may resolve an existing row onto.#- # A seller's import reaches only that seller's own products. The- # ability cannot answer this: it grants capability, never tenancy —- # a seller holding `write_products` gets `can :manage, Spree::Product`,- # the whole class (see Spree::Ability). On the API that is safe because- # the controller scope-fetches through `current_seller`; a background- # row processor has no controller, so the narrowing has to happen here- # or a CSV naming another seller's slug would edit their product.+ # The import's own store's products, and for a seller's import only+ # that seller's. The ability cannot answer either: it grants+ # capability, never tenancy — a seller holding `write_products` gets+ # `can :manage, Spree::Product`, the whole class (see Spree::Ability),+ # and an admin of two stores reaches both. On the API that is safe because+ # the controller scope-fetches through `current_store` and+ # `current_seller`; a background row processor has no controller, so+ # the narrowing has to happen here or a CSV naming another store's or+ # seller's slug would edit their product.def product_scope- scope = Spree::Product.accessible_by(import.current_ability, :manage)+ scope = store.products.accessible_by(import.current_ability, :manage)seller.present? ? scope.where(seller_id: seller.id) : scopeend@@ -237,7 +239,7 @@ module Spreedef prepare_tax_categorytax_category_name = attributes['tax_category'].stripcached_lookup(:tax_category, tax_category_name) do- Spree::TaxCategory.find_by(name: tax_category_name)+ store.tax_categories.find_by(name: tax_category_name)endend@@ -302,15 +304,19 @@ module Spreedef find_or_create_option_type!(label)cached_lookup(:option_type, label) dobegin- Spree::OptionType.search_by_name(label).first || Spree::OptionType.create!(label: label)+ store_option_types.search_by_name(label).first || store_option_types.create!(label: label)rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid => eraise unless uniqueness_conflict?(e, :name)- Spree::OptionType.search_by_name(label).first!+ store_option_types.search_by_name(label).first!endendend+ def store_option_types+ Spree::OptionType.for_store(store)+ end+def find_or_create_option_value!(option_type, label)cached_lookup(:option_value, option_type.id, label) dobegindiff --git a/spree/core/app/services/spree/sample_data/import_builder.rb b/spree/core/app/services/spree/sample_data/import_builder.rbindex c8fc6fde23..e168037082 100644--- a/spree/core/app/services/spree/sample_data/import_builder.rb+++ b/spree/core/app/services/spree/sample_data/import_builder.rb@@ -7,7 +7,7 @@ module Spree# runs — a price-list import's `preferred_price_list_id`, say# @return [Spree::Import] persisted, unprocesseddef self.call(csv_path:, import_class:, store: nil, user: nil, inline: false, skip_events: false, attributes: {})- store ||= Spree::Store.default+ store ||= Spree::Current.store# An admin of the target store, not `admin_user_class.first` — in a# multi-store or multi-tenant app that global first can belong to a# different store entirely.diff --git a/spree/core/app/services/spree/sample_data/loader.rb b/spree/core/app/services/spree/sample_data/loader.rbindex b8014e0283..dfcfd43d2f 100644--- a/spree/core/app/services/spree/sample_data/loader.rb+++ b/spree/core/app/services/spree/sample_data/loader.rb@@ -4,65 +4,79 @@ module Spreeprepend Spree::ServiceModule::Baseinclude Spree::SampleData::Helper- def call+ # Loads the demo data into one store. The sample files and the imports+ # they run read `Spree::Current.store`, so it is set for the whole run+ # and restored afterwards.+ #+ # @param store [Spree::Store, nil] the store to load into; defaults to+ # the default store, resolved after the seeds so a bare install works+ # @return [Spree::ServiceModule::Result]+ def call(store: nil)Spree::Events.disable dowithout_geocoding doActiveRecord::Base.no_touching doputs 'Running seeds first...' unless seeds_loaded?ensure_seeds_loaded- puts 'Loading sample configuration data...'- load_configuration_data+ @store = store || Spree::Store.default+ Spree::Current.set(store: @store) { load_sample_data }+ end+ end+ end+ end- puts 'Loading sample channels...'- load_ruby_file('channels')+ private- puts 'Loading sample custom_field definitions...'- load_ruby_file('custom_field_definitions')+ attr_reader :store- puts 'Loading sample options...'- load_ruby_file('options')+ def load_sample_data+ puts 'Loading sample configuration data...'+ load_configuration_data- puts 'Loading sample product types...'- load_ruby_file('product_types')+ puts 'Loading sample channels...'+ load_ruby_file('channels')- puts 'Loading sample products...'- load_products+ puts 'Loading sample custom_field definitions...'+ load_ruby_file('custom_field_definitions')- puts 'Attaching the sample digital product file...'- load_ruby_file('digital_products')+ puts 'Loading sample options...'+ load_ruby_file('options')- puts 'Publishing sample products on the default channel...'- publish_sample_products(Spree::Store.default)+ puts 'Loading sample product types...'+ load_ruby_file('product_types')- puts 'Loading sample product translations...'- load_product_translations+ puts 'Loading sample products...'+ load_products- puts 'Linking product types to categories...'- load_ruby_file('product_type_categories')+ puts 'Attaching the sample digital product file...'+ load_ruby_file('digital_products')- puts 'Loading sample collections...'- load_ruby_file('collections')+ puts 'Publishing sample products on every channel...'+ publish_sample_products(store)- puts 'Loading sample customers...'- load_customers+ puts 'Loading sample product translations...'+ load_product_translations- puts 'Loading wholesale demo data...'- load_ruby_file('wholesale')+ puts 'Linking product types to categories...'+ load_ruby_file('product_type_categories')- puts 'Loading sample orders...'- load_ruby_file('orders')+ puts 'Loading sample collections...'+ load_ruby_file('collections')- puts 'Loading sample posts...'- load_ruby_file('posts')+ puts 'Loading sample customers...'+ load_customers- puts 'Sample data loaded successfully!'- end- end- end- end+ puts 'Loading wholesale demo data...'+ load_ruby_file('wholesale')- private+ puts 'Loading sample orders...'+ load_ruby_file('orders')++ puts 'Loading sample posts...'+ load_ruby_file('posts')++ puts 'Sample data loaded successfully!'+ enddef load_configuration_dataload_ruby_file('fulfillment')@@ -72,19 +86,19 @@ module Spreedef load_productscsv_path = sample_data_path.join('products.csv')- Spree::SampleData::ImportRunner.call(csv_path: csv_path, import_class: Spree::Imports::Products, inline: true)+ Spree::SampleData::ImportRunner.call(csv_path: csv_path, import_class: Spree::Imports::Products, store: store, inline: true)enddef load_product_translationscsv_path = sample_data_path.join('product_translations.csv')return unless csv_path.exist?- Spree::SampleData::ImportRunner.call(csv_path: csv_path, import_class: Spree::Imports::ProductTranslations, inline: true)+ Spree::SampleData::ImportRunner.call(csv_path: csv_path, import_class: Spree::Imports::ProductTranslations, store: store, inline: true)enddef load_customerscsv_path = sample_data_path.join('customers.csv')- Spree::SampleData::ImportRunner.call(csv_path: csv_path, import_class: Spree::Imports::Customers, inline: true)+ Spree::SampleData::ImportRunner.call(csv_path: csv_path, import_class: Spree::Imports::Customers, store: store, inline: true)endendenddiff --git a/spree/core/db/sample_data/channels.rb b/spree/core/db/sample_data/channels.rbindex 026d46c242..ba0631f376 100644--- a/spree/core/db/sample_data/channels.rb+++ b/spree/core/db/sample_data/channels.rb@@ -1,7 +1,7 @@# 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 = Spree::Current.storestore.channels.find_or_create_by!(code: 'pos') do |channel|channel.name = 'Point of Sale'diff --git a/spree/core/db/sample_data/collections.rb b/spree/core/db/sample_data/collections.rbindex 81bf660e58..6d39ff6343 100644--- a/spree/core/db/sample_data/collections.rb+++ b/spree/core/db/sample_data/collections.rb@@ -1,7 +1,7 @@# Three collections that between them exercise both membership models: two# rule-based (they regenerate themselves) and one hand-curated with a dynamic# sort. Runs after the product import so there is a catalog to draw from.-store = Spree::Store.default+store = Spree::Current.store# Each automatic collection is defined by the single rule that materializes it.automatic_collections = [diff --git a/spree/core/db/sample_data/custom_field_definitions.rb b/spree/core/db/sample_data/custom_field_definitions.rbindex ecb23ef090..4e9672c2f9 100644--- a/spree/core/db/sample_data/custom_field_definitions.rb+++ b/spree/core/db/sample_data/custom_field_definitions.rb@@ -1,4 +1,4 @@-store = Spree::Store.default+store = Spree::Current.store%w[warranty capacity voltage wattage runtime room_coverage noise_level connectivity].each do |key|store.custom_field_definitions.find_or_create_by!(diff --git a/spree/core/db/sample_data/digital_products.rb b/spree/core/db/sample_data/digital_products.rbindex 2e67b426c2..5f8e2f148d 100644--- a/spree/core/db/sample_data/digital_products.rb+++ b/spree/core/db/sample_data/digital_products.rb@@ -3,7 +3,7 @@# type stamps it at creation. The one thing a CSV row cannot carry is the file# buyers download, so that is all this step does: attach a PDF to the imported# product's default variant.-store = Spree::Store.default+store = Spree::Current.storeproduct = Spree::Product.find_by(store: store, slug: 'the-spree-commerce-handbook')diff --git a/spree/core/db/sample_data/fulfillment.rb b/spree/core/db/sample_data/fulfillment.rbindex b67e5a1395..99145c006a 100644--- a/spree/core/db/sample_data/fulfillment.rb+++ b/spree/core/db/sample_data/fulfillment.rb@@ -2,7 +2,7 @@# Shopify-style delivery methods on the Domestic and International zones.# The free international method showcases delivery-method rules — free# above a spend threshold, hidden below it.-store = Spree::Store.default+store = Spree::Current.store# The zones are created from the store's country at first-run setup, so an# install that has not been set up yet has none. Provision them here fromdiff --git a/spree/core/db/sample_data/options.rb b/spree/core/db/sample_data/options.rbindex 9af1de49e1..2b346c51f4 100644--- a/spree/core/db/sample_data/options.rb+++ b/spree/core/db/sample_data/options.rb@@ -1,4 +1,6 @@-color = Spree::OptionType.find_or_initialize_by(name: 'color')+store = Spree::Current.store++color = Spree::OptionType.for_store(store).find_or_initialize_by(name: 'color')color.label = 'Color'color.kind = 'color_swatch'color.save!@@ -15,7 +17,7 @@ color.save!# sells only new goods should not find this on a fresh install. A marketplace# that wants its sellers to describe condition the same way loads it, or# creates its own.-condition = Spree::OptionType.find_or_initialize_by(name: 'condition')+condition = Spree::OptionType.for_store(store).find_or_initialize_by(name: 'condition')condition.label = 'Condition'condition.kind = 'buttons'condition.filterable = truediff --git a/spree/core/db/sample_data/orders.rb b/spree/core/db/sample_data/orders.rbindex f5aa5d0153..91ce0e02e2 100644--- a/spree/core/db/sample_data/orders.rb+++ b/spree/core/db/sample_data/orders.rb@@ -1,8 +1,8 @@-store = Spree::Store.default+store = Spree::Current.store# Find products created by the product import-product_1 = Spree::Product.find_by(name: 'Automatic Espresso Machine')-product_2 = Spree::Product.find_by(name: 'Drip Coffee Maker 1.5L')+product_1 = store.products.find_by(name: 'Automatic Espresso Machine')+product_2 = store.products.find_by(name: 'Drip Coffee Maker 1.5L')unless product_1 && product_2puts ' Skipping orders: required products not found'@@ -84,7 +84,7 @@ orders.each(&:rebuild_fulfillments!)Spree::Order.where(id: orders.map(&:id)).update_all(status: 'placed', completed_at: Time.current - 1.day)# Tax lines (zero-amount sample rows against the California rate)-tax_rate = Spree::TaxRate.find_by(name: 'California')+tax_rate = store.tax_rates.find_by(name: 'California')if tax_rateorders.each do |order|@@ -105,7 +105,7 @@ if tax_rateend# Payments-method = Spree::PaymentMethod.where(name: 'Credit Card', active: true).first+method = store.payment_methods.where(name: 'Credit Card', active: true).firstif methodSpree::Gateway.class_eval do@@ -114,8 +114,7 @@ if methodendend- credit_card = Spree::CreditCard.find_or_initialize_by(gateway_customer_profile_id: 'BGS-1234')- credit_card.payment_method = method+ credit_card = Spree::CreditCard.find_or_initialize_by(gateway_customer_profile_id: 'BGS-1234', payment_method: method)credit_card.cc_type = 'visa'credit_card.month = 12credit_card.year = 2.years.from_now.year@@ -140,15 +139,15 @@ orders.each { |order| order.reload.update_statuses! }# A return in progress, so the admin has something to look at. Built through# the workflows rather than by direct writes — they own every transition.-first_complete_order = Spree::Order.complete.first+first_complete_order = store.orders.complete.firstif first_complete_order && first_complete_order.fulfillment_items.any?fulfillment_item = first_complete_order.fulfillment_items.firstSpree::Returns::Create.call(order: first_complete_order,items: [{ fulfillment_item: fulfillment_item, quantity: 1 }],- stock_location: fulfillment_item.fulfillment&.stock_location || Spree::StockLocation.first,- reason: Spree::ReturnReason.first,+ stock_location: fulfillment_item.fulfillment&.stock_location || store.stock_locations.first,+ reason: store.return_reasons.first,memo: 'Sample return')enddiff --git a/spree/core/db/sample_data/payment_methods.rb b/spree/core/db/sample_data/payment_methods.rbindex 3f6b997ded..82e33e50ce 100644--- a/spree/core/db/sample_data/payment_methods.rb+++ b/spree/core/db/sample_data/payment_methods.rb@@ -1,19 +1,19 @@-Spree::Store.all.find_each do |store|- cc_payment_method = store.payment_methods.find_or_initialize_by(- type: 'Spree::Gateway::Bogus',- name: 'Credit Card',- description: 'Bogus payment gateway.',- active: true- )- cc_payment_method.storefront_visible = false- cc_payment_method.save!+store = Spree::Current.store- check_payment_method = store.payment_methods.find_or_initialize_by(- type: 'Spree::PaymentMethod::Check',- name: 'Check',- description: 'Pay by check.',- active: true- )- check_payment_method.storefront_visible = false- check_payment_method.save!-end+cc_payment_method = store.payment_methods.find_or_initialize_by(+ type: 'Spree::Gateway::Bogus',+ name: 'Credit Card',+ description: 'Bogus payment gateway.',+ active: true+)+cc_payment_method.storefront_visible = false+cc_payment_method.save!++check_payment_method = store.payment_methods.find_or_initialize_by(+ type: 'Spree::PaymentMethod::Check',+ name: 'Check',+ description: 'Pay by check.',+ active: true+)+check_payment_method.storefront_visible = false+check_payment_method.save!diff --git a/spree/core/db/sample_data/product_type_categories.rb b/spree/core/db/sample_data/product_type_categories.rbindex 9aec52f9fd..dc06b0dcbe 100644--- a/spree/core/db/sample_data/product_type_categories.rb+++ b/spree/core/db/sample_data/product_type_categories.rb@@ -5,7 +5,7 @@# categories — before it there is nothing to link to. Seeding is additive and# only applies to products created from here on, so linking after the fact# changes nothing about the imported catalog.-store = Spree::Store.default+store = Spree::Current.storecategories_by_type = {'Kitchen Appliance' => 'Kitchen',diff --git a/spree/core/db/sample_data/product_types.rb b/spree/core/db/sample_data/product_types.rbindex 9d10ef9998..f820d9a478 100644--- a/spree/core/db/sample_data/product_types.rb+++ b/spree/core/db/sample_data/product_types.rb@@ -10,9 +10,9 @@## Categories are attached afterwards by product_type_categories.rb — the import# is what creates them, so there is nothing to link to at this point.-store = Spree::Store.default+store = Spree::Current.store-color_option_type = Spree::OptionType.find_by(name: 'color')+color_option_type = Spree::OptionType.for_store(store).find_by(name: 'color')definitions = store.custom_field_definitions.where(namespace: 'custom',diff --git a/spree/core/db/sample_data/promotions.rb b/spree/core/db/sample_data/promotions.rbindex 92699bb3f0..f5101c2305 100644--- a/spree/core/db/sample_data/promotions.rb+++ b/spree/core/db/sample_data/promotions.rb@@ -1,8 +1,6 @@-promotion = Spree::Promotion.where(+promotion = Spree::Current.store.promotions.where(name: 'Free Shipping',code: 'FREESHIP'-).first_or_create! do |promo|- promo.store = Spree::Store.default-end+).first_or_create!Spree::Promotion::Actions::FreeShipping.where(promotion: promotion).first_or_create!diff --git a/spree/core/db/sample_data/wholesale.rb b/spree/core/db/sample_data/wholesale.rbindex 3a1177e8c1..909322adf0 100644--- a/spree/core/db/sample_data/wholesale.rb+++ b/spree/core/db/sample_data/wholesale.rb@@ -2,7 +2,7 @@# Spree::Seeds::Channels: an approved demo buyer and a customer-group price# list, so a fresh install can walk the whole B2B portal story — sign in as# the buyer, see wholesale prices, check out on the wholesale channel.-store = Spree::Store.default+store = Spree::Current.storewholesale_group = store.customer_groups.find_or_create_by!(name: Spree::Seeds::CustomerGroups::WHOLESALE_NAME)diff --git a/spree/core/lib/tasks/sample_data.rake b/spree/core/lib/tasks/sample_data.rakeindex 542519eeb5..af13f8a159 100644--- a/spree/core/lib/tasks/sample_data.rake+++ b/spree/core/lib/tasks/sample_data.rake@@ -1,7 +1,13 @@namespace :spree do- desc 'Loads sample data (products, customers, orders, configuration)'+ desc 'Loads sample data (products, customers, orders, configuration). Set STORE_ID (prefixed or numeric) or STORE_CODE to target a store other than the default one'task load_sample_data: :environment do- Spree::SampleData::Loader.call+ store = if ENV['STORE_ID'].present?+ Spree::Store.find_by_param!(ENV['STORE_ID'])+ elsif ENV['STORE_CODE'].present?+ Spree::Store.find_by!(code: ENV['STORE_CODE'])+ end++ Spree::SampleData::Loader.call(store: store)endenddiff --git a/spree/core/spec/jobs/spree/sample_data/load_job_spec.rb b/spree/core/spec/jobs/spree/sample_data/load_job_spec.rbindex 321e9677d9..94b1ba8006 100644--- a/spree/core/spec/jobs/spree/sample_data/load_job_spec.rb+++ b/spree/core/spec/jobs/spree/sample_data/load_job_spec.rb@@ -1,11 +1,25 @@require 'spec_helper'RSpec.describe Spree::SampleData::LoadJob, type: :job do- it 'runs the sample data loader' do- loader = class_double(Spree::SampleData::Loader, call: nil).as_stubbed_const+ let!(:loader) { class_double(Spree::SampleData::Loader, call: nil).as_stubbed_const }+ it 'loads into the default store when no store is given' dodescribed_class.perform_now- expect(loader).to have_received(:call)+ expect(loader).to have_received(:call).with(no_args)+ end++ it 'loads into the given store' do+ store = create(:store)++ described_class.perform_now(store.id)++ expect(loader).to have_received(:call).with(store: store)+ end++ it 'skips a store that no longer exists' do+ described_class.perform_now(0)++ expect(loader).not_to have_received(:call)endenddiff --git a/spree/core/spec/models/spree/concerns/has_number_spec.rb b/spree/core/spec/models/spree/concerns/has_number_spec.rbindex 428a4641c7..f9371dc5fd 100644--- a/spree/core/spec/models/spree/concerns/has_number_spec.rb+++ b/spree/core/spec/models/spree/concerns/has_number_spec.rb@@ -51,6 +51,14 @@ RSpec.describe Spree::HasNumber doexpect(create(:order).number).to eq('R-FREE-1')end+ # The unique index spans the whole table, so another store's record of a+ # sibling STI type holds the number just the same.+ it 'skips a number another store holds under a sibling subclass' do+ taken = create(:customer_import, store: create(:store)).number++ expect(create(:product_import, store: create(:store)).number).not_to eq(taken)+ end+it 'gives up rather than looping forever' dotaken = create(:order).numbergenerator = instance_double(Spree::NumberGenerators::Sequential)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.rbindex fe26bd30b1..14c07e88b2 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@@ -239,6 +239,17 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendend+ # Slugs are unique across the installation, so the row cannot claim it —+ # but it must never resolve onto the other store's product either.+ context "when another store's product has that slug" do+ let!(:foreign_product) { create(:product, slug: 'denim-shirt', name: 'Old Name', store: create(:store)) }++ it "refuses the row rather than editing the other store's product" do+ expect { subject }.to raise_error(ActiveRecord::RecordInvalid, /Slug/)+ expect(foreign_product.reload.name).to eq('Old Name')+ end+ end+context 'when tags are not present' doit 'does not enqueue AssignTagsJob' dorow_data['tags'] = nil@@ -292,6 +303,18 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doexpect(size_option_type.option_values.find_by(label: 'XS')).to be_presentend+ context 'when another store has an option type with the same name' do+ let!(:foreign_fabric) { create(:option_type, name: 'fabric', label: 'Fabric', store: create(:store)) }+ let(:row_data) { super().merge('option3_name' => 'Fabric', 'option3_value' => 'Cotton') }++ it "creates the option type in the import's store" do+ fabric = variant.option_values.find_by(label: 'Cotton').option_type++ expect(fabric).not_to eq(foreign_fabric)+ expect(fabric.store).to eq(store)+ end+ end+context 'when a concurrent worker has already created the option type/value' do# Simulates two Sidekiq workers racing on the same option name during a CSV import.# Force search_by_name to miss on the initial lookup so create! runs, then return@@ -1052,6 +1075,25 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendend+ context 'when the named tax category belongs to another store' do+ let!(:foreign_tax) { create(:tax_category, name: 'Clothing', store: create(:store)) }++ let(:row_data) do+ csv_row_hash(+ 'slug' => 'test-product',+ 'name' => 'Test Product',+ 'status' => 'active',+ 'price' => '29.99',+ 'currency' => 'USD',+ 'tax_category' => 'Clothing'+ )+ end++ it 'does not reach across stores' do+ expect(product.default_variant.tax_category).to be_nil+ end+ end+context 'when updating variant with different tax_category' dolet!(:standard_tax) { create(:tax_category, name: 'Standard') }let!(:clothing_tax) { create(:tax_category, name: 'Clothing') }diff --git a/spree/core/spec/services/spree/sample_data/loader_spec.rb b/spree/core/spec/services/spree/sample_data/loader_spec.rbindex a7184ca9ac..1fd231e448 100644--- a/spree/core/spec/services/spree/sample_data/loader_spec.rb+++ b/spree/core/spec/services/spree/sample_data/loader_spec.rb@@ -11,7 +11,15 @@ RSpec.describe Spree::SampleData::Loader, type: :service, without_global_store:original_password = ENV['ADMIN_PASSWORD']ENV['ADMIN_EMAIL'] = '[email protected]'ENV['ADMIN_PASSWORD'] = 'Secret123!'- described_class.call++ # Loaded into a store that is not the default one, so the default store+ # has to stay empty. It exists before the seeds so they provision it too.+ Spree::Seeds::Stores.call+ @store = create(:store, default: false)+ Spree::Seeds::All.call+ @store.add_user(Spree.admin_user_class.first)++ described_class.call(store: @store)ensureoriginal_email.nil? ? ENV.delete('ADMIN_EMAIL') : ENV['ADMIN_EMAIL'] = original_emailoriginal_password.nil? ? ENV.delete('ADMIN_PASSWORD') : ENV['ADMIN_PASSWORD'] = original_password@@ -25,6 +33,30 @@ RSpec.describe Spree::SampleData::Loader, type: :service, without_global_store:expect(Spree::Product.count).to be > 30end+ it 'loads everything into the given store and leaves the default store empty' do+ default_store = Spree::Store.default++ aggregate_failures do+ expect(default_store).not_to eq(@store)+ expect(Spree::Product.where.not(store: @store)).to be_empty+ expect(Spree::Order.where.not(store: @store)).to be_empty+ expect(Spree::OptionType.where.not(store: @store)).to be_empty+ expect(Spree::Promotion.where.not(store: @store)).to be_empty+ expect(Spree::Import.where.not(store: @store)).to be_empty++ expect(default_store.collections).to be_empty+ expect(default_store.price_lists).to be_empty+ expect(default_store.companies).to be_empty+ expect(default_store.catalogs).to be_empty+ expect(default_store.payment_methods.where(name: 'Credit Card')).to be_empty+ expect(default_store.channels.where(code: 'pos')).to be_empty++ expect(@store.collections).to be_present+ expect(@store.payment_methods.where(name: 'Credit Card')).to exist+ expect(@store.orders.complete.count).to be >= 2+ end+ end+it 'assigns imported products a product type' doexpect(Spree::Product.where(product_type_id: nil)).to be_emptyend@@ -116,7 +148,7 @@ RSpec.describe Spree::SampleData::Loader, type: :service, without_global_store:enddescribe 'wholesale demo data' do- let(:store) { Spree::Store.default }+ let(:store) { @store }let(:wholesale) { store.channels.find_by(code: 'wholesale') }it 'gates the wholesale channel' do