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.

Migrate Payment Method and Promotion from legacy multi-store to standard store resource (#14232)

Damian Legawiec867c6d63ac87
diff --git a/CLAUDE.md b/CLAUDE.md
index ae1af832e8..08df2da605 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -38,6 +38,7 @@ Multi-version plans (some phases shipped, some pending):
- `5.5-6.0-display-on-to-boolean.md` — Collapse `display_on` tri-state to a single `storefront_visible` boolean. 5.5 bridge (`storefront_visible` accessor + Ransacker on `Spree::DisplayOn`) shipped; 6.0 schema rename pending.
- `6.0-order-routing.md` — Two-tier extension: pluggable `Spree::OrderRouting::Strategy::Base` + STI subclasses of `Spree::OrderRoutingRule`. Phase 1 (5.5) shipped: `Channel`, `OrderRoutingRule`, strategy base + Rules + Reducer + Legacy, `preferred_stock_location_id` + `channel_id` on Order. Phase 2+ (6.0) layers Catalog/Company on top via `6.0-channels-catalogs-b2b.md`.
- `6.0-channels-catalogs-b2b.md` — Channel + ProductPublication (replaces StoreProduct) + single-owner Product (`belongs_to :store`) + Publishing card (legacy admin + SPA) + `Channel#default` boolean shipped in 5.5. Catalog, Company/CompanyLocation/CompanyContact for B2B pending in 6.0. Multi-store catalogs (historic `Product has_many :stores`) move to the `spree_multi_store` extension.
+- `5.6-6.0-single-store-promotions-payment-methods.md` — Migrate `Spree::Promotion` + `Spree::PaymentMethod` from multi-store (`has_many :stores` via `spree_promotions_stores` / `spree_payment_methods_stores` join tables) to single-owner `belongs_to :store`, mirroring the 5.5 single-owner Product migration. 5.6 (implemented): `store_id` FK + required-store presence via `Spree::SingleStoreResource`, backfill rake task (loud per-record deprecation on shared records), shared `LegacyMultiStoreSupport` deprecation bridge, deletes the `ResourceController` `store_ids=` seam, deprecates `StoreScopedResource`; multi-store sharing moves to the `spree_multi_store` extension (join tables left intact). 6.0 cleanup: enforce `null: false`, drop join tables + bridges. Paired with `6.0-channels-catalogs-b2b.md`.
Pending design work (drafts, no implementation yet):
- `5.5-6.0-resource-translations-api.md` — Admin API v3 translation management + React dashboard for all `Spree.translatable_resources`. Hybrid: embedded `translations` object on resource update + generic dedicated `…/:id/translations` endpoint (one registry-driven controller), self-describing field discovery, advisory server-side staleness. Canonical `{ locale → { field → value } }` shape (consistent with metafield-translations). Cross-record bulk = CSV import/export generalized across the registry (NOT a JSON bulk endpoint — no competitor ships one). Phase 1 (5.5) API; Phase 2 (6.0) coverage read + CSV generalization + staleness + centralized SPA page; Phase 3 folds in metafields.
diff --git a/docs/plans/5.6-6.0-single-store-promotions-payment-methods.md b/docs/plans/5.6-6.0-single-store-promotions-payment-methods.md
new file mode 100644
index 0000000000..9f1e7f6c12
--- /dev/null
+++ b/docs/plans/5.6-6.0-single-store-promotions-payment-methods.md
@@ -0,0 +1,289 @@
+# Single-Store Promotions & Payment Methods
+
+**Status:** In Progress — 5.6 phase implemented (models, migrations, bridges, backfill, controllers); 6.0 cleanup pending
+**Target:** Spree 5.6 (single-store migration: FK + bridges + backfill), 6.0 (cleanup: enforce `null: false`, drop join tables)
+**Depends on:** `6.0-channels-catalogs-b2b.md` (single-owner Product is the reference pattern), `5.4-6.0-custom-fields-rename.md` (unrelated, but touches the same serializers)
+**Author:** Damian (getvendo)
+**Last updated:** 2026-06-28
+
+## Summary
+
+`Spree::Promotion` and `Spree::PaymentMethod` are the last two core resources still modelled as **multi-store** via `has_many :through` join tables (`spree_promotions_stores`, `spree_payment_methods_stores`). Every other store-scoped resource — including `Spree::Product` as of 5.5 — now uses a direct `belongs_to :store` foreign key. This plan migrates Promotions and Payment Methods to single-store ownership, mirroring the Product migration shipped in 5.5 (`6.0-channels-catalogs-b2b.md`), and pushes the historic "shared across stores" behaviour into the `spree_multi_store` extension.
+
+The intent is already flagged in the codebase. `Spree::Api::V3::ResourceController` carries this bridge:
+
+```ruby
+# 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)
+```
+
+This plan removes the need for that branch.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Single owner via FK.** Both models gain a `store_id` column and `belongs_to :store`. No new join model is introduced (unlike Product, which needed `ProductPublication` for channel distribution — promotions and payment methods have no equivalent distribution concept, so the FK is the whole story).
+- **No `Channel`/`Publication` layer.** Products needed publications because a catalog item is *distributed* to multiple channels. A promotion or payment method belongs to exactly one store; there is nothing to publish. Keep it simple — just the FK.
+- **Multi-store behaviour moves to `spree_multi_store`.** The `has_many :stores` / `store_ids` accessors are preserved as **deprecation bridges** in core (returning `Array(store)`), and the real multi-store association is restored by the `spree_multi_store` extension on top of the untouched join tables. Same split as Product.
+- **Join tables survive 5.6, drop in 6.0.** `spree_promotions_stores` and `spree_payment_methods_stores` are left intact in the 5.6 migration so the extension can overlay the old relationship and so the backfill is re-runnable. The 6.0 cleanup migration drops them.
+- **`store_id` stays nullable in 5.6, `null: false` in 6.0.** Matching the Product migration (which left `store_id` nullable in 5.5), the 5.6 columns are nullable so installs that haven't run the backfill don't fail validations. The 6.0 cleanup migration enforces `null: false` once the data is known-clean.
+- **Swap `StoreScopedResource` for the existing `SingleStoreResource` concern.** The old `StoreScopedResource` (many-to-many `for_store` via `joins(:stores)`) is deprecated and its `include` removed from both models. In its place they include `Spree::SingleStoreResource` — the concern already used by `Order`, `GiftCard`, `Channel`, etc. — which provides the FK-based `for_store` scope, a `store can't be changed once set` validation, and (since #14231) a global `before_validation :ensure_store` that assigns `Spree::Current.store` when `store_id` is blank. No bespoke per-model `for_store`. `StoreScopedResource` stays in the tree for one deprecation cycle for external code still including it.
+- **Store is required — no nil store, no per-model auto-assignment.** The concern's `ensure_store` fills the store from `Spree::Current.store`; each model then declares `validates :store, presence: true` (honoring the documented `disable_store_presence_validation` escape hatch) — the same per-model presence pattern every other single-store resource uses. Together: the current store is auto-assigned, and a record with no resolvable store fails validation rather than persisting nil. Every entry point also sets the store explicitly: the API `ResourceController#build_resource`, the legacy admin `ResourceController#ensure_current_store`, the factories, seeds, and sample data.
+- **Read/write field symmetry preserved.** Serializers and controllers continue to expose/accept the same fields; the only change is that `store_ids` (plural, array) is deprecated in favour of `store_id` (singular). The API v3 controller branch above is deleted.
+- **Loud multi-store data-loss signalling.** The backfill warns per-record at runtime (`Spree::Deprecation`) whenever a record has more than one store attachment, in addition to an aggregate count in the rake task summary, so merchants who relied on sharing know to install `spree_multi_store`.
+
+## Design Details
+
+### Current state
+
+Both models include `Spree::StoreScopedResource` and declare:
+
+```ruby
+# Spree::Promotion
+has_many :store_promotions, class_name: 'Spree::StorePromotion'
+has_many :stores, class_name: 'Spree::Store', through: :store_promotions
+
+# Spree::PaymentMethod
+has_many :store_payment_methods, class_name: 'Spree::StorePaymentMethod', inverse_of: :payment_method
+has_many :stores, class_name: 'Spree::Store', through: :store_payment_methods
+```
+
+Join models / tables:
+
+| Model | Table | Columns | Unique index |
+|---|---|---|---|
+| `Spree::StorePromotion` | `spree_promotions_stores` | `promotion_id`, `store_id`, timestamps | `(promotion_id, store_id)` |
+| `Spree::StorePaymentMethod` | `spree_payment_methods_stores` | `payment_method_id`, `store_id` | `(payment_method_id, store_id)` |
+
+`Spree::StoreScopedResource` provides:
+
+```ruby
+scope :for_store, ->(store) { joins(:stores).where(Store.table_name => { id: store.id }) }
+before_validation :set_default_store, if: :new_record?
+# set_default_store pushes Spree::Store.default into the through-association when empty
+```
+
+`Spree::Store` declares the inverse: `has_many :promotions, through: :store_promotions` and `has_many :payment_methods, through: :store_payment_methods`.
+
+`PaymentMethod` is STI (`Spree::Gateway`, `Spree::PaymentMethod::Check`, `Spree::PaymentMethod::StoreCredit`, external gateway gems). The `store_id` FK lives on the base `spree_payment_methods` table and is inherited by all subclasses — no STI complications.
+
+### Target state
+
+#### Models
+
+Both models adopt the existing `Spree::SingleStoreResource` concern (already used by `Order`, `GiftCard`, `Channel`, `Wishlist`, etc.), which provides the `for_store` scope, the global `ensure_store` assignment, and a `store can't be changed once set` validation. Each model declares its own `belongs_to :store` plus a per-model store-presence validation:
+
+```ruby
+# Spree::Promotion / Spree::PaymentMethod
+include Spree::SingleStoreResource # for_store + ensure_store + immutability
+
+belongs_to :store, class_name: 'Spree::Store'
+validates :store, presence: true, unless: -> { Spree::Config[:disable_store_presence_validation] }
+
+include Spree::LegacyMultiStoreSupport unless defined?(SpreeMultiStore)
+```
+
+```ruby
+# Spree::SingleStoreResource (in core, shared)
+before_validation :ensure_store, unless: :store_id? # self.store ||= Spree::Current.store
+validate :ensure_store_association_is_not_changed # store_id frozen once persisted
+scope :for_store, ->(store) { where(store_id: store.id) }
+```
+
+`Spree.base_class.belongs_to_required_by_default` is `false`, so `belongs_to :store` does not validate presence on its own — the per-model `validates :store, presence: true` does (matching every other single-store resource, which each declare their own). `ensure_store` auto-assigns the current store; the presence validation then rejects any record left with no resolvable store. The `disable_store_presence_validation` preference is the documented escape hatch for data imports and the backfill window (existing rows are NULL until the rake task runs).
+
+#### Legacy multi-store bridges
+
+Mirror `Spree::Product::LegacyMultiStoreSupport` exactly — deprecation warnings + `Array(store)` semantics, auto-included unless the `spree_multi_store` extension defines `SpreeMultiStore`:
+
+```ruby
+module Spree::Promotion::LegacyMultiStoreSupport
+ included do
+ def stores
+ Spree::Deprecation.warn(
+ 'Spree::Promotion#stores is deprecated. Use Spree::Promotion#store instead. ' \
+ 'Install spree_multi_store to keep multi-store promotions.'
+ )
+ store ? [store] : []
+ end
+
+ def store_ids
+ Spree::Deprecation.warn('...')
+ store_id ? [store_id] : []
+ end
+
+ def stores=(values)
+ Spree::Deprecation.warn('...')
+ self.store = Array(values).compact.first
+ end
+
+ def store_ids=(ids)
+ Spree::Deprecation.warn('...')
+ self.store_id = Array(ids).compact_blank.first
+ end
+ end
+end
+```
+
+Identical concern for `Spree::PaymentMethod::LegacyMultiStoreSupport`. These bridges are what let the API controller's `store_ids=` branch keep working during deprecation — though we delete that branch and rely on `store_id` directly (see below).
+
+#### `Spree::Store` associations
+
+Replace the through-associations:
+
+```ruby
+# before
+has_many :store_promotions, class_name: 'Spree::StorePromotion'
+has_many :promotions, through: :store_promotions, class_name: 'Spree::Promotion'
+has_many :store_payment_methods, class_name: 'Spree::StorePaymentMethod'
+has_many :payment_methods, through: :store_payment_methods, class_name: 'Spree::PaymentMethod'
+
+# after
+has_many :promotions, class_name: 'Spree::Promotion', dependent: :nullify
+has_many :payment_methods, class_name: 'Spree::PaymentMethod', dependent: :nullify
+```
+
+`dependent: :nullify` (not `:destroy`) matches the existing `Store has_many :products` association and is required for correctness: with a direct `has_many`, clearing the collection (`store.promotions = []`, used in the test-support teardown) applies the `dependent` strategy to the removed records. `:destroy` would cascade into `Promotion`'s `before_destroy :not_used?` guard and raise on any used promotion; `:nullify` just clears the FK, which is the intended "detach, don't delete business records" behaviour.
+
+`store.promotions` / `store.payment_methods` keep working unchanged for all callers — `Order#payment_methods`, the promotion handlers (`Coupon`, `Cart`, `FreeShipping`, `Page`), and the admin/API controllers all read through these and need no changes.
+
+#### Controllers & serializers
+
+- **`Spree::Api::V3::ResourceController`**: delete the `resource.store_ids = [current_store.id]` bridge. The base `build_resource` already assigns `resource.store = current_store` when `store_id` is blank, which now satisfies the required-store validation for both models.
+- **Admin promotions API** (`promotion_includes`): drop `:stores` from the includes array.
+- **Admin payment methods API**: the `joins(:store_payment_methods).where(spree_payment_methods_stores: …)` query for installed class names becomes `where(store_id: current_store.id).pluck(:type)` or simply `current_store.payment_methods.pluck(:type)`.
+- **Serializers**: no field changes — neither the promotion nor payment-method serializers currently expose `stores`/`store_ids`, so nothing to remove. (If any admin serializer is later found to expose `store_ids`, replace with `store_id` prefixed-id.)
+- **Webhook URL** in `PaymentMethod` (currently `stores.first`) becomes `store`.
+
+#### `available_for_store?` / `available_for_order?`
+
+`PaymentMethod#available_for_store?(store)` currently checks `store_ids.include?(store.id)`. Rewrite as `store_id == store.id`.
+
+#### Factories
+
+`promotion_factory` and `payment_method` factories currently push into `promotion.stores`. Replace with `store { Spree::Store.default || association(:store) }` assigning the FK directly.
+
+### Migrations
+
+Two migrations, following the Product pattern (`20260601000002_add_store_id_to_spree_products.rb`). No FK constraints, no defaults, nullable until backfill:
+
+```ruby
+class AddStoreIdToSpreePromotions < ActiveRecord::Migration[7.2]
+ def change
+ add_reference :spree_promotions, :store, null: true, index: true
+ end
+end
+```
+
+```ruby
+class AddStoreIdToSpreePaymentMethods < ActiveRecord::Migration[7.2]
+ def change
+ add_reference :spree_payment_methods, :store, null: true, index: true
+ end
+end
+```
+
+`spree_promotions_stores` and `spree_payment_methods_stores` are **not** touched.
+
+> **Critical window:** after migrating but before backfilling, every promotion/payment method has `store_id IS NULL` and is invisible to `for_store`. Backfill must run immediately after migrate, exactly as with products.
+
+## Migration Path
+
+A single rake task `spree:upgrade:populate_single_store_associations` (in `spree/core/lib/tasks/`), idempotent, batched, mirroring `spree:upgrade:populate_publications` but simpler (no publication/channel step — just FK backfill):
+
+```ruby
+task populate_single_store_associations: :environment do
+ shared = Hash.new(0) # owner-store summary, surfaced at the end
+
+ # Promotions: earliest store attachment wins as the owner
+ Spree::Promotion.where(store_id: nil).find_each do |promotion|
+ store_ids = Spree::StorePromotion.where(promotion_id: promotion.id)
+ .order(:created_at).pluck(:store_id)
+ next if store_ids.empty?
+
+ if store_ids.size > 1
+ shared[:promotions] += 1
+ Spree::Deprecation.warn(
+ "Promotion #{promotion.id} was shared across #{store_ids.size} stores; " \
+ "assigning to store #{store_ids.first}. Install spree_multi_store to keep sharing."
+ )
+ end
+ promotion.update_column(:store_id, store_ids.first)
+ end
+
+ # Payment methods: join table has no timestamps — pick lowest store_id deterministically
+ Spree::PaymentMethod.where(store_id: nil).find_each do |payment_method|
+ store_ids = Spree::StorePaymentMethod.where(payment_method_id: payment_method.id)
+ .order(:store_id).pluck(:store_id)
+ next if store_ids.empty?
+
+ if store_ids.size > 1
+ shared[:payment_methods] += 1
+ Spree::Deprecation.warn(
+ "PaymentMethod #{payment_method.id} was shared across #{store_ids.size} stores; " \
+ "assigning to store #{store_ids.first}. Install spree_multi_store to keep sharing."
+ )
+ end
+ payment_method.update_column(:store_id, store_ids.first)
+ end
+
+ if shared.values.sum.positive?
+ puts " #{shared[:promotions]} promotion(s) and #{shared[:payment_methods]} payment method(s) " \
+ "were shared across stores — only the owner store keeps them unless spree_multi_store is installed."
+ end
+end
+```
+
+For merchants who genuinely shared one promotion/payment method across N stores, the **earliest** (promotions) / **lowest `store_id`** (payment methods — its join table has no timestamps) attachment becomes the owner and the rest of the rows survive in the join table. Each shared record triggers a per-record `Spree::Deprecation` warning during backfill, plus an aggregate count in the task summary, so the loss is impossible to miss. Installing `spree_multi_store` restores the full `has_many :stores` view; without it, those extra stores lose the shared record (also documented as a breaking change in the upgrade guide, with a remediation note to duplicate the record per store or install the extension).
+
+Deployment order (identical shape to the channels upgrade):
+
+1. Deploy code (models, concerns, migrations, controller/serializer edits).
+2. `bundle exec rake db:migrate` → adds nullable `store_id` columns. **Promotions/payment methods now invisible to `for_store` until backfilled.**
+3. `bundle exec rake spree:upgrade:populate_single_store_associations` → backfills FKs. Resources visible again.
+
+**6.0 cleanup (separate cycle).** Once the `spree_multi_store` extension has shipped and the deprecation window has elapsed, a follow-up migration (a) sets `store_id` `null: false` and (b) drops the `spree_promotions_stores` / `spree_payment_methods_stores` join tables and removes the now-unused `StorePromotion` / `StorePaymentMethod` models, the `LegacyMultiStoreSupport` bridges, and the deprecated `StoreScopedResource` concern.
+
+### `spree_multi_store` extension responsibilities
+
+- Define `SpreeMultiStore` so core skips the `LegacyMultiStoreSupport` includes.
+- Re-declare `has_many :stores, through: :store_{promotions,payment_methods}` on both models and the inverse on `Store`.
+- Keep `StorePromotion` / `StorePaymentMethod` models and the join tables alive.
+- Restore the original multi-store `for_store` (`joins(:stores)`) and default-store-assignment semantics.
+
+This is the same contract the extension already fulfils for `Product has_many :stores`.
+
+## Constraints on Current Work
+
+Apply these now, even before implementation, to avoid widening the surface we have to migrate:
+
+- **Do not add new `store_ids`/`stores` usages** for promotions or payment methods. Write code against `store` / `store_id` (singular) where possible, or go through `current_store.promotions` / `current_store.payment_methods` so it survives the change transparently.
+- **Do not add new callers of `StoreScopedResource`'s through-based `for_store`** for these two models; prefer `current_store.<assoc>`.
+- **New API/serializer code must not expose `store_ids`** for these resources — there is no public field today, keep it that way.
+- When touching the `ResourceController` `store_ids=` bridge, leave it until the migration lands — it is the documented seam.
+
+## Resolved Decisions
+
+These were the original open questions, now settled (see Key Decisions / Migration Path for how they fold in):
+
+- **Multi-store data-loss signalling → loud.** Per-record `Spree::Deprecation` warning at backfill time for any record with >1 store attachment, plus an aggregate count in the rake summary and an upgrade-guide note.
+- **`null: false` timing → deferred to 6.0.** `store_id` stays nullable in 5.6 (matching the 5.5 Product migration); the 6.0 cleanup migration enforces not-null once data is clean.
+- **`StoreScopedResource` → deprecated, replaced by `SingleStoreResource`.** The concern is marked deprecated and its `include` dropped from both models, which now include `Spree::SingleStoreResource` (FK `for_store` + `ensure_store` + immutability) and declare a per-model `validates :store, presence: true`. `StoreScopedResource` is removed entirely in the 6.0 cleanup.
+- **Payment-method owner tiebreak → lowest `store_id`.** Deterministic and re-runnable; the join table has no timestamps so "earliest created" isn't available.
+
+## Open Questions
+
+- None outstanding. Reopen here if implementation surfaces new ones.
+
+## References
+
+- `docs/plans/6.0-channels-catalogs-b2b.md` — reference migration (single-owner Product, `LegacyMultiStoreSupport`, `spree_multi_store` extension split).
+- 5.5 Product migration code:
+ - `spree/core/app/models/spree/product/channels.rb` (`belongs_to :store`, `assign_default_store`)
+ - `spree/core/app/models/spree/product/legacy_multi_store_support.rb` (deprecation bridge to mirror)
+ - `spree/core/db/migrate/20260601000002_add_store_id_to_spree_products.rb` (migration shape)
+ - `spree/core/lib/tasks/publications.rake` (backfill task shape)
+- Current multi-store code being replaced:
+ - `spree/core/app/models/spree/promotion.rb`, `spree/core/app/models/spree/store_promotion.rb`
+ - `spree/core/app/models/spree/payment_method.rb`, `spree/core/app/models/spree/store_payment_method.rb`
+ - `spree/core/app/models/concerns/spree/store_scoped_resource.rb`
+ - `spree/api/app/controllers/spree/api/v3/resource_controller.rb` (the `store_ids=` bridge to delete)
diff --git a/spree/admin/spec/controllers/spree/admin/promotions_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/promotions_controller_spec.rb
index c43134a91f..09b06ea704 100644
--- a/spree/admin/spec/controllers/spree/admin/promotions_controller_spec.rb
+++ b/spree/admin/spec/controllers/spree/admin/promotions_controller_spec.rb
@@ -60,15 +60,15 @@ RSpec.describe Spree::Admin::PromotionsController, type: :controller do
{
name: 'New Promotion',
description: 'Promotion description',
- code: 'PROMO123',
- store_ids: [store.id]
+ code: 'PROMO123'
}
end
- it 'creates a new promotion' do
+ it 'creates a new promotion scoped to the current store' do
expect {
post :create, params: { promotion: promotion_params }
}.to change(Spree::Promotion, :count).by(1)
+ expect(assigns[:promotion].store).to eq(store)
end
it 'redirects to the edit page' do
diff --git a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
index fcffa381ed..2429d64cde 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/payment_methods_controller.rb
@@ -22,14 +22,7 @@ module Spree
def types
authorize! :create, model_class
- # Query via direct join rather than `current_store.payment_methods`
- # — the has_many-through association can cache stale results when
- # `current_store` was loaded earlier in the request (e.g. by the
- # auth layer).
- installed_class_names = Spree::PaymentMethod
- .joins(:store_payment_methods)
- .where(spree_payment_methods_stores: { store_id: current_store.id })
- .pluck(:type)
+ installed_class_names = current_store.payment_methods.pluck(:type)
installed_shorthands = installed_class_names.filter_map do |name|
name.safe_constantize&.api_type
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb
index f5402e4ee6..124cba47e8 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/promotions_controller.rb
@@ -69,7 +69,7 @@ module Spree
private
def promotion_includes
- [:stores, :promotion_actions, :promotion_rules]
+ [:promotion_actions, :promotion_rules]
end
end
end
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 ecfe29687b..9320c78fe3 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -114,8 +114,6 @@ module Spree
model_class.new(permitted_params)
end
resource.store = current_store if resource.respond_to?(:store_id) && resource.store_id.blank?
- # 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/core/app/models/concerns/spree/legacy_multi_store_support.rb b/spree/core/app/models/concerns/spree/legacy_multi_store_support.rb
new file mode 100644
index 0000000000..f98ff8cf25
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/legacy_multi_store_support.rb
@@ -0,0 +1,45 @@
+module Spree
+ # Backwards-compatible shim for resources migrated from a many-to-many store
+ # relationship to a single-store +belongs_to :store+ FK (Spree::Product in 5.5,
+ # Spree::Promotion and Spree::PaymentMethod in 5.6). Maps the historic
+ # +stores+/+store_ids+ accessors onto the singular +store+/+store_id+, warning
+ # on use. The +spree_multi_store+ extension defines +SpreeMultiStore+ to
+ # suppress the include and restore the real +has_many :stores+ association.
+ module LegacyMultiStoreSupport
+ extend ActiveSupport::Concern
+
+ included do
+ def stores
+ Spree::Deprecation.warn(
+ "#{self.class.base_class}#stores is deprecated. Please use #{self.class.base_class}#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(
+ "#{self.class.base_class}#store_ids is deprecated. Please use #{self.class.base_class}#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(
+ "#{self.class.base_class}#stores= is deprecated. Please use #{self.class.base_class}#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(
+ "#{self.class.base_class}#store_ids= is deprecated. Please use #{self.class.base_class}#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
diff --git a/spree/core/app/models/concerns/spree/store_scoped_resource.rb b/spree/core/app/models/concerns/spree/store_scoped_resource.rb
index 5a25884273..3bd5e4abdd 100644
--- a/spree/core/app/models/concerns/spree/store_scoped_resource.rb
+++ b/spree/core/app/models/concerns/spree/store_scoped_resource.rb
@@ -1,8 +1,18 @@
module Spree
+ # @deprecated Use a single-store +belongs_to :store+ FK instead. This concern
+ # modelled the historic many-to-many store relationship (Promotion,
+ # PaymentMethod) and is removed in Spree 6.0 once those models finish
+ # migrating to single-store ownership. See
+ # docs/plans/5.6-6.0-single-store-promotions-payment-methods.md.
module StoreScopedResource
extend ActiveSupport::Concern
included do
+ Spree::Deprecation.warn(
+ "Spree::StoreScopedResource is deprecated and will be removed in Spree 6.0. " \
+ "Use a single-store `belongs_to :store` FK instead (see Spree::Promotion / Spree::PaymentMethod)."
+ )
+
scope :for_store, ->(store) { joins(:stores).where(Store.table_name => { id: store.id }) }
before_validation :set_default_store, if: :new_record?
diff --git a/spree/core/app/models/spree/exports/coupon_codes.rb b/spree/core/app/models/spree/exports/coupon_codes.rb
index e541d72511..0b0cc4fdf7 100644
--- a/spree/core/app/models/spree/exports/coupon_codes.rb
+++ b/spree/core/app/models/spree/exports/coupon_codes.rb
@@ -14,8 +14,7 @@ module Spree
end
def scope
- model_class.joins(promotion: :stores).where(spree_stores: { id: store.id })
- .accessible_by(current_ability)
+ model_class.where(promotion: store.promotions).accessible_by(current_ability, :show)
end
end
end
diff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rb
index 874e20f473..3bd5cbac46 100644
--- a/spree/core/app/models/spree/payment_method.rb
+++ b/spree/core/app/models/spree/payment_method.rb
@@ -5,13 +5,15 @@ module Spree
acts_as_paranoid
acts_as_list
- include Spree::StoreScopedResource
+ include Spree::SingleStoreResource
include Spree::Metafields
include Spree::Metadata
include Spree::DisplayOn
if defined?(Spree::Security::PaymentMethods)
include Spree::Security::PaymentMethods
end
+ # Multi-store sharing moved to the spree_multi_store extension in 5.6.
+ include Spree::LegacyMultiStoreSupport unless defined?(SpreeMultiStore)
scope :active, -> { where(active: true).order(position: :asc) }
scope :available, -> { active.where(display_on: [:front_end, :back_end, :both]) }
@@ -20,10 +22,10 @@ module Spree
after_initialize :set_name, if: :new_record?
validates :name, presence: true
+ validates :store, presence: true, unless: -> { Spree::Config[:disable_store_presence_validation] }
normalizes :name, with: ->(value) { value&.to_s&.squish&.presence }
- has_many :store_payment_methods, class_name: 'Spree::StorePaymentMethod', inverse_of: :payment_method
- has_many :stores, class_name: 'Spree::Store', through: :store_payment_methods
+ belongs_to :store, class_name: 'Spree::Store'
has_many :payments, class_name: 'Spree::Payment', inverse_of: :payment_method, dependent: :nullify
has_many :credit_cards, class_name: 'Spree::CreditCard', dependent: :destroy # CCs are soft deleted
@@ -101,7 +103,6 @@ module Spree
# Returns the webhook URL for this payment method.
# @return [String, nil]
def webhook_url
- store = stores.first
return nil unless store
"#{store.url_or_custom_domain}/api/v3/webhooks/payments/#{prefixed_id}"
@@ -200,7 +201,7 @@ module Spree
def available_for_store?(store)
return true if store.blank?
- store_ids.include?(store.id)
+ store_id == store.id
end
def public_preferences
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 952a7e3431..235d38d962 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -34,7 +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::LegacyMultiStoreSupport unless defined?(SpreeMultiStore)
include Spree::SearchIndexable
if defined?(Spree::VendorConcern)
include Spree::VendorConcern
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
deleted file mode 100644
index 04af66f268..0000000000
--- a/spree/core/app/models/spree/product/legacy_multi_store_support.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-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/promotion.rb b/spree/core/app/models/spree/promotion.rb
index 5dbaad570a..dbf723a074 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -2,12 +2,14 @@ module Spree
class Promotion < Spree.base_class
has_prefix_id :promo # Spree-specific: promotion
- include Spree::StoreScopedResource
+ include Spree::SingleStoreResource
include Spree::Metafields
include Spree::Metadata
if defined?(Spree::Security::Promotions)
include Spree::Security::Promotions
end
+ # Multi-store sharing moved to the spree_multi_store extension in 5.6.
+ include Spree::LegacyMultiStoreSupport unless defined?(SpreeMultiStore)
publishes_lifecycle_events
@@ -37,8 +39,7 @@ module Spree
has_many :coupon_codes, -> { order(created_at: :asc) }, dependent: :destroy, class_name: 'Spree::CouponCode'
has_many :order_promotions, class_name: 'Spree::OrderPromotion'
has_many :orders, through: :order_promotions, class_name: 'Spree::Order'
- has_many :store_promotions, class_name: 'Spree::StorePromotion'
- has_many :stores, class_name: 'Spree::Store', through: :store_promotions
+ belongs_to :store, class_name: 'Spree::Store'
after_save :apply_pending_rules_and_actions, if: :pending_rules_or_actions?
@@ -60,6 +61,7 @@ module Spree
#
validates_associated :rules
validates :name, presence: true
+ validates :store, presence: true, unless: -> { Spree::Config[:disable_store_presence_validation] }
validates :usage_limit, numericality: { greater_than: 0, allow_nil: true }
validates :description, length: { maximum: 255 }, allow_blank: true
validate :expires_at_must_be_later_than_starts_at, if: -> { starts_at && expires_at }
diff --git a/spree/core/app/models/spree/promotion_handler/promotion_duplicator.rb b/spree/core/app/models/spree/promotion_handler/promotion_duplicator.rb
index f9652bb191..eef82afe36 100644
--- a/spree/core/app/models/spree/promotion_handler/promotion_duplicator.rb
+++ b/spree/core/app/models/spree/promotion_handler/promotion_duplicator.rb
@@ -11,7 +11,7 @@ module Spree
@new_promotion.path = "#{@promotion.path}_#{@random_string}"
@new_promotion.name = "New #{@promotion.name}"
@new_promotion.code = "#{@promotion.code}_#{@random_string}"
- @new_promotion.stores = @promotion.stores
+ @new_promotion.store = @promotion.store
ActiveRecord::Base.transaction do
@new_promotion.save
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 3b5bb62446..80db834c60 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -74,8 +74,9 @@ module Spree
has_many :return_authorizations, through: :orders, class_name: 'Spree::ReturnAuthorization'
# has_many :reimbursements, through: :orders, class_name: 'Spree::Reimbursement' FIXME: we should fetch this via Customer Return
- has_many :store_payment_methods, class_name: 'Spree::StorePaymentMethod'
- has_many :payment_methods, through: :store_payment_methods, class_name: 'Spree::PaymentMethod'
+ # :nullify (not :destroy) — clearing the collection must not cascade into
+ # Promotion#not_used? / payment records; orphaned rows are detached, not deleted.
+ has_many :payment_methods, class_name: 'Spree::PaymentMethod', dependent: :nullify
has_many :products, class_name: 'Spree::Product', dependent: :nullify
has_many :product_publications, through: :channels, source: :publications, class_name: 'Spree::ProductPublication'
@@ -94,8 +95,7 @@ module Spree
has_many :taxons, class_name: 'Spree::Taxon'
has_many :categories, class_name: 'Spree::Category'
- has_many :store_promotions, class_name: 'Spree::StorePromotion'
- has_many :promotions, through: :store_promotions, class_name: 'Spree::Promotion'
+ has_many :promotions, class_name: 'Spree::Promotion', dependent: :nullify
has_many :wishlists, class_name: 'Spree::Wishlist'
diff --git a/spree/core/app/models/spree/store_payment_method.rb b/spree/core/app/models/spree/store_payment_method.rb
index f657a41a61..f4fdc8fd60 100644
--- a/spree/core/app/models/spree/store_payment_method.rb
+++ b/spree/core/app/models/spree/store_payment_method.rb
@@ -1,9 +1,13 @@
module Spree
+ # Legacy join between Store and PaymentMethod. Superseded by the single-store
+ # +PaymentMethod#store+ FK in 5.6; retained only so the +spree_multi_store+
+ # extension can restore +has_many :stores+ and so the backfill task can read
+ # historic attachments. Dropped in 6.0.
class StorePaymentMethod < Spree.base_class
self.table_name = 'spree_payment_methods_stores'
belongs_to :store, class_name: 'Spree::Store', touch: true
- belongs_to :payment_method, class_name: 'Spree::PaymentMethod', touch: true, inverse_of: :store_payment_methods
+ belongs_to :payment_method, class_name: 'Spree::PaymentMethod', touch: true
validates :store, :payment_method, presence: true
validates :store_id, uniqueness: { scope: :payment_method_id }
diff --git a/spree/core/app/models/spree/store_promotion.rb b/spree/core/app/models/spree/store_promotion.rb
index 0c145942ec..0efe234357 100644
--- a/spree/core/app/models/spree/store_promotion.rb
+++ b/spree/core/app/models/spree/store_promotion.rb
@@ -1,4 +1,8 @@
module Spree
+ # Legacy join between Store and Promotion. Superseded by the single-store
+ # +Promotion#store+ FK in 5.6; retained only so the +spree_multi_store+
+ # extension can restore +has_many :stores+ and so the backfill task can read
+ # historic attachments. Dropped in 6.0.
class StorePromotion < Spree.base_class
self.table_name = 'spree_promotions_stores'
diff --git a/spree/core/db/migrate/20260628000001_add_store_id_to_spree_promotions.rb b/spree/core/db/migrate/20260628000001_add_store_id_to_spree_promotions.rb
new file mode 100644
index 0000000000..1065b88298
--- /dev/null
+++ b/spree/core/db/migrate/20260628000001_add_store_id_to_spree_promotions.rb
@@ -0,0 +1,10 @@
+class AddStoreIdToSpreePromotions < ActiveRecord::Migration[7.2]
+ # NOTE: After running this migration, existing promotions have +store_id IS NULL+
+ # and are invisible to +Promotion.for_store+. Run the backfill immediately to
+ # copy ownership from the legacy +spree_promotions_stores+ join table:
+ #
+ # bundle exec rake spree:upgrade:populate_single_store_associations
+ def change
+ add_reference :spree_promotions, :store, null: true, if_not_exists: true
+ end
+end
diff --git a/spree/core/db/migrate/20260628000002_add_store_id_to_spree_payment_methods.rb b/spree/core/db/migrate/20260628000002_add_store_id_to_spree_payment_methods.rb
new file mode 100644
index 0000000000..de76e22e9b
--- /dev/null
+++ b/spree/core/db/migrate/20260628000002_add_store_id_to_spree_payment_methods.rb
@@ -0,0 +1,11 @@
+class AddStoreIdToSpreePaymentMethods < ActiveRecord::Migration[7.2]
+ # NOTE: After running this migration, existing payment methods have
+ # +store_id IS NULL+ and are invisible to +PaymentMethod.for_store+. Run the
+ # backfill immediately to copy ownership from the legacy
+ # +spree_payment_methods_stores+ join table:
+ #
+ # bundle exec rake spree:upgrade:populate_single_store_associations
+ def change
+ add_reference :spree_payment_methods, :store, null: true, if_not_exists: true
+ end
+end
diff --git a/spree/core/db/sample_data/promotions.rb b/spree/core/db/sample_data/promotions.rb
index 15ee04b347..92699bb3f0 100644
--- a/spree/core/db/sample_data/promotions.rb
+++ b/spree/core/db/sample_data/promotions.rb
@@ -2,7 +2,7 @@ promotion = Spree::Promotion.where(
name: 'Free Shipping',
code: 'FREESHIP'
).first_or_create! do |promo|
- promo.stores = Spree::Store.all
+ promo.store = Spree::Store.default
end
Spree::Promotion::Actions::FreeShipping.where(promotion: promotion).first_or_create!
diff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rb
index 9100d76339..5decc98223 100644
--- a/spree/core/lib/spree/permitted_attributes.rb
+++ b/spree/core/lib/spree/permitted_attributes.rb
@@ -198,7 +198,7 @@ module Spree
]
@@promotion_attributes = [:name, :description, :starts_at, :expires_at, :code, :usage_limit, :path, :match_policy,
- :advertise, :promotion_category_id, :code_prefix, :kind, :number_of_codes, :multi_codes, store_ids: []]
+ :advertise, :promotion_category_id, :code_prefix, :kind, :number_of_codes, :multi_codes]
@@promotion_rule_attributes = [:type, :preferred_match_policy, preferred_eligible_values: [], user_ids_to_add: [], product_ids_to_add: [], taxon_ids_to_add: []]
diff --git a/spree/core/lib/spree/testing_support/factories/export_factory.rb b/spree/core/lib/spree/testing_support/factories/export_factory.rb
index c8704045f6..20cb395161 100644
--- a/spree/core/lib/spree/testing_support/factories/export_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/export_factory.rb
@@ -16,5 +16,9 @@ FactoryBot.define do
factory :customer_export, class: 'Spree::Exports::Customers', parent: :export do
type { 'Spree::Exports::Customers' }
end
+
+ factory :coupon_code_export, class: 'Spree::Exports::CouponCodes', parent: :export do
+ type { 'Spree::Exports::CouponCodes' }
+ end
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/payment_method_factory.rb b/spree/core/lib/spree/testing_support/factories/payment_method_factory.rb
index 26126fd7be..777767bfc8 100644
--- a/spree/core/lib/spree/testing_support/factories/payment_method_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/payment_method_factory.rb
@@ -2,15 +2,7 @@ FactoryBot.define do
factory :payment_method, class: Spree::PaymentMethod do
type { 'Spree::PaymentMethod' }
name { 'Test' }
-
- before(:create) do |payment_method|
- if payment_method.stores.empty?
- default_store = Spree::Store.default.persisted? ? Spree::Store.default : nil
- store = default_store || create(:store)
-
- payment_method.stores << store
- end
- end
+ store { Spree::Store.find_by(default: true) || association(:store) }
end
factory :check_payment_method, parent: :payment_method, class: Spree::PaymentMethod::Check do
diff --git a/spree/core/lib/spree/testing_support/factories/promotion_factory.rb b/spree/core/lib/spree/testing_support/factories/promotion_factory.rb
index bf312f3bcc..0998179bcf 100644
--- a/spree/core/lib/spree/testing_support/factories/promotion_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/promotion_factory.rb
@@ -17,19 +17,11 @@ FactoryBot.define do
factory :promotion, class: Spree::Promotion do
name { 'Promo' }
+ store { Spree::Store.find_by(default: true) || association(:store) }
sequence :code do |n|
"CODE-#{n}"
end
- before(:create) do |promotion, _evaluator|
- if promotion.stores.empty?
- default_store = Spree::Store.default.persisted? ? Spree::Store.default : nil
- store = default_store || create(:store)
-
- promotion.stores << [store]
- end
- end
-
trait :with_line_item_adjustment do
transient do
adjustment_rate { 10 }
diff --git a/spree/core/lib/spree/upgrades/5_5_to_5_6/manifest.yml b/spree/core/lib/spree/upgrades/5_5_to_5_6/manifest.yml
index d53b546eeb..44df0bb400 100644
--- a/spree/core/lib/spree/upgrades/5_5_to_5_6/manifest.yml
+++ b/spree/core/lib/spree/upgrades/5_5_to_5_6/manifest.yml
@@ -28,3 +28,15 @@ steps:
resolves roles by store. Store-scoped assignments only; extensions (e.g.
spree_multi_vendor) backfill their own resource types. Store admins stay
authorized via the spree_admin? fallback until this runs.
+
+ - id: single_store_promotions_payment_methods
+ name: "Backfill store_id on promotions and payment methods"
+ task: "spree:upgrade:populate_single_store_associations"
+ notes: |
+ Sets store_id on Spree::Promotion and Spree::PaymentMethod from the legacy
+ spree_promotions_stores / spree_payment_methods_stores join tables. Until
+ this runs, migrated rows have a NULL store_id and are hidden from
+ store-scoped lookups (and unavailable at checkout), so run it right after
+ db:migrate. Records shared across stores keep one owner (promotions:
+ earliest then lowest store_id; payment methods: lowest store_id) unless
+ spree_multi_store is installed.
diff --git a/spree/core/lib/tasks/single_store_associations.rake b/spree/core/lib/tasks/single_store_associations.rake
new file mode 100644
index 0000000000..e3ff0b4fe1
--- /dev/null
+++ b/spree/core/lib/tasks/single_store_associations.rake
@@ -0,0 +1,65 @@
+namespace :spree do
+ namespace :upgrade do
+ desc <<~DESC
+ Populates +spree_promotions.store_id+ and +spree_payment_methods.store_id+
+ from the legacy +spree_promotions_stores+ / +spree_payment_methods_stores+
+ join tables. Idempotent — re-running skips records that already have a
+ +store_id+.
+
+ Run once after upgrading to Spree 5.6+. Multi-store merchants must install
+ +spree_multi_store+ before running; without it, a record shared across
+ several stores keeps only one owner (promotions: the earliest
+ +spree_promotions_stores+ row by +created_at+; payment methods: the lowest
+ +store_id+, since that join has no timestamps) and the other stores lose
+ the shared record. Each shared record is logged so the loss is visible.
+ DESC
+ task populate_single_store_associations: :environment do
+ shared = Hash.new(0)
+
+ if ActiveRecord::Base.connection.table_exists?(Spree::StorePromotion.table_name)
+ Spree::Promotion.where(store_id: nil).find_each do |promotion|
+ store_ids = Spree::StorePromotion.where(promotion_id: promotion.id).order(:created_at, :store_id).pluck(:store_id)
+ next if store_ids.empty?
+
+ if store_ids.size > 1
+ shared[:promotions] += 1
+ Spree::Deprecation.warn(
+ "Promotion #{promotion.id} was shared across #{store_ids.size} stores; " \
+ "assigning it to store #{store_ids.first}. Install spree_multi_store to keep sharing."
+ )
+ end
+
+ promotion.update_column(:store_id, store_ids.first)
+ end
+ else
+ puts " #{Spree::StorePromotion.table_name} table not found — skipping promotions."
+ end
+
+ if ActiveRecord::Base.connection.table_exists?(Spree::StorePaymentMethod.table_name)
+ # +with_deleted+: PaymentMethod is paranoid, so soft-deleted rows would
+ # otherwise be skipped and keep a NULL store_id.
+ Spree::PaymentMethod.with_deleted.where(store_id: nil).find_each do |payment_method|
+ store_ids = Spree::StorePaymentMethod.where(payment_method_id: payment_method.id).order(:store_id).pluck(:store_id)
+ next if store_ids.empty?
+
+ if store_ids.size > 1
+ shared[:payment_methods] += 1
+ Spree::Deprecation.warn(
+ "PaymentMethod #{payment_method.id} was shared across #{store_ids.size} stores; " \
+ "assigning it to store #{store_ids.first}. Install spree_multi_store to keep sharing."
+ )
+ end
+
+ payment_method.update_column(:store_id, store_ids.first)
+ end
+ else
+ puts " #{Spree::StorePaymentMethod.table_name} table not found — skipping payment methods."
+ end
+
+ if shared.values.sum.positive?
+ puts " #{shared[:promotions]} promotion(s) and #{shared[:payment_methods]} payment method(s) " \
+ "were shared across stores — only the owner store keeps them unless spree_multi_store is installed."
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/core/controller_helpers/store_spec.rb b/spree/core/spec/lib/spree/core/controller_helpers/store_spec.rb
index 4071fe6d25..a28bc31b6e 100644
--- a/spree/core/spec/lib/spree/core/controller_helpers/store_spec.rb
+++ b/spree/core/spec/lib/spree/core/controller_helpers/store_spec.rb
@@ -27,34 +27,33 @@ describe Spree::Core::ControllerHelpers::Store, type: :controller do
let!(:store) { @default_store }
let!(:store_2) { create :store }
- context 'on an object that accepts multiple stores' do
+ context 'on a single-store object (payment method)' do
before { allow(controller).to receive(:current_store).and_return(store) }
- context 'when the object has no stores associated' do
- let(:object) { build(:payment_method, stores: []) }
+ context 'when the object has no store associated' do
+ let(:object) { build(:payment_method, store: nil) }
it 'associates the object with the current_store' do
controller.ensure_current_store(object)
- expect(object.stores).to contain_exactly(store)
- expect(object.stores).not_to contain_exactly(store_2)
+ expect(object.store).to eq(store)
+ expect(object.store).not_to eq(store_2)
end
end
- context 'when the object has a store pre assigned' do
- let(:object) { create(:payment_method, stores: [store_2]) }
+ context 'when the object has a different store pre assigned' do
+ let(:object) { create(:payment_method, store: store_2) }
- it 'adds the new store without removing the original store' do
- controller.ensure_current_store(object)
- expect(object.stores).to contain_exactly(store, store_2)
+ it 'raises an exception' do
+ expect { controller.ensure_current_store(object) }.to raise_error('Store is already set')
end
end
- context 'when the object has a store and the same store is attempted to be added' do
- let(:object) { create(:payment_method) }
+ context 'when the object already has the current store assigned' do
+ let(:object) { create(:payment_method, store: store) }
it 'object is not changed' do
controller.ensure_current_store(object)
- expect(object.stores).to contain_exactly(store)
+ expect(object.store).to eq(store)
end
end
end
diff --git a/spree/core/spec/lib/tasks/single_store_associations_spec.rb b/spree/core/spec/lib/tasks/single_store_associations_spec.rb
new file mode 100644
index 0000000000..c65717af83
--- /dev/null
+++ b/spree/core/spec/lib/tasks/single_store_associations_spec.rb
@@ -0,0 +1,99 @@
+require 'spec_helper'
+require 'rake'
+
+describe 'spree:upgrade:populate_single_store_associations' do
+ subject { Rake::Task[task_name] }
+
+ let(:task_name) { 'spree:upgrade:populate_single_store_associations' }
+
+ before(:all) do
+ Rake::Task.define_task(:environment)
+ load Spree::Core::Engine.root.join('lib', 'tasks', 'single_store_associations.rake')
+ end
+
+ before { subject.reenable }
+
+ let!(:default_store) { Spree::Store.find_by(default: true) || create(:store, default: true) }
+
+ describe 'promotions' do
+ let!(:promotion) { create(:promotion, store: default_store) }
+
+ # Simulate the pre-5.6 state: store_id nil + a legacy join row.
+ before do
+ promotion.update_columns(store_id: nil)
+ Spree::StorePromotion.create!(promotion: promotion, store: default_store)
+ end
+
+ it 'sets store_id from the legacy join row' do
+ expect { subject.invoke }.to change { promotion.reload.store_id }.from(nil).to(default_store.id)
+ end
+
+ it 'is idempotent — a re-run changes nothing' do
+ subject.invoke
+ subject.reenable
+ expect { subject.invoke }.not_to change { promotion.reload.store_id }
+ end
+
+ context 'when shared across multiple stores' do
+ let!(:other_store) { create(:store, default: false) }
+
+ before do
+ # Earliest legacy row wins. Backdate the default-store row so it's
+ # older than the other-store row and assert it's chosen.
+ Spree::StorePromotion.where(promotion_id: promotion.id).update_all(created_at: 2.days.ago)
+ Spree::StorePromotion.create!(promotion: promotion, store: other_store, created_at: 1.day.ago)
+ end
+
+ it 'assigns the earliest store and reports the shared record' do
+ expect { subject.invoke }
+ .to output(/shared across stores/).to_stdout
+ .and change { promotion.reload.store_id }.from(nil).to(default_store.id)
+ end
+ end
+ end
+
+ describe 'payment methods' do
+ let!(:payment_method) { create(:check_payment_method, store: default_store) }
+
+ before do
+ payment_method.update_columns(store_id: nil)
+ Spree::StorePaymentMethod.create!(payment_method: payment_method, store: default_store)
+ end
+
+ it 'sets store_id from the legacy join row' do
+ expect { subject.invoke }.to change { payment_method.reload.store_id }.from(nil).to(default_store.id)
+ end
+
+ it 'is idempotent — a re-run changes nothing' do
+ subject.invoke
+ subject.reenable
+ expect { subject.invoke }.not_to change { payment_method.reload.store_id }
+ end
+
+ context 'when shared across multiple stores' do
+ let!(:other_store) { create(:store, default: false) }
+
+ before do
+ Spree::StorePaymentMethod.create!(payment_method: payment_method, store: other_store)
+ end
+
+ # No timestamps on the join — the lowest store_id is the deterministic owner.
+ it 'assigns the lowest store_id' do
+ subject.invoke
+ expect(payment_method.reload.store_id).to eq([default_store.id, other_store.id].min)
+ end
+ end
+ end
+
+ context 'legacy tables not present' do
+ before do
+ allow(ActiveRecord::Base.connection).to receive(:table_exists?).and_call_original
+ allow(ActiveRecord::Base.connection).to receive(:table_exists?).with('spree_promotions_stores').and_return(false)
+ allow(ActiveRecord::Base.connection).to receive(:table_exists?).with('spree_payment_methods_stores').and_return(false)
+ end
+
+ it 'no-ops with a message' do
+ expect { subject.invoke }.to output(/not found/).to_stdout
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/exports/coupon_codes_spec.rb b/spree/core/spec/models/spree/exports/coupon_codes_spec.rb
new file mode 100644
index 0000000000..4a402f9ab3
--- /dev/null
+++ b/spree/core/spec/models/spree/exports/coupon_codes_spec.rb
@@ -0,0 +1,19 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Exports::CouponCodes do
+ let(:store) { @default_store }
+ let(:user) { create(:admin_user) }
+ let(:export) { build(:coupon_code_export, store: store, user: user, format: 'csv') }
+
+ describe '#scope' do
+ let!(:promotion) { create(:promotion, store: store, multi_codes: true, number_of_codes: 1, code_prefix: 'SAVE') }
+ let!(:other_promotion) { create(:promotion, store: create(:store), multi_codes: true, number_of_codes: 1, code_prefix: 'NOPE') }
+
+ # Regression: the scope must resolve via the single-store FK on Promotion,
+ # not the removed has_many :stores join.
+ it 'returns only coupon codes for promotions owned by the export store' do
+ expect { export.records_to_export.to_a }.not_to raise_error
+ expect(export.records_to_export.map(&:promotion_id).uniq).to eq([promotion.id])
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/gateway_spec.rb b/spree/core/spec/models/spree/gateway_spec.rb
index 670ea8e065..7ecf22b3c2 100644
--- a/spree/core/spec/models/spree/gateway_spec.rb
+++ b/spree/core/spec/models/spree/gateway_spec.rb
@@ -35,7 +35,7 @@ describe Spree::Gateway, type: :model do
end
it 'validates the type' do
- expect(TestGateway.new.valid?).to be_truthy
+ expect(TestGateway.new(store: @default_store).valid?).to be_truthy
end
it 'automatically sets the name' do
diff --git a/spree/core/spec/services/spree/seeds/payment_methods_spec.rb b/spree/core/spec/services/spree/seeds/payment_methods_spec.rb
index bb0d21dbb9..12020faf49 100644
--- a/spree/core/spec/services/spree/seeds/payment_methods_spec.rb
+++ b/spree/core/spec/services/spree/seeds/payment_methods_spec.rb
@@ -14,7 +14,7 @@ RSpec.describe Spree::Seeds::PaymentMethods do
payment_method = s.payment_methods.store_credit.first
expect(payment_method).to be_present
expect(payment_method).to be_active
- expect(payment_method.stores).to contain_exactly(s)
+ expect(payment_method.store).to eq(s)
expect(payment_method.name).to eq('Store Credit')
expect(payment_method.description).to eq('Store Credit')
end
@@ -22,13 +22,15 @@ RSpec.describe Spree::Seeds::PaymentMethods do
context 'when a store already has a Store Credit payment method' do
before do
- create(
- :store_credit_payment_method,
- stores: [store, other_store],
- name: 'Store Credit',
- description: 'Store Credit',
- active: true
- )
+ [store, other_store].each do |s|
+ create(
+ :store_credit_payment_method,
+ store: s,
+ name: 'Store Credit',
+ description: 'Store Credit',
+ active: true
+ )
+ end
end
it "doesn't create a new payment method" do