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.

Scope custom field definitions to a store (#14554)

Damian Legawiec11a5820ee3b8
diff --git a/docs/developer/core-concepts/metafields.mdx b/docs/developer/core-concepts/metafields.mdx
index 86cf52f329..26abfeae9a 100644
--- a/docs/developer/core-concepts/metafields.mdx
+++ b/docs/developer/core-concepts/metafields.mdx
@@ -203,6 +203,14 @@ In the dashboard, fields with these flags become available in the product table'
Most things you'd want to annotate: products, variants, orders, line items, customers, categories, payments, fulfillments, gift cards and store credits, among others.
+## Definitions belong to a store
+
+A definition is owned by the store it was created in. Each store keeps its own
+set, so two stores can both define `custom.material` without colliding, and
+neither can read or edit the other's. Everything that reads the schema — the
+dashboard, CSV exports and imports, and product sorting and filtering — reads
+the current store's definitions.
+
## Custom fields or metadata?
Spree has two ways to store your own data, and they are not competing — they solve different problems.
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index df9fb1e0c9..8504219f9f 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -360,6 +360,10 @@ Two behavior notes for extension authors: `Spree::Metadata` no longer includes t
**BREAKING — product CSV.** Custom-field columns are now prefixed `custom_field.` instead of `metafield.` (for example `custom_field.custom.material`). Exports emit the new prefix and imports only recognise the new prefix, so update any saved import templates and any integration that reads the export. A file still using the old prefix imports without its custom-field values rather than failing.
+**Definitions now belong to a store.** They used to be global, shared by every store in an installation. `db:migrate` assigns every existing definition to the default store and gives it a `filter_key` column (the `cf_…` identifier that used to be recomputed on every read). Read them through the store — `store.custom_field_definitions` — rather than the class; the admin endpoint is store-scoped, so a definition belonging to another store now returns 404 instead of being readable and editable.
+
+Single-store installations notice nothing. **A multi-store installation ends up with its whole schema on the default store**, and its other stores start empty: create the fields you want on each store, or run `bin/rake spree:upgrade:backfill_custom_field_definition_stores` first if the migration ran before any store existed. Existing values keep pointing at the definitions they always did, which is why the rows are not copied — copies would render blank anyway. Two definitions whose `namespace`/`key` pair flattens to one `cf_…` key (`("a_b", "c")` and `("a", "b_c")`) can no longer coexist in a store; the migration suffixes the later one and names it in its output so you can rename it.
+
### The Legacy order-routing strategy is gone
`Spree::OrderRouting::Strategy::Legacy` — the pre-5.5 escape hatch that delegated straight to `Spree::Stock::Coordinator` and consulted no routing rules — is removed and no longer registered in `Spree.order_routing.strategies`.
diff --git a/docs/plans/6.0-store-scoped-custom-field-definitions.md b/docs/plans/6.0-store-scoped-custom-field-definitions.md
index 721e266caf..61c0becadf 100644
--- a/docs/plans/6.0-store-scoped-custom-field-definitions.md
+++ b/docs/plans/6.0-store-scoped-custom-field-definitions.md
@@ -1,27 +1,29 @@
# Store-scoped Custom Field Definitions + persisted `filter_key`
-**Status:** Draft
+**Status:** Implemented (2026-09-02)
**Target:** Spree 6.0
**Depends on:** `5.4-6.0-custom-fields-rename.md`, `5.6-6.0-single-store-promotions-payment-methods.md`
**Author:** Damian Legawiec
-**Last updated:** 2026-07-27
+**Last updated:** 2026-09-02
## Summary
-`Spree::MetafieldDefinition` (public name: `Spree::CustomFieldDefinition`) is
-currently **global** — it has no `store_id`, and nothing scopes it by store.
-Every store in an installation shares one custom-field schema, and the Admin API
-lets any store's admin read and edit every other store's definitions.
+`Spree::CustomFieldDefinition` (renamed from `Spree::MetafieldDefinition` by the
+custom-fields rename) was **global** — it had no `store_id`, and nothing scoped
+it by store. Every store in an installation shared one custom-field schema, and
+the Admin API let any store's staff read and edit every other store's
+definitions.
-Two related changes are deferred here from the 5.6 custom-field search/sort/filter
-work (that PR shipped as a patch release and these are schema changes):
+Two related changes were deferred here from the 5.6 custom-field
+search/sort/filter work (that PR shipped as a patch release and these are schema
+changes):
1. **`store_id` on definitions** — make custom-field schema store-owned, matching
the single-owner direction already taken for Product, Promotion, and
PaymentMethod.
2. **Persist `filter_key`** — the `cf_<namespace>_<key>` identifier used to sort
- and filter product listings is currently computed in Ruby on every call. A
- column lets it be uniquely indexed and looked up directly.
+ and filter product listings was computed in Ruby on every call. A column lets
+ it be uniquely indexed and looked up directly.
Together they make uniqueness `(store_id, resource_type, filter_key)`, enforced
by both a model validation and a DB unique index.
@@ -30,110 +32,130 @@ by both a model validation and a DB unique index.
- **`filter_key` is the name**, not `search_key` — the value drives sorting and
filtering, not just text search. `full_key` was already taken: it returns the
- dotted `custom.material` form used by CSV headers (`metafield.custom.material`)
+ dotted `custom.material` form used by CSV headers (`custom_field.custom.material`)
and the Store API's `key` field, and must not be repurposed.
- **Format stays `cf_<namespace>_<key>`.** Not `cf_<namespace.length>_...` (the
original length-delimited form, dropped as unreadable) and not the definition's
prefixed ID (opaque, and not portable across environments).
- **Uniqueness needs enforcing either way.** `key` is already unique per
- `(resource_type, namespace)`, but both segments normalize to underscored slugs,
- so `("a_b", "c")` and `("a", "b_c")` both flatten to `cf_a_b_c` — one of them
- would be unaddressable. Until the column exists this is a `CONCAT`-based
- validation (`MetafieldDefinition::SearchCapabilities#filter_key_must_be_unique`);
- after, it becomes a plain uniqueness validation plus a unique index.
-- **Definitions get a `has_many` on Store**, not a `for_store` scope — the
- association is the scoping mechanism (`store.metafield_definitions`).
+ `(store_id, resource_type, namespace)`, but both segments normalize to
+ underscored slugs, so `("a_b", "c")` and `("a", "b_c")` both flatten to
+ `cf_a_b_c` — one of them would be unaddressable. This was a `CONCAT`-based
+ validation with no index behind it; it is now a plain uniqueness validation
+ plus a unique index.
+- **Definitions get a `has_many` on Store**, not a `for_store` scope of their own
+ — the association is the scoping mechanism (`store.custom_field_definitions`).
+ `Spree::SingleStoreResource` supplies the `belongs_to`, the `Spree::Current`
+ fallback and the immutable-owner guard, and `Spree::Base.for_store` resolves
+ through the association, so the Admin API controller became store-scoped
+ without an override.
+
+### Settled 2026-09-02
+
+- **Existing definitions all move to the default store**, rather than being
+ copied per store. Copies would have produced N duplicate rows whose values
+ still pointed at the originals, so every non-default store would show the same
+ blank fields it shows under the simpler backfill — at N times the rows, plus a
+ re-pointing pass over `spree_custom_fields`. Multi-store operators re-create
+ the fields they want on their other stores.
+- **The migration backfills and enforces `null: false` itself.** Shipping the
+ columns nullable would void the unique index outright — SQL treats NULLs as
+ distinct, so uniqueness would look enforced while not holding. Follows the
+ return/refund reason precedent already shipped in 6.0;
+ `spree:upgrade:backfill_custom_field_definition_stores` is the recovery path
+ for installs whose migration ran before any store existed.
+- **A custom field's value is validated to agree with its definition's store**
+ (revised during implementation — the original ruling was the opposite). The
+ premise, that every path resolving a definition is store-scoped, was false:
+ Rails' own `accepts_nested_attributes_for` writer assigns
+ `custom_field_definition_id` straight onto the row and reaches no resolver.
+ The check lives on `Spree::CustomField` beside the `resource_type` agreement
+ check already there, and skips resources with no store of their own — a
+ customer and an address are global, and were resolved within a store on the
+ way in.
## Design Details
### Schema
```ruby
-add_column :spree_metafield_definitions, :filter_key, :string
-add_reference :spree_metafield_definitions, :store, index: true # nullable at 5.x, null: false at 6.0
+add_reference :spree_custom_field_definitions, :store # backfilled, then null: false
+add_column :spree_custom_field_definitions, :filter_key, :string # backfilled, then null: false
-add_index :spree_metafield_definitions, [:store_id, :resource_type, :filter_key],
- unique: true, name: 'index_metafield_definitions_on_store_and_filter_key'
+add_index :spree_custom_field_definitions, [:store_id, :resource_type, :filter_key],
+ unique: true, name: 'index_custom_field_definitions_on_store_and_filter_key'
```
+The pre-existing `(resource_type, namespace, key)` unique index is replaced by a
+store-scoped one.
+
### Model
-- `Spree::Store` gains `has_many :metafield_definitions, dependent: :destroy_async`
- plus a `custom_field_definitions` alias.
-- `Spree::MetafieldDefinition` gains `belongs_to :store`, a
- `before_validation :set_filter_key` callback (so the value follows a renamed
- namespace/key and back-fills on next write), and store-scoped uniqueness on
- both `key` and `filter_key`.
-- Backend callers that create definitions implicitly need a store. `set_default_store`
- falls back to `Spree::Current.store || Spree::Store.default`.
+- `Spree::Store` gains `has_many :custom_field_definitions, dependent: :destroy_async`.
+- `Spree::CustomFieldDefinition` includes `Spree::SingleStoreResource` and gains a
+ `before_validation :set_filter_key` callback, so the value follows a renamed
+ namespace or key.
+- `filter_key` is read from the column, falling back to the computed form for an
+ unsaved record whose callback has not run yet.
-### Call sites that must become store-scoped
+### Call sites that became store-scoped
-All of these currently fetch definitions with `for_resource_type` and no store
-filter. The CSV pairs must stay in lockstep or header and value columns
-misalign:
+All of these fetched definitions with `for_resource_type` and no store filter.
+The CSV pairs must stay in lockstep or header and value columns misalign:
| Location | Note |
|---|---|
-| `Spree::Export#metafields_headers` | header row |
-| `Spree::Product#to_csv` | value row — must match the header scope |
-| `Spree::Order#to_csv` | value row — takes a store arg that is currently ignored (`_store`) |
-| `Spree::Import#metafield_definitions_for_model` | |
+| `Spree::Export#custom_fields_headers` | header row |
+| `Spree::Product#to_csv` | value row — takes the store the export runs for |
+| `Spree::Order#to_csv` | value row — its store argument was ignored (`_store`) |
+| `Spree::CSV::CustomFieldsHelper` | customer / gift card / newsletter presenters |
+| `Spree::Import#custom_field_definitions_for_model` | |
| `Spree::Product.search` scope | |
-| `Spree::SearchProvider::MetafieldSchema#product_definitions` | needs a `store` constructor arg |
-| `Spree::Metafields.ensure_metafield_definition_exists!` | auto-creates — needs a store |
-| `Spree::Metafields#resolve_metafield_definition_id_from_string` | auto-creates via the `"namespace.key"` form |
-| `Api::V3::Admin::CustomFieldDefinitionsController#scope` | currently unscoped — cross-store read/write |
-| `Spree::ProductTypeCustomFieldDefinition` (`6.0-product-types.md`) | the ProductType↔definition join validates same-store (`definition.store_id == product_type.store_id`) — ProductType is store-owned in the same release |
+| `Spree::SearchProvider::CustomFieldSchema` | takes a `store` constructor argument |
+| `Spree::HasCustomFields.ensure_custom_field_definition_exists!` | auto-creates — needs a store |
+| `Spree::HasCustomFields#resolve_custom_field_definition_id_from_string` | auto-creates via the `"namespace.key"` form |
+| `Spree::Imports::RowProcessors::ProductVariant` | definition lookup per CSV column |
+| `Api::V3::Admin::CustomFieldDefinitionsController` | store-scoped through `for_store`, no override needed |
+| `Spree::ProductTypeCustomFieldDefinition` | the join validates that both sides belong to one store |
+| `Spree::SellerRequirements::RequiredCustomFields` | definitions picked for a requirement come from the requirement's store |
### Backfill
-A rake task registered in the upgrade manifest, run post-`db:migrate`:
+`spree:upgrade:backfill_custom_field_definition_stores`, registered in the
+5.6→6.0 manifest, is the recovery path when the migration ran with no store
+present:
- Assign `store_id = Spree::Store.default.id` to every definition missing one.
-- Populate `filter_key` on rows still missing it, via `valid?` (which fires the
- callback) then `save!(validate: false)` so unrelated legacy data doesn't block
- the column backfill.
+- Populate `filter_key` on rows still missing it.
- Report and skip rows whose namespace/key pair collides with an
- already-backfilled row in the same store; only one can own the key. Operator
- renames one of each pair and re-runs. Idempotent.
-
-## Migration Path
-
-1. **5.x (additive):** add both columns nullable, add `has_many`/`belongs_to`,
- ship the backfill task in the upgrade manifest, switch every call site above
- to the association. `NULL store_id` rows keep working until backfilled.
-2. **6.0 (cleanup):** enforce `null: false` on `store_id` and `filter_key`, drop
- the `CONCAT` validation in favour of the plain uniqueness validation, and drop
- any global-row fallbacks.
+ already-backfilled row in the same store; only one can own the key. The
+ operator renames one of each pair and re-runs. Idempotent.
## Constraints on Current Work
-Until this lands:
-
-- **`filter_key` is a computed method**, not a column — don't add a Ransack
- predicate, an `order(:filter_key)`, or a `where(filter_key: …)` against it.
- Filter it in Ruby or match on `namespace`/`key`.
-- **Uniqueness is enforced by `filter_key_must_be_unique`**, a `CONCAT`-based
- validation. It's not backed by a DB index, so it can't hold under concurrent
- creates. Don't rely on it as a hard guarantee.
-- **Definitions are global.** Any new code reading them is reading every store's
- schema. Don't add features that assume per-store custom-field schemas.
-- Don't add a `for_store` scope to `MetafieldDefinition` — the `has_many` on
- Store is the intended mechanism.
+- **Never read `Spree::CustomFieldDefinition` unscoped.** Go through
+ `store.custom_field_definitions`. The table now carries a `store_id`, so
+ `Spree::StoreScopeGuard` watches it and an unscoped scan raises in the API
+ suite. A deliberately global lookup wraps in `Spree::StoreScopeGuard.skip { }`
+ and needs a reason.
+- **Don't add a `for_store` scope to `CustomFieldDefinition`** — the `has_many`
+ on Store is the mechanism, and `Spree::Base.for_store` already resolves through
+ it.
+- **CSV headers and values must come from one store's definitions.** They are
+ produced in different objects (`Spree::Export` and the record's `to_csv`); if
+ the two disagree about the store the columns silently misalign.
+- **`filter_key` is derived, never client-writable.** It is set by the callback
+ from `namespace` and `key`; the Admin API does not permit it.
+- **A definition's store is immutable** once set (`SingleStoreResource`'s guard).
+ Moving a definition between stores would orphan every value pointing at it.
## Open Questions
-- Should existing installations get one definition set per store (copy the
- default store's schema to each store) or keep a single set on the default
- store? The backfill above assumes the latter; copying may surprise
- multi-store operators either way.
-- Does `spree_multi_store` want to keep sharing definitions across stores, the
- way it does for promotions and payment methods? If so the sharing bridge
- belongs in that extension, not core.
-- `Spree::Metafield` rows point at a definition, so a definition's store is
- implied by its resource. Worth validating that a metafield's resource and its
- definition agree on the store, or is that over-constraining?
+None — the three that stood were settled 2026-09-02 (see Key Decisions).
+
+`spree_multi_store` may still want to share definitions across stores the way it
+does for promotions and payment methods. If so the sharing bridge belongs in that
+extension, not core.
## References
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 8ecded6e0e..0072716213 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -6,6 +6,18 @@
**Consequences:** No `source_digest` column, no `stale` key, no `?include=staleness`. The matrix keeps its flat `{ field → value }` shape and `translated_field_count` stays the only completeness signal. Nothing forecloses a revival: two findings from the cut are recorded in the plan for whoever picks it up — a shared polymorphic digest table beats a column per `*_translations` table (per-field rather than per-row granularity, and future registry members need no migration), and the flag stays advisory, never required on write. Revisit when merchants using the coverage page report source drift as an actual complaint.
+## 2026-09-02: Custom field definitions become store-owned, with a persisted filter_key
+
+**Context:** `Spree::CustomFieldDefinition` (formerly `MetafieldDefinition`) was the last piece of merchant-facing schema with no owner. Every store in an installation shared one set of definitions, and the admin endpoint had no `scope` override, so any store's staff read and edited every other store's custom-field schema. Alongside it, `filter_key` — the `cf_<namespace>_<key>` identifier the product listing sorts and filters on — was computed in Ruby on every call, which left its uniqueness resting on a `CONCAT`-based validation with no index behind it. Both were deferred out of the 5.6 search/sort/filter work because they are schema changes and that shipped as a patch release.
+
+**Decision:** The definition becomes a `Spree::SingleStoreResource` with a persisted `filter_key`, and uniqueness becomes `(store_id, resource_type, filter_key)` behind a real unique index. Three sub-rulings settled today:
+
+1. **Existing definitions all move to the default store.** No per-store copies. Copying would have produced N duplicate rows whose values still pointed at the originals, so every non-default store would show the same blank fields it shows under the simpler backfill — at N times the rows and with a re-pointing pass over `spree_custom_fields` to write. Multi-store operators re-create the fields they want on their other stores.
+2. **The migration backfills and enforces NOT NULL itself**, with `spree:upgrade:backfill_custom_field_definition_stores` in the 5.6→6.0 manifest as the recovery path for installs that migrated before any store existed. This follows the return/refund reason precedent shipped earlier in 6.0 and closes the window the plan's original two-phase path left open: a nullable scope column voids the unique index outright, because SQL treats NULLs as distinct, so uniqueness would look enforced while not holding.
+3. **A custom field's value is validated to agree with its definition's store** (revised during implementation). The original ruling was that resolution is store-scoped at every path, making a validation redundant — that turned out to be false. `custom_fields=` routes through the store-scoped resolver, but Rails' own `accepts_nested_attributes_for` writer assigns `custom_field_definition_id` straight onto the row and reaches no resolver at all, so a foreign definition was accepted through the nested path. The validation now sits on `Spree::CustomField`, beside the `resource_type` agreement check that was already there for the same reason, and it is the one gate every write path passes. It skips resources with no store of their own (a customer, an address are global), which is the partial-guarantee objection from the original ruling — but a partial guarantee at the convergence point beats none, and the skipped types were resolved within a store on the way in.
+
+**Consequences:** `store.custom_field_definitions` is the reading mechanism — no `for_store` scope of its own, and no unscoped `Spree::CustomFieldDefinition` reads anywhere (the store-scope tripwire now watches the table). `filter_key` is a real column: it can be selected, indexed and ordered on, and the `CONCAT` validation is gone. `Spree::SearchProvider::CustomFieldSchema` takes the store it describes, so two stores no longer share one filter vocabulary. CSV header and value rows must be produced from the same store's definitions or they misalign.
+
## 2026-09-01: Seller delivery — the marketplace owns the profiles, the seller owns their methods
**Context:** `6.0-multi-vendor-marketplace.md` had promised `DeliveryMethod#seller_id` since 2026-08-15 without ever designing it, and the shipped code went the other way: every delivery record is store-scoped, the estimator knows nothing about sellers, a seller's only delivery lever is where their stock sits, and `Carts::SplitBySeller#divide_delivery_cost` apportions one quote after payment. Meanwhile the seller branch had taken product type and delivery profile off the product form (2026-08-26), so every seller product landed on the store's default profile. The legacy multi-vendor module owned methods per vendor and kept zones and categories global; of the two marketplace platforms studied, one lets sellers build the whole shipping tree themselves and the other keeps an operator vocabulary the seller prices within.
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb
index e3921665b6..77b084be19 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb
@@ -181,6 +181,52 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldDefinitionsController, type: :c
end
end
+ # Definitions are store-owned, so another store's schema is not readable,
+ # editable or deletable through this endpoint — a cross-store id is simply
+ # not found.
+ describe 'store isolation' do
+ let!(:other_store_definition) do
+ create(:custom_field_definition, store: create(:store), namespace: 'specs', key: 'supplier')
+ end
+
+ it 'omits another store\'s definitions from the listing' do
+ get :index, as: :json
+
+ keys = json_response['data'].map { |definition| definition['key'] }
+ expect(keys).to include('fabric')
+ expect(keys).not_to include('supplier')
+ end
+
+ it 'does not find another store\'s definition' do
+ get :show, params: { id: other_store_definition.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'refuses to update another store\'s definition' do
+ patch :update, params: { id: other_store_definition.prefixed_id, label: 'Taken' }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(other_store_definition.reload.label).not_to eq('Taken')
+ end
+
+ it 'refuses to destroy another store\'s definition' do
+ delete :destroy, params: { id: other_store_definition.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(other_store_definition.reload).to be_present
+ end
+
+ it 'builds a created definition on the requesting store' do
+ post :create,
+ params: { namespace: 'specs', key: 'weave', field_type: 'short_text', resource_type: 'Spree::Product' },
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(store.custom_field_definitions.find_by(key: 'weave')).to be_present
+ end
+ end
+
describe 'API key scope enforcement' do
let(:api_key) { create(:api_key, :secret, store: store, scopes: [granted_scope]) }
let(:api_key_headers) { { 'x-spree-api-key' => api_key.plaintext_token } }
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb
index d80b312798..4bc5b227cb 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb
@@ -168,8 +168,13 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
describe 'cross-store IDOR — a product in another store' do
let(:other_store) { create(:store) }
let(:other_product) { create(:product, store: other_store) }
+ # The other store's own definition: a record may only carry one from the
+ # store that owns it, so this is the only shape the row can take.
+ let(:other_store_definition) do
+ create(:custom_field_definition, :short_text_field, store: other_store)
+ end
let!(:foreign_field) do
- create(:custom_field, resource: other_product, custom_field_definition: short_text_definition, value: 'secret')
+ create(:custom_field, resource: other_product, custom_field_definition: other_store_definition, value: 'secret')
end
it 'does not list custom fields of another store\'s product' do
diff --git a/spree/core/app/jobs/spree/images/save_from_url_job.rb b/spree/core/app/jobs/spree/images/save_from_url_job.rb
index 85263863c5..33367343f2 100644
--- a/spree/core/app/jobs/spree/images/save_from_url_job.rb
+++ b/spree/core/app/jobs/spree/images/save_from_url_job.rb
@@ -28,7 +28,12 @@ module Spree
def perform(viewable_id, viewable_type, external_url, external_id = nil, position = nil, link_variant_id = nil)
viewable = viewable_type.safe_constantize.find(viewable_id)
- Spree::Media.ensure_custom_field_definition_exists!(Spree::Media::EXTERNAL_URL_CUSTOM_FIELD_KEY)
+ # The viewable's own store, not the current one: a job runs outside a
+ # request, where `Spree::Current.store` answers with the default store
+ # and would file every store's external-url definition on that one.
+ Spree::Media.ensure_custom_field_definition_exists!(
+ Spree::Media::EXTERNAL_URL_CUSTOM_FIELD_KEY, store: store_for(viewable)
+ )
external_url = external_url.strip
references = external_references_from(external_id)
@@ -60,6 +65,14 @@ module Spree
private
+ # Mirrors how Spree::Media picks its own store: the viewable's, or its
+ # product's for a variant.
+ #
+ # @return [Spree::Store]
+ def store_for(viewable)
+ viewable.try(:store) || viewable.try(:product)&.store || Spree::Store.default
+ end
+
def download_and_attach_image(external_url, image)
max_size = Spree::Config.max_image_download_size
diff --git a/spree/core/app/models/concerns/spree/custom_field_filterable.rb b/spree/core/app/models/concerns/spree/custom_field_filterable.rb
index 4f014cb1cd..c113a7ac71 100644
--- a/spree/core/app/models/concerns/spree/custom_field_filterable.rb
+++ b/spree/core/app/models/concerns/spree/custom_field_filterable.rb
@@ -35,15 +35,16 @@ module Spree
# "no filter" instead of a 500.
#
# @param filters [Hash]
- # @param schema [Spree::SearchProvider::CustomFieldSchema, nil]
+ # @param schema [Spree::SearchProvider::CustomFieldSchema] the store's
+ # custom-field vocabulary; definitions are store-owned, so filtering
+ # without one would read another store's schema.
# @return [Array(ActiveRecord::Relation, Hash)] scoped relation + remaining filters
- def with_custom_field_filters(filters, schema: nil)
+ def with_custom_field_filters(filters, schema:)
return [all, filters] if filters.blank?
# Skip the schema's DB query entirely for the common case of a filter
# hash with no custom-field predicates at all.
return [all, filters] unless filters.any? { |key, _| key.to_s.start_with?('cf_') }
- schema ||= Spree::SearchProvider::CustomFieldSchema.new
scope = all
remaining = filters.reject do |key, value|
diff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rb
index 06adf7d28f..d8116e36bd 100644
--- a/spree/core/app/models/concerns/spree/customer_methods.rb
+++ b/spree/core/app/models/concerns/spree/customer_methods.rb
@@ -288,10 +288,13 @@ module Spree
end
# Returns the CSV row representation of the user
- # @param [Spree::Store] store
# @return [Array<String>]
- def to_csv(_store = nil)
- Spree::CSV::CustomerPresenter.new(self).call
+ # @param store [Spree::Store, nil] the store the export runs for — it
+ # decides which custom-field definitions the value columns are built
+ # from. Customers are global, so unlike a store-owned record there is
+ # nothing to fall back to but the current request's store.
+ def to_csv(store = nil)
+ Spree::CSV::CustomerPresenter.new(self, store || Spree::Current.store).call
end
# Returns the full name of the user
diff --git a/spree/core/app/models/concerns/spree/has_custom_fields.rb b/spree/core/app/models/concerns/spree/has_custom_fields.rb
index 63eb0e749c..be6a2a8539 100644
--- a/spree/core/app/models/concerns/spree/has_custom_fields.rb
+++ b/spree/core/app/models/concerns/spree/has_custom_fields.rb
@@ -3,9 +3,17 @@ module Spree
extend ActiveSupport::Concern
module ClassMethods
- def ensure_custom_field_definition_exists!(key_with_namespace)
+ # @param key_with_namespace [String] the dotted `"namespace.key"` form
+ # @param store [Spree::Store, nil] the store the definition belongs to;
+ # defaults to the current request's store, since definitions are
+ # store-owned and there is no global schema to fall back on.
+ def ensure_custom_field_definition_exists!(key_with_namespace, store: Spree::Current.store)
namespace, key = extract_namespace_and_key(key_with_namespace)
- Spree::CustomFieldDefinition.find_or_create_by!(namespace: namespace, key: key, resource_type: self.name)
+ raise ArgumentError, 'a store is required to create a custom field definition' if store.nil?
+
+ store.custom_field_definitions.find_or_create_by!(
+ namespace: namespace, key: key, resource_type: self.name
+ )
end
def extract_namespace_and_key(key_with_namespace)
@@ -15,9 +23,9 @@ module Spree
end
# Deprecated 6.0 names, removed in 6.1.
- def ensure_metafield_definition_exists!(key_with_namespace)
+ def ensure_metafield_definition_exists!(key_with_namespace, store: Spree::Current.store)
Spree::Deprecation.warn('ensure_metafield_definition_exists! is deprecated and will be removed in Spree 6.1. Use ensure_custom_field_definition_exists! instead.')
- ensure_custom_field_definition_exists!(key_with_namespace)
+ ensure_custom_field_definition_exists!(key_with_namespace, store: store)
end
def with_metafield_key(key_with_namespace)
@@ -252,16 +260,27 @@ module Spree
# Resolve any of the supported reference shapes to a raw definition id.
# See {#set_custom_field} for the accepted shapes.
#
+ # Every shape is checked against this record's store: definitions are
+ # store-owned, so one store's record must not end up carrying another
+ # store's definition whichever way the caller names it.
+ #
# @param definition_or_key [String, Integer, Spree::CustomFieldDefinition]
# @return [Integer, String] the definition's primary key value (Integer
# for legacy integer-id setups, String for UUID setups).
- # @raise [ArgumentError] for unknown / malformed input.
+ # @raise [ArgumentError] for unknown / malformed input, or a definition
+ # belonging to another store.
def resolve_custom_field_definition_id(definition_or_key)
case definition_or_key
when Spree::CustomFieldDefinition
+ # A loaded record already carries its store, so compare in memory
+ # rather than paying a lookup to learn what is in hand.
+ unless definition_or_key.store_id == custom_field_definition_store.id
+ raise ArgumentError, "Unknown custom field definition id: #{definition_or_key.full_key.inspect}"
+ end
+
definition_or_key.id
when Integer
- definition_or_key
+ find_definition_id_in_store!(definition_or_key, definition_or_key)
when String
resolve_custom_field_definition_id_from_string(definition_or_key)
else
@@ -278,32 +297,63 @@ module Spree
# auto-create the definition if missing.
if value.include?('.')
namespace, key = extract_namespace_and_key(value)
- return Spree::CustomFieldDefinition.find_or_create_by!(
+ return custom_field_definition_store.custom_field_definitions.find_or_create_by!(
namespace: namespace, key: key, resource_type: self.class.name
).id
end
# Prefixed id (`"cfdef_..."`/`"mfd_..."`). Use the canonical predicate
# so single-segment names with underscores (e.g. `"product_specs"`)
- # don't get mistaken for prefixed ids. We must verify the decoded id
- # actually exists — Sqids will happily decode any all-lowercase
- # alphanumeric string to a phantom integer; without the existence
- # check `find_or_initialize_by(custom_field_definition_id: phantom_id)`
- # would later raise a confusing "CustomField definition must exist"
- # 422 instead of an "unknown id" 422.
+ # don't get mistaken for prefixed ids.
+ #
+ # Both id shapes are resolved through the store rather than the class.
+ # That is what stops one store's record carrying another store's
+ # definition, and it also covers the phantom-id case: Sqids will
+ # happily decode any all-lowercase alphanumeric string to an integer
+ # that matches no row, and without the existence check
+ # `find_or_initialize_by(custom_field_definition_id: phantom_id)` would
+ # later raise a confusing "CustomField definition must exist" 422
+ # instead of an "unknown id" one.
if Spree::PrefixedId.prefixed_id?(value)
decoded = Spree::CustomFieldDefinition.decode_prefixed_id(value)
- existing = decoded && Spree::CustomFieldDefinition.find_by(id: decoded)
- raise ArgumentError, "Unknown custom field definition id: #{value.inspect}" if existing.nil?
-
- return existing.id
+ return find_definition_id_in_store!(decoded, value)
end
- # Bare numeric id ("42"). Reject anything else outright. Returned as
- # the original string — casting would rewrite zero-padded ids.
+ # Bare numeric id ("42"). Reject anything else outright.
raise ArgumentError, "Invalid custom field definition reference: #{value.inspect}" unless /\A\d+\z/.match?(value)
- value
+ find_definition_id_in_store!(value, value)
+ end
+
+ # @param id [Integer, String, nil] the decoded primary key
+ # @param reference [String] what the caller passed, for the error message
+ # @return [Integer, String] the definition's own primary key value
+ # @raise [ArgumentError] when this store has no such definition.
+ def find_definition_id_in_store!(id, reference)
+ definition = id && custom_field_definition_store.custom_field_definitions.find_by(id: id)
+ raise ArgumentError, "Unknown custom field definition id: #{reference.inspect}" if definition.nil?
+
+ definition.id
+ end
+
+ # The store whose custom-field schema this record's fields are defined
+ # in. A record that owns a store answers with it; one that reaches a
+ # store through its owner overrides this (see Spree::Payment,
+ # Spree::Variant); the genuinely global records — a customer, an
+ # address — fall through to the current request's store, since their
+ # fields still belong to one.
+ #
+ # Override rather than extending a chain here: which owner holds the
+ # store is the host's own fact, and a chain of `try`s silently answers
+ # for the wrong one when a host matches none of its steps.
+ #
+ # @return [Spree::Store]
+ # @raise [ArgumentError] when none is available.
+ def custom_field_definition_store
+ store = try(:store) || Spree::Current.store
+ raise ArgumentError, 'a store is required to resolve a custom field definition' if store.nil?
+
+ store
end
end
end
diff --git a/spree/core/app/models/spree/custom_field.rb b/spree/core/app/models/spree/custom_field.rb
index 45a015de80..9d301dcf70 100644
--- a/spree/core/app/models/spree/custom_field.rb
+++ b/spree/core/app/models/spree/custom_field.rb
@@ -67,6 +67,7 @@ module Spree
validates :custom_field_definition_id, uniqueness: { scope: [:resource_type, :resource_id] }
validate :type_must_match_custom_field_definition
validate :resource_type_must_match_custom_field_definition
+ validate :custom_field_definition_must_belong_to_the_resource_store
#
# Scopes
@@ -141,5 +142,17 @@ module Spree
errors.add(:resource_type, 'must match custom field definition')
end
+
+ # Definitions are store-owned, so a record may only carry its own store's.
+ # Rails' `custom_fields_attributes=` assigns the id straight onto the row
+ # without passing the store-scoped resolver, so this is what covers it.
+ # A global resource — a customer, an address — has no store_id and is
+ # skipped: it can carry a field defined by any store it deals with.
+ def custom_field_definition_must_belong_to_the_resource_store
+ return if custom_field_definition.blank? || resource.try(:store_id).blank?
+ return if custom_field_definition.store_id == resource.store_id
+
+ errors.add(:custom_field_definition, :must_belong_to_same_store)
+ end
end
end
diff --git a/spree/core/app/models/spree/custom_field_definition.rb b/spree/core/app/models/spree/custom_field_definition.rb
index 3a4250f947..42d030e20f 100644
--- a/spree/core/app/models/spree/custom_field_definition.rb
+++ b/spree/core/app/models/spree/custom_field_definition.rb
@@ -2,6 +2,7 @@ module Spree
class CustomFieldDefinition < Spree.base_class
has_prefix_id :cfdef
+ include Spree::SingleStoreResource
include Spree::CustomFieldDefinition::SearchCapabilities
#
@@ -14,7 +15,7 @@ module Spree
#
validates :namespace, :key, :label, :resource_type, presence: true
validates :resource_type, presence: true, inclusion: { in: :valid_available_resources }
- validates :key, uniqueness: { scope: spree_base_uniqueness_scope + [:resource_type, :namespace] }
+ validates :key, uniqueness: { scope: spree_base_uniqueness_scope + [:store_id, :resource_type, :namespace] }
validate :field_type_input_must_be_recognized
validate :field_type_must_be_available
@@ -42,6 +43,7 @@ module Spree
normalizes :namespace, with: ->(value) { value.to_s.parameterize.underscore.strip }
before_validation :set_default_type, if: -> { self[:field_type].blank? }, on: :create
before_validation :set_label_from_key, if: -> { label.blank? }, on: :create
+ before_validation :set_filter_key
#
# Ransack
@@ -200,5 +202,19 @@ module Spree
def set_label_from_key
self.label ||= key.titleize
end
+
+ # Kept in step with namespace and key, so renaming either moves the
+ # sort/filter identifier with it rather than leaving a stale one that no
+ # listing can address.
+ #
+ # A stored value is left alone while both segments stay put. Two splits can
+ # flatten to one key, and the upgrade migration resolves such a pair by
+ # suffixing the later row; recomputing on an unrelated edit would undo that
+ # and leave the row permanently unsaveable.
+ def set_filter_key
+ return if self[:filter_key].present? && !namespace_changed? && !key_changed?
+
+ self.filter_key = computed_filter_key
+ end
end
end
diff --git a/spree/core/app/models/spree/custom_field_definition/search_capabilities.rb b/spree/core/app/models/spree/custom_field_definition/search_capabilities.rb
index 2fe03d41f1..e67cf6d09e 100644
--- a/spree/core/app/models/spree/custom_field_definition/search_capabilities.rb
+++ b/spree/core/app/models/spree/custom_field_definition/search_capabilities.rb
@@ -10,7 +10,13 @@ module Spree
attribute :sortable, :boolean, default: false
validate :search_sort_capabilities_compatible_with_type
- validate :filter_key_must_be_unique
+
+ # `key` is already unique per (store, resource_type, namespace), but
+ # both segments normalize to underscored slugs, so two different splits
+ # ("a_b"/"c" vs "a"/"b_c") flatten to one filter_key — which would make
+ # one of them unaddressable as a sort/filter param.
+ validates :filter_key, uniqueness: { scope: spree_base_uniqueness_scope + [:store_id, :resource_type] },
+ allow_blank: true
scope :searchable, -> { where(searchable: true) }
scope :sortable, -> { where(sortable: true) }
@@ -42,35 +48,23 @@ module Spree
# Public identifier for sorting and filtering product listings by this
# custom field (+sort=cf_specs_material+,
- # +q[cf_specs_material_i_cont]=wool+).
+ # +q[cf_specs_material_i_cont]=wool+). Persisted, so it can be selected,
+ # indexed and ordered on; the computed form answers for a record whose
+ # callback has not run yet.
#
# @return [String] e.g. +cf_custom_label+
def filter_key
- "cf_#{namespace}_#{key}"
+ self[:filter_key].presence || computed_filter_key
end
private
- # `key` is already unique per (resource_type, namespace), but both
- # segments normalize to underscored slugs, so two different splits
- # ("a_b"/"c" vs "a"/"b_c") flatten to one filter_key — which would make
- # one of them unaddressable as a sort/filter param.
- def filter_key_must_be_unique
- return if namespace.blank? || key.blank? || resource_type.blank?
- return unless new_record? || namespace_changed? || key_changed? || resource_type_changed?
-
- table = self.class.arel_table
- concatenated = Arel::Nodes::NamedFunction.new(
- 'CONCAT', [table[:namespace], Arel::Nodes.build_quoted('_'), table[:key]]
- )
-
- scope = self.class.
- for_resource_type(resource_type).
- where(concatenated.eq("#{namespace}_#{key}")).
- where(self.class.spree_base_uniqueness_scope.index_with { |attr| public_send(attr) })
- scope = scope.where.not(id: id) if persisted?
-
- errors.add(:key, :taken) if scope.exists?
+ # @return [String, nil] nil while either segment is still blank, so a
+ # half-filled record does not persist a meaningless +cf__+.
+ def computed_filter_key
+ return if namespace.blank? || key.blank?
+
+ "cf_#{namespace}_#{key}"
end
def field_type_class
diff --git a/spree/core/app/models/spree/export.rb b/spree/core/app/models/spree/export.rb
index 06b17bee1a..dd430cc529 100644
--- a/spree/core/app/models/spree/export.rb
+++ b/spree/core/app/models/spree/export.rb
@@ -114,8 +114,15 @@ module Spree
end
def generate
- send(:"generate_#{format}")
- handle_attachment
+ # An export runs in a job, where nothing has named a store. Scopes that
+ # read the current one — the product search's custom-field arm, address
+ # validation — would otherwise answer for the default store rather than
+ # the one whose records are being exported.
+ Spree::Current.set(store: store) do
+ send(:"generate_#{format}")
+ handle_attachment
+ end
+
send_export_done_email
end
@@ -157,7 +164,8 @@ module Spree
#
# @return [Array<String>]
def custom_fields_headers
- @custom_fields_headers ||= Spree::CustomFieldDefinition.for_resource_type(model_class.to_s).order(:namespace, :key).map(&:csv_header_name)
+ @custom_fields_headers ||= store.custom_field_definitions.for_resource_type(model_class.to_s).
+ order(:namespace, :key).map(&:csv_header_name)
end
def build_csv_line(_record)
@@ -205,7 +213,9 @@ module Spree
# `cf_*` custom-field predicates aren't Ransack attributes — resolve them
# first so an export of a filtered list matches what the admin sees.
filtered_scope, params = if scope.respond_to?(:with_custom_field_filters)
- scope.with_custom_field_filters(params)
+ scope.with_custom_field_filters(
+ params, schema: Spree::SearchProvider::CustomFieldSchema.new(store)
+ )
else
[scope, params]
end
diff --git a/spree/core/app/models/spree/gift_card.rb b/spree/core/app/models/spree/gift_card.rb
index 5023e778de..3e51f8d97c 100644
--- a/spree/core/app/models/spree/gift_card.rb
+++ b/spree/core/app/models/spree/gift_card.rb
@@ -168,8 +168,8 @@ module Spree
run_gift_card_workflow(Spree.gift_card_cancel_workflow)
end
- def to_csv(_store = nil)
- Spree::CSV::GiftCardPresenter.new(self).call
+ def to_csv(store = nil)
+ Spree::CSV::GiftCardPresenter.new(self, store || self.store).call
end
private
diff --git a/spree/core/app/models/spree/import.rb b/spree/core/app/models/spree/import.rb
index b38dadf04b..0631dc6a97 100644
--- a/spree/core/app/models/spree/import.rb
+++ b/spree/core/app/models/spree/import.rb
@@ -524,7 +524,9 @@ module Spree
def custom_field_definitions_for_model
return [] unless model_class.present?
- Spree::CustomFieldDefinition.for_resource_type(model_class.name)
+ # `store` is assigned at before_validation, so the unsaved import the
+ # template CSV is built on has none yet.
+ (store || Spree::Current.store).custom_field_definitions.for_resource_type(model_class.name)
end
end
end
diff --git a/spree/core/app/models/spree/media.rb b/spree/core/app/models/spree/media.rb
index aa942d7cf3..1f480c8829 100644
--- a/spree/core/app/models/spree/media.rb
+++ b/spree/core/app/models/spree/media.rb
@@ -292,6 +292,14 @@ module Spree
set_custom_field(EXTERNAL_URL_CUSTOM_FIELD_KEY, url.strip)
end
+ # An image is given its external URL before it is saved, so `store_id` is
+ # still unset at that point. Run the callback that fills it early rather
+ # than repeating how it picks the owner.
+ def custom_field_definition_store
+ ensure_store unless store_id?
+ store || Spree::Current.store
+ end
+
# Places a copy of this file on another product or variant, sharing the
# blob rather than copying the file. The copy is an ordinary new row, so it
# carries its own position, variant links and list placement in the new
diff --git a/spree/core/app/models/spree/newsletter_subscriber.rb b/spree/core/app/models/spree/newsletter_subscriber.rb
index 9f6806fe13..4f4c2d0ac4 100644
--- a/spree/core/app/models/spree/newsletter_subscriber.rb
+++ b/spree/core/app/models/spree/newsletter_subscriber.rb
@@ -56,8 +56,8 @@ module Spree
verified_at.present?
end
- def to_csv(_store = nil)
- Spree::CSV::NewsletterSubscriberPresenter.new(self).call
+ def to_csv(store = nil)
+ Spree::CSV::NewsletterSubscriberPresenter.new(self, store || self.store).call
end
def self.subscribe(email:, customer: nil, store: nil, redirect_url: nil)
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index eec3936c38..ad6ba4b6e6 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -1,6 +1,7 @@
module Spree
class Order < Spree.base_class
+ include Spree::CSV::CustomFieldsHelper
has_prefix_id :or # Stripe: or_
# Legacy free-text `channel` column was replaced by the `channel_id` FK
@@ -1074,15 +1075,17 @@ module Spree
# @param omit_headers [Array<String>] columns to leave out, named by their
# header. A seller's export drops the buyer's email this way — see
# Spree::Exports::Orders.
- def to_csv(_store = nil, omit_headers: [])
- custom_fields_for_csv ||= Spree::CustomFieldDefinition.for_resource_type('Spree::Order').order(:namespace, :key).map do |mf_def|
- custom_fields.find { |mf| mf.custom_field_definition_id == mf_def.id }&.csv_value
- end
+ def to_csv(store = nil, omit_headers: [])
+ store ||= self.store
+ # Through the shared helper so the value row is built from exactly the
+ # definitions, in exactly the order, that Export#custom_fields_headers
+ # used for the header row — a mismatch shifts every value column.
+ custom_field_values = custom_fields_for_csv(self, store)
csv_lines = []
line_items.each_with_index do |line_item, index|
csv_lines << Spree::CSV::OrderLineItemPresenter.new(
- self, line_item, index, custom_fields_for_csv, omit_headers: omit_headers
+ self, line_item, index, custom_field_values, omit_headers: omit_headers
).call
end
csv_lines
diff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rb
index 7d20eb9a47..42eebec334 100644
--- a/spree/core/app/models/spree/payment.rb
+++ b/spree/core/app/models/spree/payment.rb
@@ -108,7 +108,7 @@ module Spree
# transaction_id is much easier to understand
alias_attribute :transaction_id, :response_code
- delegate :currency, to: :owner
+ delegate :currency, :store, to: :owner
money_methods :amount, :credit_allowed
alias money display_amount # for compatibility with older versions of Spree
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index a7de44d29d..5934ecdf55 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -14,6 +14,8 @@
module Spree
class Product < Spree.base_class
+ include Spree::CSV::CustomFieldsHelper
+
has_prefix_id :prod # Stripe: prod_
acts_as_paranoid
@@ -273,12 +275,16 @@ module Spree
where("#{Spree::Price.table_name}.compare_at_amount > #{Spree::Price.table_name}.amount")
}
- scope :search, ->(query) {
+ # @param store [Spree::Store] whose custom-field definitions take part in
+ # the search. Definitions are store-owned, so the caller says which store
+ # is searching; `Spree::Current.store` is the request's answer and a
+ # background caller (an export, say) passes its own.
+ scope :search, ->(query, store = Spree::Current.store) {
next none if query.blank?
product_ids = Spree::Variant.search_by_product_name_or_sku(query).pluck(:product_id)
- searchable_definitions = Spree::CustomFieldDefinition.
+ searchable_definitions = store.custom_field_definitions.
for_resource_type('Spree::Product').
searchable
@@ -799,9 +805,10 @@ module Spree
else
[]
end
- custom_fields_for_csv ||= Spree::CustomFieldDefinition.for_resource_type('Spree::Product').order(:namespace, :key).map do |mf_def|
- custom_fields.find { |mf| mf.custom_field_definition_id == mf_def.id }&.csv_value
- end
+ # Through the shared helper so the value row is built from exactly the
+ # definitions, in exactly the order, that Export#custom_fields_headers
+ # used for the header row — a mismatch shifts every value column.
+ custom_field_values = custom_fields_for_csv(self, store)
categories_for_csv ||= categories.reorder(depth: :desc).first(3).pluck(:pretty_name)
categories_for_csv.fill(nil, categories_for_csv.size...3)
@@ -813,7 +820,7 @@ module Spree
# Primary rows in the store's default currency
all_variants.each_with_index do |variant, index|
csv_lines << Spree::CSV::ProductVariantPresenter.new(self, variant, index, properties_for_csv, categories_for_csv, store,
- custom_fields_for_csv).call
+ custom_field_values).call
end
# Price-only rows for each additional currency
diff --git a/spree/core/app/models/spree/product_type.rb b/spree/core/app/models/spree/product_type.rb
index cab507e342..e9e79ad2fa 100644
--- a/spree/core/app/models/spree/product_type.rb
+++ b/spree/core/app/models/spree/product_type.rb
@@ -74,8 +74,11 @@ module Spree
rows = @pending_custom_field_definitions
@pending_custom_field_definitions = nil
+ # Resolved through the type's own store: definitions are store-owned, so
+ # another store's id is unknown here rather than a join that fails
+ # silently on save.
resolved = rows.map do |row|
- [Spree::CustomFieldDefinition.find_by_prefix_id(row[:id]), row]
+ [store.custom_field_definitions.find_by_prefix_id(row[:id]), row]
end
# Validate the whole payload before touching anything. This runs inside
diff --git a/spree/core/app/models/spree/product_type_custom_field_definition.rb b/spree/core/app/models/spree/product_type_custom_field_definition.rb
index 9f8a24507d..17ba2c0466 100644
--- a/spree/core/app/models/spree/product_type_custom_field_definition.rb
+++ b/spree/core/app/models/spree/product_type_custom_field_definition.rb
@@ -6,12 +6,11 @@ module Spree
# docs/plans/decisions.md). Read live by reference; no values are copied.
class ProductTypeCustomFieldDefinition < Spree.base_class
belongs_to :product_type, class_name: 'Spree::ProductType'
- # Association and column carry the 6.0 custom-field vocabulary; the class is
- # still named CustomFieldDefinition until the rename wave lands.
belongs_to :custom_field_definition, class_name: 'Spree::CustomFieldDefinition'
validates :custom_field_definition_id, uniqueness: { scope: :product_type_id }
validate :custom_field_definition_applies_to_products
+ validate :custom_field_definition_belongs_to_same_store
scope :required, -> { where(required: true) }
scope :ordered, -> { order(:sort_order, :id) }
@@ -26,5 +25,15 @@ module Spree
errors.add(:custom_field_definition, :must_apply_to_products)
end
+
+ # Both sides are store-owned, so a type may only use its own store's
+ # definitions — one from another store would render a field the product
+ # form can never save.
+ def custom_field_definition_belongs_to_same_store
+ return if custom_field_definition.blank? || product_type.blank?
+ return if custom_field_definition.store_id == product_type.store_id
+
+ errors.add(:custom_field_definition, :must_belong_to_same_store)
+ end
end
end
diff --git a/spree/core/app/models/spree/search_provider/base.rb b/spree/core/app/models/spree/search_provider/base.rb
index b8c188e689..0cc6ee6c6b 100644
--- a/spree/core/app/models/spree/search_provider/base.rb
+++ b/spree/core/app/models/spree/search_provider/base.rb
@@ -15,7 +15,7 @@ module Spree
# @return [CustomFieldSchema]
def custom_field_schema
- @custom_field_schema ||= CustomFieldSchema.new
+ @custom_field_schema ||= CustomFieldSchema.new(store)
end
# Deprecated 6.0 name, removed in 6.1.
diff --git a/spree/core/app/models/spree/search_provider/database.rb b/spree/core/app/models/spree/search_provider/database.rb
index fffac3a8db..10a67366db 100644
--- a/spree/core/app/models/spree/search_provider/database.rb
+++ b/spree/core/app/models/spree/search_provider/database.rb
@@ -65,7 +65,7 @@ module Spree
private
def apply_search_and_filters(scope, query: nil, filters: {})
- scope = scope.search(query) if query.present?
+ scope = scope.search(query, store) if query.present?
filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
scope, filters = scope.with_custom_field_filters(filters, schema: custom_field_schema)
diff --git a/spree/core/app/models/spree/seller_requirement_custom_field.rb b/spree/core/app/models/spree/seller_requirement_custom_field.rb
index 4b8e07caea..ae3fd9561f 100644
--- a/spree/core/app/models/spree/seller_requirement_custom_field.rb
+++ b/spree/core/app/models/spree/seller_requirement_custom_field.rb
@@ -11,6 +11,7 @@ module Spree
validates :custom_field_definition_id, uniqueness: { scope: :seller_requirement_id }, allow_nil: true
validate :definition_must_describe_a_seller
+ validate :definition_must_belong_to_the_same_store
private
@@ -24,5 +25,14 @@ module Spree
message: Spree.t('seller_requirements.custom_field_not_for_sellers',
default: 'must be a custom field defined for sellers'))
end
+
+ # Both sides are store-owned, so a marketplace can only ask its sellers
+ # for fields it defined itself.
+ def definition_must_belong_to_the_same_store
+ return if custom_field_definition.nil? || seller_requirement.nil?
+ return if custom_field_definition.store_id == seller_requirement.store_id
+
+ errors.add(:custom_field_definition, :must_belong_to_same_store)
+ end
end
end
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index f153039c14..043520206d 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -203,6 +203,11 @@ module Spree
# store's types out from under its products would contradict that guard.
has_many :product_types, class_name: 'Spree::ProductType', dependent: :restrict_with_error
+ # The store's custom-field schema. Destroying a definition takes its values
+ # with it, which is a large fan-out on a busy store, so it runs in a job.
+ has_many :custom_field_definitions, class_name: 'Spree::CustomFieldDefinition',
+ inverse_of: :store, dependent: :destroy_async
+
# @deprecated Use #categories; removed in 6.1.
def taxons
Spree::Deprecation.warn('Spree::Store#taxons is deprecated and will be removed in Spree 6.1. Use #categories instead.')
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index e0b0a82626..8c71727230 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -35,7 +35,7 @@ module Spree
belongs_to :delivery_profile, class_name: 'Spree::DeliveryProfile', optional: true
delegate :name, :name=, :description, :slug, :available_on, :make_active_at, :product_type_id,
- :meta_description, :meta_keywords, :product_type, to: :product
+ :meta_description, :meta_keywords, :product_type, :store_id, to: :product
normalizes :sku, with: ->(value) { value&.to_s&.strip }
normalizes :hs_code, with: ->(value) { value&.to_s&.gsub(/[^0-9]/, '') }
diff --git a/spree/core/app/presenters/spree/csv/custom_fields_helper.rb b/spree/core/app/presenters/spree/csv/custom_fields_helper.rb
index 970f24faa2..79ac5b0089 100644
--- a/spree/core/app/presenters/spree/csv/custom_fields_helper.rb
+++ b/spree/core/app/presenters/spree/csv/custom_fields_helper.rb
@@ -3,13 +3,21 @@ module Spree
module CustomFieldsHelper
private
- def custom_field_definitions_for_csv(resource)
- Spree::CustomFieldDefinition.for_resource_type(resource.class.to_s).order(:namespace, :key)
+ # The store the export runs for decides the schema. Its header row comes
+ # from the same store's definitions, so reading any other store's here
+ # would shift every value column.
+ def custom_field_definitions_for_csv(resource, store)
+ # No store means no schema to read, so the row carries the base columns
+ # only — matching what the header row does in the same situation,
+ # rather than raising on nil halfway through a file.
+ return Spree::CustomFieldDefinition.none if store.nil?
+
+ store.custom_field_definitions.for_resource_type(resource.class.to_s).order(:namespace, :key)
end
- def custom_fields_for_csv(resource)
- Spree::CustomFieldDefinition.for_resource_type(resource.class.to_s).order(:namespace, :key).map do |mf_def|
- resource.custom_fields.find { |mf| mf.custom_field_definition_id == mf_def.id }&.csv_value
+ def custom_fields_for_csv(resource, store)
+ custom_field_definitions_for_csv(resource, store).map do |definition|
+ resource.custom_fields.find { |custom_field| custom_field.custom_field_definition_id == definition.id }&.csv_value
end
end
end
diff --git a/spree/core/app/presenters/spree/csv/customer_presenter.rb b/spree/core/app/presenters/spree/csv/customer_presenter.rb
index a56919a6e4..4c0c3fabf9 100644
--- a/spree/core/app/presenters/spree/csv/customer_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/customer_presenter.rb
@@ -23,11 +23,12 @@ module Spree
'Tags'
].freeze
- def initialize(customer)
+ def initialize(customer, store)
@customer = customer
+ @store = store
end
- attr_accessor :customer
+ attr_accessor :customer, :store
def call
csv = [
@@ -50,7 +51,7 @@ module Spree
customer.tag_list
]
- csv += custom_fields_for_csv(customer)
+ csv += custom_fields_for_csv(customer, store)
csv
end
diff --git a/spree/core/app/presenters/spree/csv/gift_card_presenter.rb b/spree/core/app/presenters/spree/csv/gift_card_presenter.rb
index 63cf1bf196..cd08d4dee8 100644
--- a/spree/core/app/presenters/spree/csv/gift_card_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/gift_card_presenter.rb
@@ -18,11 +18,12 @@ module Spree
'Updated At'
].freeze
- def initialize(gift_card)
+ def initialize(gift_card, store)
@gift_card = gift_card
+ @store = store
end
- attr_accessor :gift_card
+ attr_accessor :gift_card, :store
def call
csv = [
@@ -40,7 +41,7 @@ module Spree
gift_card.updated_at&.strftime('%Y-%m-%d %H:%M:%S')
]
- csv += custom_fields_for_csv(gift_card)
+ csv += custom_fields_for_csv(gift_card, store)
csv
end
diff --git a/spree/core/app/presenters/spree/csv/newsletter_subscriber_presenter.rb b/spree/core/app/presenters/spree/csv/newsletter_subscriber_presenter.rb
index 56b754ac34..246bd723fa 100644
--- a/spree/core/app/presenters/spree/csv/newsletter_subscriber_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/newsletter_subscriber_presenter.rb
@@ -13,11 +13,12 @@ module Spree
'Updated At'
].freeze
- def initialize(newsletter_subscriber)
+ def initialize(newsletter_subscriber, store)
@newsletter_subscriber = newsletter_subscriber
+ @store = store
end
- attr_accessor :newsletter_subscriber
+ attr_accessor :newsletter_subscriber, :store
def call
csv = [
@@ -30,7 +31,7 @@ module Spree
newsletter_subscriber.updated_at
]
- csv += custom_fields_for_csv(newsletter_subscriber)
+ csv += custom_fields_for_csv(newsletter_subscriber, store)
csv
end
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 af5a7044d4..34321ae648 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
@@ -363,7 +363,7 @@ module Spree
# Find or initialize custom_field definition
custom_field_definition = cached_lookup(:custom_field_definition, namespace, key, product.class.name) do
- Spree::CustomFieldDefinition.find_by(
+ store.custom_field_definitions.find_by(
namespace: namespace,
key: key,
resource_type: product.class.name
diff --git a/spree/core/app/services/spree/search_provider/custom_field_schema.rb b/spree/core/app/services/spree/search_provider/custom_field_schema.rb
index 886493a042..45be1d488d 100644
--- a/spree/core/app/services/spree/search_provider/custom_field_schema.rb
+++ b/spree/core/app/services/spree/search_provider/custom_field_schema.rb
@@ -15,6 +15,15 @@ module Spree
ORDERED_FILTER_PREDICATES = (TEXT_FILTER_PREDICATES | NUMBER_FILTER_PREDICATES).
sort_by { |predicate| -predicate.length }.freeze
+ attr_reader :store
+
+ # @param store [Spree::Store] the store whose custom-field schema this
+ # describes — definitions are store-owned, so two stores have their own
+ # filter vocabularies.
+ def initialize(store)
+ @store = store
+ end
+
# @return [Hash{String => Spree::CustomFieldDefinition}]
def entries
@entries ||= product_definitions.index_by(&:filter_key)
@@ -57,7 +66,7 @@ module Spree
def sort_options
@sort_options ||= entries.each_value.select(&:sortable?).flat_map do |definition|
key = definition.filter_key
- name = definition.name.presence || key
+ name = definition.label.presence || key
[
{ id: key, label: sort_option_label(name, definition.field_type, :asc) },
@@ -126,7 +135,7 @@ module Spree
private
def product_definitions
- scope = Spree::CustomFieldDefinition.for_resource_type('Spree::Product')
+ scope = store.custom_field_definitions.for_resource_type('Spree::Product')
scope.where(searchable: true).or(scope.where(sortable: true))
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 912bb05119..0ad14d13c6 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -248,6 +248,7 @@ en:
messages:
blank: can't be blank
must_apply_to_products: must be a custom field definition for products
+ must_belong_to_same_store: must belong to the same store
not_registered: is not a registered provider
spree_content_type_not_allowed: is not a file type we accept
models:
diff --git a/spree/core/db/migrate/20260902000001_add_store_and_filter_key_to_custom_field_definitions.rb b/spree/core/db/migrate/20260902000001_add_store_and_filter_key_to_custom_field_definitions.rb
new file mode 100644
index 0000000000..e776f2cc86
--- /dev/null
+++ b/spree/core/db/migrate/20260902000001_add_store_and_filter_key_to_custom_field_definitions.rb
@@ -0,0 +1,143 @@
+class AddStoreAndFilterKeyToCustomFieldDefinitions < ActiveRecord::Migration[8.1]
+ def up
+ add_reference :spree_custom_field_definitions, :store unless column_exists?(:spree_custom_field_definitions, :store_id)
+
+ unless column_exists?(:spree_custom_field_definitions, :filter_key)
+ add_column :spree_custom_field_definitions, :filter_key, :string
+ end
+
+ # Read through SQL rather than Spree::Store: a migration that loads a model
+ # breaks the moment that model's columns move ahead of this point in the
+ # migration history.
+ default_store_id = select_value(
+ "SELECT id FROM spree_stores ORDER BY #{quote_column_name(:default)} DESC, id ASC LIMIT 1"
+ )
+
+ execute("UPDATE spree_custom_field_definitions SET store_id = #{default_store_id.to_i} WHERE store_id IS NULL") if default_store_id.present?
+
+ # The same value the model's callback writes. Definitions predating this
+ # migration are backfilled here so the unique index below has something to
+ # constrain.
+ execute(<<~SQL.squish)
+ UPDATE spree_custom_field_definitions
+ SET filter_key = #{concat_filter_key}
+ WHERE filter_key IS NULL
+ SQL
+
+ remove_index :spree_custom_field_definitions, column: [:resource_type, :namespace, :key], unique: true, if_exists: true
+
+ disambiguate_colliding_filter_keys
+
+ add_index :spree_custom_field_definitions, [:store_id, :resource_type, :filter_key],
+ unique: true, name: 'index_custom_field_definitions_on_store_and_filter_key'
+ add_index :spree_custom_field_definitions, [:store_id, :resource_type, :namespace, :key],
+ unique: true, name: 'index_custom_field_definitions_on_store_and_key'
+
+ # Enforce once nothing is left unowned — true on a fresh install (empty
+ # table) and after the backfill above. A leftover orphan skips the
+ # constraint rather than failing the migration;
+ # spree:upgrade:backfill_custom_field_definition_stores is the recovery path.
+ return if select_value('SELECT COUNT(*) FROM spree_custom_field_definitions WHERE store_id IS NULL OR filter_key IS NULL').to_i.positive?
+
+ change_column_null :spree_custom_field_definitions, :store_id, false
+ change_column_null :spree_custom_field_definitions, :filter_key, false
+ end
+
+ def down
+ # Two stores may each hold `custom.material` once this migration has run —
+ # that is the point of it. The pre-migration index was global, so rolling
+ # back over such a pair has no correct answer: one of them would have to
+ # lose its key. Refuse before anything is dropped rather than fail halfway
+ # with the columns already gone.
+ duplicated = select_value(<<~SQL.squish).to_i
+ SELECT COUNT(*) FROM (
+ SELECT 1 FROM spree_custom_field_definitions
+ GROUP BY resource_type, namespace, #{quote_column_name(:key)}
+ HAVING COUNT(*) > 1
+ ) AS duplicated_keys
+ SQL
+
+ if duplicated.positive?
+ raise ActiveRecord::IrreversibleMigration,
+ "#{duplicated} custom field definition key(s) are held by more than one store. " \
+ 'The pre-6.0 schema indexes them globally, so rolling back would have to discard one of each pair. ' \
+ 'Remove the duplicates you do not want to keep, then roll back.'
+ end
+
+ remove_index :spree_custom_field_definitions, name: 'index_custom_field_definitions_on_store_and_filter_key', if_exists: true
+ remove_index :spree_custom_field_definitions, name: 'index_custom_field_definitions_on_store_and_key', if_exists: true
+
+ add_index :spree_custom_field_definitions, [:resource_type, :namespace, :key], unique: true
+
+ remove_column :spree_custom_field_definitions, :filter_key
+ remove_reference :spree_custom_field_definitions, :store
+ end
+
+ private
+
+ # `key` and `namespace` both normalize to underscored slugs, so ("a_b", "c")
+ # and ("a", "b_c") flatten to one filter_key. Nothing forbade that before
+ # this migration, so an existing install can hold a pair the unique index
+ # below would reject. The later row keeps its namespace and key and gets a
+ # suffixed filter_key, which keeps it addressable and leaves the operator a
+ # visible thing to rename.
+ def disambiguate_colliding_filter_keys
+ duplicate_groups = select_rows(<<~SQL.squish)
+ SELECT store_id, resource_type, filter_key
+ FROM spree_custom_field_definitions
+ GROUP BY store_id, resource_type, filter_key
+ HAVING COUNT(*) > 1
+ SQL
+
+ duplicate_groups.each do |store_id, resource_type, filter_key|
+ ids = select_values(<<~SQL.squish)
+ SELECT id FROM spree_custom_field_definitions
+ WHERE store_id #{store_id.nil? ? 'IS NULL' : "= #{store_id.to_i}"}
+ AND resource_type = #{quote(resource_type)}
+ AND filter_key = #{quote(filter_key)}
+ ORDER BY id ASC
+ SQL
+
+ ids.drop(1).each do |id|
+ replacement = free_filter_key(filter_key, store_id, resource_type)
+ execute("UPDATE spree_custom_field_definitions SET filter_key = #{quote(replacement)} WHERE id = #{quote(id)}")
+ say " filter_key collision on #{filter_key} — definition #{id} renamed to #{replacement}", true
+ end
+ end
+ end
+
+ # The first +cf_..._2+, +_3+, ... not already taken in this store. An install
+ # can legitimately hold the suffixed form as a definition of its own
+ # (namespace +a_b_c+, key +2+), and handing it out twice would fail the
+ # unique index halfway through this migration.
+ def free_filter_key(filter_key, store_id, resource_type)
+ suffix = 2
+
+ loop do
+ candidate = "#{filter_key}_#{suffix}"
+ taken = select_value(<<~SQL.squish)
+ SELECT 1 FROM spree_custom_field_definitions
+ WHERE store_id #{store_id.nil? ? 'IS NULL' : "= #{store_id.to_i}"}
+ AND resource_type = #{quote(resource_type)}
+ AND filter_key = #{quote(candidate)}
+ LIMIT 1
+ SQL
+ return candidate if taken.nil?
+
+ suffix += 1
+ end
+ end
+
+ # `CONCAT` is MySQL/PostgreSQL; SQLite spells the same thing `||`. Both
+ # column names are quoted — `key` is reserved on MySQL.
+ def concat_filter_key
+ namespace = quote_column_name(:namespace)
+ key = quote_column_name(:key)
+
+ if connection.adapter_name.match?(/sqlite/i)
+ "'cf_' || #{namespace} || '_' || #{key}"
+ else
+ "CONCAT('cf_', #{namespace}, '_', #{key})"
+ end
+ end
+end
diff --git a/spree/core/db/sample_data/custom_field_definitions.rb b/spree/core/db/sample_data/custom_field_definitions.rb
index 268a1db429..ecb23ef090 100644
--- a/spree/core/db/sample_data/custom_field_definitions.rb
+++ b/spree/core/db/sample_data/custom_field_definitions.rb
@@ -1,5 +1,7 @@
+store = Spree::Store.default
+
%w[warranty capacity voltage wattage runtime room_coverage noise_level connectivity].each do |key|
- Spree::CustomFieldDefinition.find_or_create_by!(
+ store.custom_field_definitions.find_or_create_by!(
namespace: 'custom',
key: key,
resource_type: 'Spree::Product'
diff --git a/spree/core/db/sample_data/product_types.rb b/spree/core/db/sample_data/product_types.rb
index 3fcff6ea53..9d10ef9998 100644
--- a/spree/core/db/sample_data/product_types.rb
+++ b/spree/core/db/sample_data/product_types.rb
@@ -14,7 +14,7 @@ store = Spree::Store.default
color_option_type = Spree::OptionType.find_by(name: 'color')
-definitions = Spree::CustomFieldDefinition.where(
+definitions = store.custom_field_definitions.where(
namespace: 'custom',
resource_type: 'Spree::Product'
).index_by(&:key)
diff --git a/spree/core/lib/spree/testing_support/factories/custom_field_definition_factory.rb b/spree/core/lib/spree/testing_support/factories/custom_field_definition_factory.rb
index 2195371f89..77960667b1 100644
--- a/spree/core/lib/spree/testing_support/factories/custom_field_definition_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/custom_field_definition_factory.rb
@@ -1,5 +1,6 @@
FactoryBot.define do
factory :custom_field_definition, aliases: [:metafield_definition], class: 'Spree::CustomFieldDefinition' do
+ store { Spree::Store.default || create(:store) }
namespace { 'custom' }
sequence(:key) { |n| "custom_field_#{n}" }
label { 'Custom Field' }
diff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
index ff3ce7c1e9..fcb1fd0c7f 100644
--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
@@ -578,3 +578,28 @@ steps:
store, and their seller_id column is new for everyone.
Idempotent — imports that already carry a store are skipped.
+
+ - id: backfill_custom_field_definition_stores
+ name: "Bind custom field definitions to the default store"
+ task: "spree:upgrade:backfill_custom_field_definition_stores"
+ notes: |
+ Custom field definitions are store-owned in Spree 6.0, and their
+ sort/filter identifier is now a real column rather than a value computed
+ on every read. The migration backfills both and enforces NOT NULL, so
+ this is a safety net for installs whose migration ran before any store
+ existed.
+
+ Until this runs, a definition without a store is invisible to every
+ scoped query — the admin list, the CSV export's header row, and the
+ product listing's custom-field sorts and filters all read through the
+ store.
+
+ A multi-store install ends up with every definition on the default
+ store. Fields wanted on another store are re-created there; nothing is
+ copied automatically, because the values still point at the originals
+ and the copies would render blank either way.
+
+ Reports and skips any definition whose namespace/key pair flattens to a
+ filter_key another row in the same store already owns — only one of them
+ can be addressed as a sort or filter param. Rename one and re-run.
+ Idempotent.
diff --git a/spree/core/lib/tasks/backfill_custom_field_definition_stores.rake b/spree/core/lib/tasks/backfill_custom_field_definition_stores.rake
new file mode 100644
index 0000000000..524afe98f1
--- /dev/null
+++ b/spree/core/lib/tasks/backfill_custom_field_definition_stores.rake
@@ -0,0 +1,82 @@
+namespace :spree do
+ namespace :upgrade do
+ desc <<~DESC
+ Assigns the default store and the persisted filter_key to custom field
+ definitions that predate their store binding (Spree 6.0). Idempotent —
+ rows that already carry both are skipped.
+
+ The migration backfills and then enforces NOT NULL, so this is a safety
+ net rather than the primary path: it covers installs whose migration ran
+ before any store existed, leaving definitions unowned and the constraint
+ unapplied.
+
+ A definition whose namespace/key pair flattens to a filter_key another
+ row in the same store already owns is reported and skipped — only one of
+ them can be addressed as a sort or filter param. Rename one and re-run.
+ DESC
+ task backfill_custom_field_definition_stores: :environment do
+ store = Spree::Store.default
+ abort ' No default store found — create a store first.' if store.nil?
+
+ assigned = Spree::CustomFieldDefinition.where(store_id: nil).update_all(store_id: store.id)
+ puts " Assigned #{assigned} custom field definition(s) to store #{store.name} (#{store.id})."
+
+ backfilled = 0
+ skipped = []
+
+ Spree::CustomFieldDefinition.where(filter_key: nil).find_each do |definition|
+ # `valid?` fires the callback that derives filter_key from namespace and
+ # key; the save skips validation so unrelated legacy data — a field type
+ # an extension no longer registers, say — cannot block the backfill.
+ definition.valid?
+
+ taken = Spree::CustomFieldDefinition.
+ where(store_id: definition.store_id, resource_type: definition.resource_type,
+ filter_key: definition.filter_key).
+ where.not(id: definition.id).
+ exists?
+
+ if taken
+ skipped << definition
+ next
+ end
+
+ definition.save!(validate: false)
+ backfilled += 1
+ end
+
+ puts " Backfilled filter_key on #{backfilled} definition(s)."
+
+ if skipped.any?
+ puts " Skipped #{skipped.size} definition(s) whose filter_key is already taken in their store:"
+ skipped.each do |definition|
+ puts " #{definition.id}: #{definition.namespace}.#{definition.key} (#{definition.resource_type}) " \
+ "would be #{definition.filter_key}"
+ end
+ puts ' Rename one of each colliding pair and re-run this task.'
+ end
+
+ # The migration applies these itself and only skips them when it found
+ # rows it could not fill. Leaving them off is what this task exists to
+ # put right: without them the unique indexes constrain nothing, because
+ # SQL treats NULLs as distinct.
+ table = Spree::CustomFieldDefinition.table_name
+ connection = ActiveRecord::Base.connection
+
+ %i[store_id filter_key].each do |column|
+ next unless connection.column_exists?(table, column)
+ next if connection.columns(table).find { |c| c.name == column.to_s }&.null == false
+
+ if Spree::CustomFieldDefinition.where(column => nil).exists?
+ puts " #{column} is still NULL on some definitions — leaving it nullable until they are resolved."
+ next
+ end
+
+ connection.change_column_null(table, column, false)
+ puts " Enforced NOT NULL on #{column}."
+ end
+
+ Spree::CustomFieldDefinition.reset_column_information
+ end
+ end
+end
diff --git a/spree/core/spec/db/migrate/add_store_and_filter_key_to_custom_field_definitions_spec.rb b/spree/core/spec/db/migrate/add_store_and_filter_key_to_custom_field_definitions_spec.rb
new file mode 100644
index 0000000000..b986ac9c1a
--- /dev/null
+++ b/spree/core/spec/db/migrate/add_store_and_filter_key_to_custom_field_definitions_spec.rb
@@ -0,0 +1,101 @@
+require 'spec_helper'
+
+# The migration derives filter_key for every pre-existing definition, and two
+# different namespace/key splits can flatten to one value. Nothing forbade that
+# before the migration, so an existing install can hold a pair the unique index
+# would reject — data no model can reach once the constraint is on.
+#
+# The disambiguation is exercised through its own query-building rather than by
+# planting colliding rows: doing that needs the unique index dropped, which is
+# DDL, and MySQL commits implicitly on DDL — dropping the savepoint the example
+# runs inside.
+RSpec.describe 'AddStoreAndFilterKeyToCustomFieldDefinitions migration' do
+ let(:migration) do
+ require Spree::Core::Engine.root.join(
+ 'db', 'migrate', '20260902000001_add_store_and_filter_key_to_custom_field_definitions.rb'
+ )
+ AddStoreAndFilterKeyToCustomFieldDefinitions.new
+ end
+
+ let(:store) { Spree::Store.default }
+
+ describe '#free_filter_key' do
+ it 'suffixes with _2 when nothing holds it' do
+ expect(migration.send(:free_filter_key, 'cf_a_b_c', store.id, 'Spree::Product')).to eq('cf_a_b_c_2')
+ end
+
+ # An install can legitimately hold the suffixed form as a definition of its
+ # own (namespace `a_b_c`, key `2`), and handing it out twice would fail the
+ # unique index halfway through the migration.
+ it 'skips a suffix another definition already owns' do
+ create(:custom_field_definition, store: store, resource_type: 'Spree::Product', namespace: 'a_b_c', key: '2')
+
+ expect(migration.send(:free_filter_key, 'cf_a_b_c', store.id, 'Spree::Product')).to eq('cf_a_b_c_3')
+ end
+
+ it 'ignores a row holding that key in another store' do
+ create(:custom_field_definition, store: create(:store), resource_type: 'Spree::Product',
+ namespace: 'a_b_c', key: '2')
+
+ expect(migration.send(:free_filter_key, 'cf_a_b_c', store.id, 'Spree::Product')).to eq('cf_a_b_c_2')
+ end
+
+ it 'ignores a row holding that key for another resource type' do
+ create(:custom_field_definition, store: store, resource_type: 'Spree::Order', namespace: 'a_b_c', key: '2')
+
+ expect(migration.send(:free_filter_key, 'cf_a_b_c', store.id, 'Spree::Product')).to eq('cf_a_b_c_2')
+ end
+ end
+
+ describe '#disambiguate_colliding_filter_keys' do
+ # Every row on a migrated schema already holds a unique filter_key, so the
+ # pass has nothing to rename and must leave them untouched.
+ it 'is a no-op when no two rows share a filter key' do
+ first = create(:custom_field_definition, store: store, resource_type: 'Spree::Product',
+ namespace: 'a_b', key: 'c')
+ second = create(:custom_field_definition, store: store, resource_type: 'Spree::Product',
+ namespace: 'custom', key: 'material')
+
+ migration.send(:disambiguate_colliding_filter_keys)
+
+ expect(first.reload[:filter_key]).to eq('cf_a_b_c')
+ expect(second.reload[:filter_key]).to eq('cf_custom_material')
+ end
+ end
+
+ # Two stores may each hold `custom.material` once this migration has run —
+ # that is the point of it. The pre-migration index was global, so rolling
+ # back over such a pair has no correct answer.
+ describe '#down' do
+ it 'refuses when two stores hold the same key' do
+ create(:custom_field_definition, store: store, resource_type: 'Spree::Product',
+ namespace: 'custom', key: 'material')
+ create(:custom_field_definition, store: create(:store), resource_type: 'Spree::Product',
+ namespace: 'custom', key: 'material')
+
+ expect { migration.down }.to raise_error(ActiveRecord::IrreversibleMigration, /more than one store/)
+ end
+
+ it 'leaves the columns in place when it refuses' do
+ create(:custom_field_definition, store: store, resource_type: 'Spree::Product',
+ namespace: 'custom', key: 'material')
+ create(:custom_field_definition, store: create(:store), resource_type: 'Spree::Product',
+ namespace: 'custom', key: 'material')
+
+ expect { migration.down }.to raise_error(ActiveRecord::IrreversibleMigration)
+
+ expect(Spree::CustomFieldDefinition.column_names).to include('store_id', 'filter_key')
+ end
+ end
+
+ describe '#concat_filter_key' do
+ it 'builds the same value the model derives, quoting the reserved key column' do
+ sql = migration.send(:concat_filter_key)
+
+ expect(sql).to include('cf_')
+ expect(sql).to match(/namespace/).and match(/key/)
+ # `key` is reserved on MySQL, so both column names must arrive quoted.
+ expect(sql).not_to match(/[^"`\w]key[^"`\w]/)
+ end
+ end
+end
diff --git a/spree/core/spec/lib/tasks/backfill_custom_field_definition_stores_spec.rb b/spree/core/spec/lib/tasks/backfill_custom_field_definition_stores_spec.rb
new file mode 100644
index 0000000000..cd01e96bc1
--- /dev/null
+++ b/spree/core/spec/lib/tasks/backfill_custom_field_definition_stores_spec.rb
@@ -0,0 +1,118 @@
+require 'spec_helper'
+require 'rake'
+
+# The task is the recovery path for an install whose migration ran with no
+# store present, leaving rows unowned and the NOT NULL constraints unapplied.
+# That shape cannot be built here — the constraints are on, and relaxing them
+# is DDL, which MySQL commits implicitly and so drops the savepoint the example
+# runs inside. What is testable without them is the behaviour every install
+# sees: the task is a no-op on a migrated schema, and it refuses to run with no
+# store to assign.
+describe 'spree:upgrade:backfill_custom_field_definition_stores' do
+ subject { Rake::Task[task_name] }
+
+ let(:task_name) { 'spree:upgrade:backfill_custom_field_definition_stores' }
+
+ before(:all) do
+ Rake::Task.define_task(:environment)
+ load Spree::Core::Engine.root.join('lib', 'tasks', 'backfill_custom_field_definition_stores.rake')
+ end
+
+ before { subject.reenable }
+
+ let(:store) { Spree::Store.default }
+
+ it 'reports nothing to do on a migrated schema' do
+ create(:custom_field_definition, store: store, namespace: 'custom', key: 'material')
+
+ expect { subject.invoke }.to output(/Assigned 0 .*Backfilled filter_key on 0/m).to_stdout
+ end
+
+ it 'leaves every definition exactly as it found it' do
+ other_store = create(:store)
+ mine = create(:custom_field_definition, store: store, namespace: 'custom', key: 'material')
+ theirs = create(:custom_field_definition, store: other_store, namespace: 'custom', key: 'supplier')
+
+ subject.invoke
+
+ expect(mine.reload.store).to eq(store)
+ expect(mine.reload[:filter_key]).to eq('cf_custom_material')
+ expect(theirs.reload.store).to eq(other_store)
+ end
+
+ # The migration applies these itself and skips them only when it found rows
+ # it could not fill. Restoring them is what this task exists to do — without
+ # them the unique indexes constrain nothing, since SQL treats NULLs as
+ # distinct.
+ it 'reports the constraints it enforced' do
+ create(:custom_field_definition, store: store, namespace: 'custom', key: 'material')
+
+ # Already enforced by the migration, so the task finds nothing to do and
+ # says so by staying silent about them rather than re-applying.
+ expect { subject.invoke }.not_to output(/leaving it nullable/).to_stdout
+ end
+
+ # The branch that matters runs only on the schema the task exists to repair:
+ # columns the migration left nullable because it found rows it could not
+ # fill. Relaxing them here would be DDL, which MySQL commits implicitly and
+ # so drops the savepoint the example runs inside — so the schema is reported
+ # as nullable instead, and the constraint call is observed rather than
+ # applied.
+ #
+ # The task guards each column separately, so both are covered: a regression
+ # in either one's branch has to fail an example.
+ def report_nullable(*columns)
+ connection = ActiveRecord::Base.connection
+ relaxed = connection.columns(Spree::CustomFieldDefinition.table_name).map do |column|
+ next column unless columns.map(&:to_s).include?(column.name)
+
+ column.dup.tap { |c| c.instance_variable_set(:@null, true) }
+ end
+
+ allow(connection).to receive(:columns).and_call_original
+ allow(connection).to receive(:columns).with(Spree::CustomFieldDefinition.table_name).and_return(relaxed)
+ allow(connection).to receive(:change_column_null).and_return(true)
+ connection
+ end
+
+ %i[store_id filter_key].each do |column|
+ it "enforces #{column} when the migration left it off" do
+ connection = report_nullable(column)
+
+ expect { subject.invoke }.to output(/Enforced NOT NULL on #{column}/).to_stdout
+
+ expect(connection).to have_received(:change_column_null).
+ with(Spree::CustomFieldDefinition.table_name, column, false)
+ end
+
+ it "leaves #{column} alone while rows still cannot be filled" do
+ connection = report_nullable(column)
+ # The guard reads `exists?`; the backfill loop earlier in the task reads
+ # `find_each` off the same query, so the double answers both.
+ unresolved = instance_double(ActiveRecord::Relation, exists?: true, find_each: nil, update_all: 0)
+ allow(Spree::CustomFieldDefinition).to receive(:where).and_call_original
+ allow(Spree::CustomFieldDefinition).to receive(:where).with(column => nil).and_return(unresolved)
+
+ expect { subject.invoke }.to output(/#{column} is still NULL/).to_stdout
+
+ expect(connection).not_to have_received(:change_column_null).with(anything, column, false)
+ end
+ end
+
+ it 'enforces both columns when the migration left both off' do
+ connection = report_nullable(:store_id, :filter_key)
+
+ subject.invoke
+
+ expect(connection).to have_received(:change_column_null).
+ with(Spree::CustomFieldDefinition.table_name, :store_id, false)
+ expect(connection).to have_received(:change_column_null).
+ with(Spree::CustomFieldDefinition.table_name, :filter_key, false)
+ end
+
+ it 'refuses to run without a default store to assign' do
+ allow(Spree::Store).to receive(:default).and_return(nil)
+
+ expect { subject.invoke }.to raise_error(SystemExit).and output(/No default store/).to_stderr
+ end
+end
diff --git a/spree/core/spec/models/concerns/spree/custom_field_filterable_spec.rb b/spree/core/spec/models/concerns/spree/custom_field_filterable_spec.rb
index e354a044f3..9f65998760 100644
--- a/spree/core/spec/models/concerns/spree/custom_field_filterable_spec.rb
+++ b/spree/core/spec/models/concerns/spree/custom_field_filterable_spec.rb
@@ -24,14 +24,18 @@ RSpec.describe Spree::CustomFieldFilterable do
product_3.set_custom_field(weight, '3.5')
end
+ def schema
+ Spree::SearchProvider::CustomFieldSchema.new(store)
+ end
+
def filter(filters)
- scope, remaining = Spree::Product.with_custom_field_filters(filters)
+ scope, remaining = Spree::Product.with_custom_field_filters(filters, schema: schema)
[scope.to_a, remaining]
end
describe '.with_custom_field_filters' do
it 'returns the untouched scope and filters when no cf_* keys are present' do
- scope, remaining = Spree::Product.with_custom_field_filters({'name_cont' => 'Blue'})
+ scope, remaining = Spree::Product.with_custom_field_filters({'name_cont' => 'Blue'}, schema: schema)
expect(scope.to_a).to match_array([product_1, product_2, product_3])
expect(remaining).to eq('name_cont' => 'Blue')
@@ -82,16 +86,17 @@ RSpec.describe Spree::CustomFieldFilterable do
end
it 'leaves keys whose predicate the field type does not support for Ransack' do
- _, remaining = Spree::Product.with_custom_field_filters({'cf_custom_weight_cont' => 'abc'})
+ _, remaining = Spree::Product.with_custom_field_filters({'cf_custom_weight_cont' => 'abc'}, schema: schema)
expect(remaining).to eq('cf_custom_weight_cont' => 'abc')
end
# The schema hits the DB, so a filter hash with no cf_* keys must not pay for it.
- it 'does not build a schema when no cf_* key is present' do
- expect(Spree::SearchProvider::CustomFieldSchema).not_to receive(:new)
+ it 'does not read the schema when no cf_* key is present' do
+ untouched = Spree::SearchProvider::CustomFieldSchema.new(store)
+ expect(untouched).not_to receive(:parse_filter)
- Spree::Product.with_custom_field_filters({'name_cont' => 'Blue'})
+ Spree::Product.with_custom_field_filters({'name_cont' => 'Blue'}, schema: untouched)
end
end
diff --git a/spree/core/spec/models/concerns/spree/has_custom_fields_spec.rb b/spree/core/spec/models/concerns/spree/has_custom_fields_spec.rb
index 886d83d84e..b29d1974ba 100644
--- a/spree/core/spec/models/concerns/spree/has_custom_fields_spec.rb
+++ b/spree/core/spec/models/concerns/spree/has_custom_fields_spec.rb
@@ -159,6 +159,46 @@ RSpec.describe Spree::HasCustomFields, type: :concern do
product.set_custom_field(Object.new, 'x')
}.to raise_error(ArgumentError, /Invalid definition_or_key/)
end
+
+ # Definitions are store-owned, so a record must not end up carrying one
+ # from another store — whichever of the accepted shapes names it.
+ context 'with a definition owned by another store' do
+ let(:foreign) do
+ create(:custom_field_definition, store: create(:store), namespace: 'custom',
+ key: 'supplier', resource_type: 'Spree::Product')
+ end
+
+ it 'refuses the record itself' do
+ expect { product.set_custom_field(foreign, 'x') }.to raise_error(ArgumentError, /Unknown custom field definition/)
+ end
+
+ it 'refuses its prefixed id' do
+ expect { product.set_custom_field(foreign.prefixed_id, 'x') }.to raise_error(ArgumentError, /Unknown custom field definition/)
+ end
+
+ it 'refuses its raw id' do
+ expect { product.set_custom_field(foreign.id, 'x') }.to raise_error(ArgumentError, /Unknown custom field definition/)
+ end
+
+ it 'writes nothing' do
+ expect {
+ begin
+ product.set_custom_field(foreign, 'x')
+ rescue ArgumentError
+ nil
+ end
+ }.not_to change { Spree::CustomField.count }
+ end
+ end
+
+ it 'accepts a definition owned by the record\'s own store' do
+ definition = create(:custom_field_definition, store: product.store, namespace: 'custom',
+ key: 'material', resource_type: 'Spree::Product')
+
+ product.set_custom_field(definition, 'wool')
+
+ expect(product.get_custom_field('custom.material').value).to eq('wool')
+ end
end
describe '#has_custom_field?' do
diff --git a/spree/core/spec/models/spree/custom_field_definition_spec.rb b/spree/core/spec/models/spree/custom_field_definition_spec.rb
index 25d5775b4c..69c48293db 100644
--- a/spree/core/spec/models/spree/custom_field_definition_spec.rb
+++ b/spree/core/spec/models/spree/custom_field_definition_spec.rb
@@ -143,6 +143,68 @@ RSpec.describe Spree::CustomFieldDefinition, type: :model do
expect(custom_field_definition.filter_key).to eq('cf_custom_material')
end
+
+ it 'persists the value so it can be queried' do
+ custom_field_definition = create(:custom_field_definition, namespace: 'custom', key: 'material')
+
+ expect(custom_field_definition.reload[:filter_key]).to eq('cf_custom_material')
+ end
+
+ it 'follows a renamed namespace or key' do
+ custom_field_definition = create(:custom_field_definition, namespace: 'custom', key: 'material')
+
+ custom_field_definition.update!(namespace: 'specs', key: 'fabric')
+
+ expect(custom_field_definition.reload[:filter_key]).to eq('cf_specs_fabric')
+ end
+
+ # The upgrade migration suffixes one of a colliding pair. Recomputing on an
+ # unrelated edit would undo that and leave the row permanently unsaveable.
+ it 'keeps a suffixed value when neither segment changes' do
+ custom_field_definition = create(:custom_field_definition, namespace: 'a', key: 'b_c')
+ described_class.where(id: custom_field_definition.id).update_all(filter_key: 'cf_a_b_c_2')
+
+ custom_field_definition.reload.update!(label: 'Renamed')
+
+ expect(custom_field_definition.reload[:filter_key]).to eq('cf_a_b_c_2')
+ end
+ end
+
+ describe 'store scoping' do
+ let(:other_store) { create(:store) }
+
+ it 'defaults to the current store' do
+ Spree::Current.store = @default_store
+
+ expect(create(:custom_field_definition, store: nil).store).to eq(@default_store)
+ ensure
+ Spree::Current.store = nil
+ end
+
+ it 'is reachable through the store association' do
+ custom_field_definition = create(:custom_field_definition, store: other_store)
+
+ expect(other_store.custom_field_definitions).to include(custom_field_definition)
+ expect(@default_store.custom_field_definitions).not_to include(custom_field_definition)
+ end
+
+ it 'allows the same namespace and key in two stores' do
+ create(:custom_field_definition, store: @default_store, resource_type: 'Spree::Product',
+ namespace: 'custom', key: 'material')
+ twin = build(:custom_field_definition, store: other_store, resource_type: 'Spree::Product',
+ namespace: 'custom', key: 'material')
+
+ expect(twin).to be_valid
+ end
+
+ it 'refuses to move a saved definition to another store' do
+ custom_field_definition = create(:custom_field_definition, store: @default_store)
+
+ custom_field_definition.store = other_store
+
+ expect(custom_field_definition).not_to be_valid
+ expect(custom_field_definition.errors[:store]).to be_present
+ end
end
describe 'filter_key uniqueness' do
@@ -153,7 +215,16 @@ RSpec.describe Spree::CustomFieldDefinition, type: :model do
colliding = build(:custom_field_definition, resource_type: 'Spree::Product', namespace: 'a', key: 'b_c')
expect(colliding).not_to be_valid
- expect(colliding.errors[:key]).to be_present
+ expect(colliding.errors[:filter_key]).to be_present
+ end
+
+ it 'allows the same filter_key in a different store' do
+ create(:custom_field_definition, store: @default_store, resource_type: 'Spree::Product',
+ namespace: 'a_b', key: 'c')
+ other_store = build(:custom_field_definition, store: create(:store), resource_type: 'Spree::Product',
+ namespace: 'a', key: 'b_c')
+
+ expect(other_store).to be_valid
end
it 'allows the same namespace/key split on a different resource type' do
diff --git a/spree/core/spec/models/spree/custom_field_spec.rb b/spree/core/spec/models/spree/custom_field_spec.rb
index abb044aa55..6e483d63da 100644
--- a/spree/core/spec/models/spree/custom_field_spec.rb
+++ b/spree/core/spec/models/spree/custom_field_spec.rb
@@ -135,6 +135,55 @@ RSpec.describe Spree::CustomField, type: :model do
end
end
+ # The last gate every write path passes through. `custom_fields=` resolves
+ # the definition through the store, but Rails' own nested-attributes writer
+ # assigns the id straight onto the row and reaches nothing else.
+ describe 'store agreement validation' do
+ let(:product) { create(:product) }
+
+ it 'rejects a definition owned by another store' do
+ foreign = create(:custom_field_definition, store: create(:store), resource_type: 'Spree::Product')
+ custom_field = build(:custom_field, resource: product, custom_field_definition: foreign)
+
+ expect(custom_field).not_to be_valid
+ expect(custom_field.errors[:custom_field_definition]).to include('must belong to the same store')
+ end
+
+ it 'accepts a definition owned by the resource store' do
+ own = create(:custom_field_definition, store: product.store, resource_type: 'Spree::Product')
+ custom_field = build(:custom_field, resource: product, custom_field_definition: own, value: 'x')
+
+ expect(custom_field).to be_valid
+ end
+
+ it 'refuses one assigned through nested attributes' do
+ foreign = create(:custom_field_definition, store: create(:store), resource_type: 'Spree::Product')
+
+ product.custom_fields_attributes = [{ custom_field_definition_id: foreign.id, value: 'x' }]
+
+ expect(product).not_to be_valid
+ end
+
+ it 'refuses a foreign definition on a variant, which belongs to its product store' do
+ variant = create(:variant, product: product)
+ foreign = create(:custom_field_definition, store: create(:store), resource_type: 'Spree::Variant', key: 'vk')
+ custom_field = build(:custom_field, resource: variant, custom_field_definition: foreign, value: 'x')
+
+ expect(custom_field).not_to be_valid
+ expect(custom_field.errors[:custom_field_definition]).to include('must belong to the same store')
+ end
+
+ # A customer is global, so there is no store to compare against — and the
+ # definition it was given was resolved within one already.
+ it 'leaves a resource without a store of its own alone' do
+ customer = create(:user)
+ definition = create(:custom_field_definition, :for_user, store: create(:store))
+ custom_field = build(:custom_field, resource: customer, custom_field_definition: definition, value: 'x')
+
+ expect(custom_field).to be_valid
+ end
+ end
+
describe 'deprecated definition writer' do
it 'assigns through metafield_definition=' do
definition = create(:custom_field_definition)
diff --git a/spree/core/spec/models/spree/export_spec.rb b/spree/core/spec/models/spree/export_spec.rb
index d4ab035075..9f84f68717 100644
--- a/spree/core/spec/models/spree/export_spec.rb
+++ b/spree/core/spec/models/spree/export_spec.rb
@@ -76,6 +76,43 @@ RSpec.describe Spree::Export, :job, type: :model do
expect { export.generate }.to change(export.attachment, :attached?).from(false).to(true)
end
end
+
+ # Header and value rows are built in different objects, so they have to
+ # agree about whose custom-field schema they describe or every value
+ # column silently shifts.
+ describe 'custom field columns' do
+ let!(:mine) do
+ create(:custom_field_definition, store: store, resource_type: 'Spree::Product',
+ namespace: 'custom', key: 'material')
+ end
+ let!(:theirs) do
+ create(:custom_field_definition, store: create(:store), resource_type: 'Spree::Product',
+ namespace: 'custom', key: 'supplier')
+ end
+ let!(:product) { create(:product, store: store) }
+
+ def generated_rows
+ export.save!
+ export.generate
+ ::CSV.parse(export.attachment.download)
+ end
+
+ it 'names only the exporting store definitions in the header' do
+ headers, = generated_rows
+
+ expect(headers).to include('custom_field.custom.material')
+ expect(headers).not_to include('custom_field.custom.supplier')
+ end
+
+ it 'lines each value up under its own header' do
+ product.set_custom_field(mine, 'Wool-Blend')
+
+ headers, *rows = generated_rows
+ column = headers.index('custom_field.custom.material')
+
+ expect(rows.map { |values| values[column] }).to include('Wool-Blend')
+ end
+ end
end
describe '#scope' do
@@ -227,6 +264,44 @@ RSpec.describe Spree::Export, :job, type: :model do
end
end
+ # An export runs in a job, so nothing has named a store. A scope that reads
+ # the current one has to see the store being exported, not the default.
+ context 'with a free-text search param' do
+ it 'exports a searched customer list' do
+ create(:user, email: '[email protected]')
+ customer_export = Spree::Exports::Customers.create!(
+ store: store, user: user, format: 'csv', search_params: { search: 'findme' }.to_json
+ )
+
+ expect { customer_export.generate }.to change(customer_export.attachment, :attached?).from(false).to(true)
+ end
+
+ it 'exports a searched product list' do
+ create(:product, name: 'Findable Widget')
+ product_export = Spree::Exports::Products.create!(
+ store: store, user: user, format: 'csv', search_params: { multi_search: 'Findable' }.to_json
+ )
+
+ expect { product_export.generate }.to change(product_export.attachment, :attached?).from(false).to(true)
+ end
+
+ it 'names the exporting store while it runs' do
+ other_store = create(:store)
+ Spree::Current.store = other_store
+ seen = nil
+ export.save!
+ allow(export).to receive(:csv_headers).and_wrap_original do |original|
+ seen = Spree::Current.store
+ original.call
+ end
+
+ export.generate
+
+ expect(seen).to eq(store)
+ expect(Spree::Current.store).to eq(other_store)
+ end
+ end
+
# The dashboard builds export search_params from the same filter state as
# the products table, so a `cf_*` filter has to survive the round-trip —
# Ransack alone has no such attribute.
diff --git a/spree/core/spec/models/spree/media_spec.rb b/spree/core/spec/models/spree/media_spec.rb
index 2c16939952..8b1d036e58 100644
--- a/spree/core/spec/models/spree/media_spec.rb
+++ b/spree/core/spec/models/spree/media_spec.rb
@@ -595,6 +595,18 @@ describe Spree::Media, type: :model do
asset = create(:asset)
expect(asset.external_url).to be_nil
end
+
+ # store_id is filled in at before_validation, so a row still being built
+ # has none — and an imported image is given its URL before it is saved.
+ it 'files the definition on the viewable store while the row is unsaved' do
+ other_store = create(:store)
+ product = create(:product, store: other_store)
+ Spree::Current.store = nil
+
+ media = product.images.new(viewable: product)
+
+ expect(media.send(:custom_field_definition_store)).to eq(other_store)
+ end
end
describe '#external_url=' do
diff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rb
index 0bfa3ea3d7..3fbf44db58 100644
--- a/spree/core/spec/models/spree/payment_spec.rb
+++ b/spree/core/spec/models/spree/payment_spec.rb
@@ -1333,6 +1333,26 @@ describe Spree::Payment, type: :model do
describe '#add_gateway_processing_error' do
subject { payment.add_gateway_processing_error('Insufficient balance on payment') }
+ # A payment has no store of its own and reaches one through what it
+ # settles. Resolving through `order` alone left a cart-owned payment
+ # filing its error against whichever store the request named — the
+ # default one in a job.
+ describe 'the store its custom fields are defined in' do
+ let(:other_store) { create(:store) }
+
+ it 'is the order it settles' do
+ order_payment = build(:payment, order: create(:order, store: other_store))
+
+ expect(order_payment.send(:custom_field_definition_store)).to eq(other_store)
+ end
+
+ it 'is the cart it settles while checkout is still open' do
+ cart_payment = build(:payment, order: nil, cart: create(:cart, store: other_store))
+
+ expect(cart_payment.send(:custom_field_definition_store)).to eq(other_store)
+ end
+ end
+
it 'adds a gateway processing error' do
subject
expect(payment.get_custom_field('gateway.processing_errors').value).to eq([{ message: 'Insufficient balance on payment' }].to_json)
diff --git a/spree/core/spec/models/spree/product_type_custom_field_definition_spec.rb b/spree/core/spec/models/spree/product_type_custom_field_definition_spec.rb
index 3bd2c2dd9b..575686d490 100644
--- a/spree/core/spec/models/spree/product_type_custom_field_definition_spec.rb
+++ b/spree/core/spec/models/spree/product_type_custom_field_definition_spec.rb
@@ -27,6 +27,14 @@ RSpec.describe Spree::ProductTypeCustomFieldDefinition, type: :model do
expect(join).not_to be_valid
expect(join.errors[:custom_field_definition]).to include('must be a custom field definition for products')
end
+
+ it 'rejects a definition owned by another store' do
+ foreign = create(:custom_field_definition, store: create(:store))
+ join = build(:product_type_custom_field_definition, product_type: product_type, custom_field_definition: foreign)
+
+ expect(join).not_to be_valid
+ expect(join.errors[:custom_field_definition]).to include('must belong to the same store')
+ end
end
describe 'defaults' do
diff --git a/spree/core/spec/models/spree/product_type_spec.rb b/spree/core/spec/models/spree/product_type_spec.rb
index 52228cbdba..8eb2d63162 100644
--- a/spree/core/spec/models/spree/product_type_spec.rb
+++ b/spree/core/spec/models/spree/product_type_spec.rb
@@ -59,6 +59,17 @@ describe Spree::ProductType, type: :model do
expect(product_type.errors[:custom_field_definitions]).to be_present
end
+ # Definitions are store-owned, so another store's is unknown here rather
+ # than a join that fails silently on save.
+ it 'refuses a definition owned by another store' do
+ foreign = create(:custom_field_definition, store: create(:store), resource_type: 'Spree::Product')
+
+ product_type.update(custom_field_definitions: [{ id: foreign.prefixed_id, required: true }])
+
+ expect(product_type.reload.custom_field_definitions).to eq([existing])
+ expect(product_type.errors[:custom_field_definitions]).to be_present
+ end
+
it 'keeps the existing joins when a definition is not for products' do
order_definition = create(:custom_field_definition, :for_order)
diff --git a/spree/core/spec/models/spree/seller_requirements_spec.rb b/spree/core/spec/models/spree/seller_requirements_spec.rb
index c3beba8504..669c64302a 100644
--- a/spree/core/spec/models/spree/seller_requirements_spec.rb
+++ b/spree/core/spec/models/spree/seller_requirements_spec.rb
@@ -226,6 +226,15 @@ RSpec.describe 'seller requirement kinds', type: :model do
expect(link.errors[:custom_field_definition].join).to match(/defined for sellers/i)
end
+ it 'refuses a field owned by another store' do
+ foreign_field = create(:custom_field_definition, store: create(:store), resource_type: 'Spree::Seller')
+
+ link = requirement.seller_requirement_custom_fields.new(custom_field_definition: foreign_field)
+
+ expect(link).not_to be_valid
+ expect(link.errors[:custom_field_definition].join).to match(/same store/i)
+ end
+
it 'forgets a field the operator deleted rather than asking for it forever' do
definition = create(:custom_field_definition, resource_type: 'Spree::Seller')
requirement.update!(custom_field_definitions: [definition])
diff --git a/spree/core/spec/presenters/spree/csv/customer_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/customer_presenter_spec.rb
index feaf4dee2f..20cefd2629 100644
--- a/spree/core/spec/presenters/spree/csv/customer_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/customer_presenter_spec.rb
@@ -26,7 +26,7 @@ RSpec.describe Spree::CSV::CustomerPresenter do
tag_list: ['premium', 'vip'])
end
let!(:orders) { create_list(:completed_order_with_totals, 3, customer: customer, store: store) }
- let(:presenter) { described_class.new(customer) }
+ let(:presenter) { described_class.new(customer, store) }
before do
orders[0].update_column(:total, 100)
@@ -73,7 +73,7 @@ RSpec.describe Spree::CSV::CustomerPresenter do
accepts_email_marketing: false)
end
- let(:presenter) { described_class.new(customer_without_address) }
+ let(:presenter) { described_class.new(customer_without_address, store) }
it 'returns nil for address fields' do
expect(subject[4]).to be_nil # company
@@ -95,7 +95,7 @@ RSpec.describe Spree::CSV::CustomerPresenter do
last_name: 'Johnson',
end
- let(:presenter) { described_class.new(customer_without_orders) }
+ let(:presenter) { described_class.new(customer_without_orders, store) }
it 'returns zero for total orders and amount spent' do
expect(subject[14]).to eq 0 # amount spent
@@ -153,7 +153,7 @@ RSpec.describe Spree::CSV::CustomerPresenter do
last_name: 'Smith',
end
- let(:presenter) { described_class.new(customer_without_custom_field) }
+ let(:presenter) { described_class.new(customer_without_custom_field, store) }
it 'returns nil for custom_field' do
result = presenter.call
diff --git a/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb
index c5963c1f8f..867d64ac54 100644
--- a/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb
@@ -14,7 +14,7 @@ RSpec.describe Spree::CSV::GiftCardPresenter, type: :model do
user: user,
store: store)
end
- let(:presenter) { described_class.new(gift_card) }
+ let(:presenter) { described_class.new(gift_card, store) }
describe '#call' do
subject { presenter.call }
@@ -88,7 +88,7 @@ RSpec.describe Spree::CSV::GiftCardPresenter, type: :model do
context 'when gift card has no custom_field value' do
let(:gift_card_without_custom_field) { create(:gift_card, store: store) }
- let(:presenter) { described_class.new(gift_card_without_custom_field) }
+ let(:presenter) { described_class.new(gift_card_without_custom_field, store) }
it 'returns nil for custom_field' do
result = presenter.call
diff --git a/spree/core/spec/presenters/spree/csv/newsletter_subscriber_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/newsletter_subscriber_presenter_spec.rb
index 8c41288398..7760729468 100644
--- a/spree/core/spec/presenters/spree/csv/newsletter_subscriber_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/newsletter_subscriber_presenter_spec.rb
@@ -1,6 +1,8 @@
require 'spec_helper'
RSpec.describe Spree::CSV::NewsletterSubscriberPresenter do
+ let(:store) { @default_store }
+
let(:user) do
create(
:user,
@@ -22,7 +24,7 @@ RSpec.describe Spree::CSV::NewsletterSubscriberPresenter do
)
end
- let(:presenter) { described_class.new(newsletter_subscriber) }
+ let(:presenter) { described_class.new(newsletter_subscriber, store) }
describe '#call' do
subject(:row) { presenter.call }
@@ -103,7 +105,7 @@ RSpec.describe Spree::CSV::NewsletterSubscriberPresenter do
create(:newsletter_subscriber,
end
- let(:presenter) { described_class.new(subscriber_without_custom_field) }
+ let(:presenter) { described_class.new(subscriber_without_custom_field, store) }
it 'returns nil for custom_field' do
result = presenter.call
diff --git a/spree/core/spec/services/spree/search_provider/custom_field_schema_spec.rb b/spree/core/spec/services/spree/search_provider/custom_field_schema_spec.rb
index ea6dea9e29..261cc4bdda 100644
--- a/spree/core/spec/services/spree/search_provider/custom_field_schema_spec.rb
+++ b/spree/core/spec/services/spree/search_provider/custom_field_schema_spec.rb
@@ -3,7 +3,9 @@
require 'spec_helper'
RSpec.describe Spree::SearchProvider::CustomFieldSchema do
- subject(:schema) { described_class.new }
+ subject(:schema) { described_class.new(store) }
+
+ let(:store) { @default_store }
describe 'accessors' do
it 'exposes definitions by cf_* key' do
diff --git a/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb
index 3eebd6405c..4422b02099 100644
--- a/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb
+++ b/spree/providers/meilisearch/app/models/spree_meilisearch/search_provider.rb
@@ -101,7 +101,7 @@ module SpreeMeilisearch
def reindex(scope = nil)
full_reindex = scope.nil?
scope ||= store.products
- @custom_field_schema = Spree::SearchProvider::CustomFieldSchema.new
+ @custom_field_schema = Spree::SearchProvider::CustomFieldSchema.new(store)
ensure_index_settings!
# On a full reindex, clear first so stale docs (e.g. membership docs for