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.

Move the media type lists into the engine registry

Damian Legawiece8f5369b6784
diff --git a/CLAUDE.md b/CLAUDE.md
index 349b0f4c9e..a398a5ed87 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -34,7 +34,7 @@ Active plans (6.0 target, work pending):
- `6.0-drop-country-state-models.md` — Delete the `Spree::Country`/`Spree::State` AR models in 6.0 (the tables and legacy FK columns survive to 6.1 as the upgrade task's source data); constants survive as `countries`-gem-backed value objects (carmen removed), consumers store `country_code` + `state_code` strings (always paired — subdivision codes aren't globally unique), Address validation semantics preserved (`STATES_REQUIRED` constants become runtime source of truth). No `id` was ever exposed, so the only v3 changes are the `state_abbr`→`state_code` and `country_iso`→`country_code` renames (Market's list moves `country_isos`→`country_codes`) — `Spree::Address` alone keeps `state_abbr` and `country_iso` as deprecated read/write bridges until 6.1. Amends tax-provider Phase 5 (TaxRate columns born as ISO strings, not FKs) and delivery-zone members. **Shipped (2026-08-14):** value objects live, carmen + country/state seeds + row-creating fallbacks deleted; `Spree::IsoData` curated registry + drift-guard spec, ISO columns on addresses/delivery-zone-members/market-countries/stock-locations/stores with `spree:upgrade:migrate_country_state_codes` in the 5.6→6.0 manifest, every consumer matching on codes, admin FK params closed, country endpoints uncached, factories built from real ISO data. `Spree::Zone`/`ZoneMember` are migration-only shells (no `zoneable` association; the data tasks resolve member ids against the legacy tables via SQL) and drop in 6.1 with the tables. **Constraint now:** no new `country_id`/`state_id` FKs or `belongs_to :country/:state` anywhere — a new model carrying geography declares `has_iso_geography` (`Spree::HasIsoGeography`, on `Spree::Base`; `state: false` for country-only tables) and stores ISO strings in columns named `country_code` + `state_code` — never `country_iso` or `state_abbr`; preference-based rules follow `Promotion::Rules::Country`
- `6.0-integrations-admin.md` — **Implemented (2026-08-06).** `Spree::Integration` as the single credential surface for all provider seams (delivery rates/tax/fulfillment/pickup points): explicit `Spree.integrations` registry, Admin API v3 CRUD + types discovery (reusing `PreferenceSchema`/`Masking` — secrets are `:password` preferences), dashboard `/settings/integrations` gallery grouped by `integration_group`. Verify-before-activate (`active: true` runs `can_connect?`, 422 on failure), ephemeral connection status. Constraints now: provider gems ship an Integration subclass (no env-var credential contracts for per-store providers); no per-provider credential UIs — pickers deep-link to the integrations page.
- `6.0-rich-text-descriptions.md` — Drop ActionText **entirely** at 6.0 (incl. CustomFields::RichText values + Order/User internal notes; gem dependency removed), store sanitized HTML in text columns, serve `field` + `field_html`, **write via `field_html`** (read/write symmetry). description_html serializer shipped 5.4; sanitizer shipped in **5.6.2** with a permissive-but-safe configurable allowlist + `sanitize_rich_text` step in the 5.5→5.6 upgrade manifest (decisions.md 2026-07-27/28), tightened to the Tiptap set at 6.0
-- `6.0-media-library.md` — Store-wide media library over `Spree::Media` (**shipped 2026-08-24**): `store_id` on `spree_media` (backfilled from the viewable's product; upgrade task in the 5.6→6.0 manifest), upload-first unattached rows (`viewable_id: nil`), dashboard library page + picker. **Reuse = blob sharing, never a shared asset entity:** copying to another product duplicates the `Media` row and attaches the same blob (`Media#duplicate_for`; `source_media_id` accepted by BOTH the nested media create and the inline `media:` list on the product — the dashboard Save uses the latter), a copy takes the **target's** store (never the source's — `duplicate_for` leaves `store_id` unset so `SingleStoreResource` reads it from the new owner), bare attachment fields (category/collection/store/seller images) adopt files via the blob's `signed_id` through their unchanged endpoints, and deletion safety rests on the Rails `active_storage_attachments`→blobs FK + `PurgeJob` discard — that FK is load-bearing (the no-FK rule covers Spree tables only), and media paths always `purge_later`, never synchronous `purge`. Rich text editor gains image embedding: Tiptap Image + `img` in `RichTextSanitizer.allowed_tags` land in the SAME change (plain `<img>` URLs to a new non-cropping `embed` rendition; no reference-tracking tables) — `MediaRichTextEditor` is the wired component every description field uses, the bare `RichTextEditor` has no picker. `Spree::Media::Usage` answers "where is this file used" from the blob's attachments plus a best-effort search of `SanitizableRichText.declaring_models`. **Category/Collection are real viewables (2026-08-24):** `Media::VIEWABLE_TYPES` = Product | Variant | Category | Collection (validated allowlist); their `image`/`square_image` slots reconcile into placements via `Spree::HasLibraryMedia` (slots stay the operational storage; clearing a slot UNPLACES the row, never destroys; `spree:upgrade:backfill_library_media_placements` in the manifest) — until a real category gallery exists, reconciliation owns every placement on those records, so never create Media rows on a category by another path. Library `DELETE /admin/media/:id` returns 422 + usage list while the file is in use; `detach=true` runs `Spree::Media::Destroy` (removes it from every placement + plain attachment in its store, then purges) — the dashboard sends it after a confirmation. Only the nested gallery destroy removes a single placement. Sellers/stores stay bare attachments (branding, not merchandising). **Constraints now:** no attachment-style join tables onto `Media` (a new context gets its own row sharing the blob); don't add `img` to the sanitizer ahead of the editor node; a new media write path must accept `source_media_id` or reuse silently drops on it; a new viewable type joins `VIEWABLE_TYPES` deliberately, never by writing the polymorphic column.
+- `6.0-media-library.md` — Store-wide media library over `Spree::Media` (**shipped 2026-08-24**): `store_id` on `spree_media` (backfilled from the viewable's product; upgrade task in the 5.6→6.0 manifest), upload-first unattached rows (`viewable_id: nil`), dashboard library page + picker. **Reuse = blob sharing, never a shared asset entity:** copying to another product duplicates the `Media` row and attaches the same blob (`Media#duplicate_for`; `source_media_id` accepted by BOTH the nested media create and the inline `media:` list on the product — the dashboard Save uses the latter), a copy takes the **target's** store (never the source's — `duplicate_for` leaves `store_id` unset so `SingleStoreResource` reads it from the new owner), bare attachment fields (category/collection/store/seller images) adopt files via the blob's `signed_id` through their unchanged endpoints, and deletion safety rests on the Rails `active_storage_attachments`→blobs FK + `PurgeJob` discard — that FK is load-bearing (the no-FK rule covers Spree tables only), and media paths always `purge_later`, never synchronous `purge`. Rich text editor gains image embedding: Tiptap Image + `img` in `RichTextSanitizer.allowed_tags` land in the SAME change (plain `<img>` URLs to a new non-cropping `embed` rendition; no reference-tracking tables) — `MediaRichTextEditor` is the wired component every description field uses, the bare `RichTextEditor` has no picker. `Spree::Media::Usage` answers "where is this file used" from the blob's attachments plus a best-effort search of `SanitizableRichText.declaring_models`. **Category/Collection are real viewables (2026-08-24):** `Spree.media_viewable_types` = Product | Variant | Category | Collection (engine registry, append from an initializer); their `image`/`square_image` slots reconcile into placements via `Spree::HasLibraryMedia` (slots stay the operational storage; clearing a slot UNPLACES the row, never destroys; `spree:upgrade:backfill_library_media_placements` in the manifest) — until a real category gallery exists, reconciliation owns every placement on those records, so never create Media rows on a category by another path. Library `DELETE /admin/media/:id` returns 422 + usage list while the file is in use; `detach=true` runs `Spree::Media::Destroy` (removes it from every placement + plain attachment in its store, then purges) — the dashboard sends it after a confirmation. Only the nested gallery destroy removes a single placement. Sellers/stores stay bare attachments (branding, not merchandising). **Constraints now:** no attachment-style join tables onto `Media` (a new context gets its own row sharing the blob); don't add `img` to the sanitizer ahead of the editor node; a new media write path must accept `source_media_id` or reuse silently drops on it; a new viewable type is appended to `Spree.media_viewable_types` deliberately, never by writing the polymorphic column; embedding is opt-in per editor in the dashboard (`MediaRichTextEditor`), never a server-side model list.
- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (the procurement source; `Spree::Seller` is the marketplace seller — see decisions.md 2026-07-14 and 2026-08-17) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.
- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.
- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). **Phase 1 shipped** (rules + Estimator seam + admin nested CRUD/types discovery + dashboard Conditions card). **2026-08-06:** `ExcludedProductsRule` (products via `spree_delivery_method_rule_products` join, Saleor-style method-side exclusion) replaces the dropped `spree_products.excluded_delivery_method_ids` JSON column; rule-reference storage picks by cardinality — small reference sets stay `normalize_id_preference` arrays, catalog-scale (products) gets a join table.
diff --git a/docs/plans/6.0-media-library.md b/docs/plans/6.0-media-library.md
index 539c558daa..0fde414a94 100644
--- a/docs/plans/6.0-media-library.md
+++ b/docs/plans/6.0-media-library.md
@@ -72,8 +72,8 @@ the storage level.
(`has_library_media :image, :square_image` on both models) creates `Media`
rows with `viewable: category` sharing the slot blobs on save, and clearing a
slot **unplaces** the row (back to the library pool) rather than destroying
- it — destroying would take the file with it. `Media::VIEWABLE_TYPES` is now a
- validated allowlist (Product, Variant, Category, Collection); `ensure_store`
+ it — destroying would take the file with it. `Spree.media_viewable_types` is now a
+ registry (Product, Variant, Category, Collection); `ensure_store`
reads the viewable's own store first. The named `image`/`square_image`
attachments remain the operational storage every existing serializer and
storefront reads; the placements are the library's view of them, and the
@@ -250,9 +250,10 @@ grid reuses the existing small/thumbnail renditions.
- `Spree::Media::Usage` must stay store-scoped on every one of its three sources
(attachments, placements, rich text) — a blob can be shared, but a file's
reported uses are its own store's rows.
-- Rich text search covers content models only (`CONTENT_MODELS`); never add
- `Spree::Order` or a customer to it. Internal notes are staff correspondence
- on the two largest tables, and the search is an unindexed `LIKE`.
+- Which editors can embed a file is a dashboard decision: `MediaRichTextEditor`
+ is opt-in per call site and only product, category and collection
+ descriptions use it. The usage search covers every model declaring rich text
+ rather than restating that list on the server.
- A controller action outside `index`/`show` needs its CanCanCan action mapped
as well as its key scope declared: `read_actions` settles the API-key gate,
but the `:read` alias covers only those two, so a custom read action refuses
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 216fced2fa..23c2879b42 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -3654,7 +3654,7 @@ the endpoint left the picker silently dropping its files. A new media write
path must accept it or reuse breaks on that path alone.
Live use then reshaped two boundaries. **Category and Collection are real
-Media viewables** (`Media::VIEWABLE_TYPES` allowlist: Product, Variant,
+Media viewables** (`Spree.media_viewable_types` registry: Product, Variant,
Category, Collection): their `image`/`square_image` slots reconcile into
placements via `Spree::HasLibraryMedia` on save — the slots stay the
operational storage, the placements are the library's view, clearing a slot
diff --git a/spree/core/app/models/spree/media.rb b/spree/core/app/models/spree/media.rb
index faa5eb1d7e..1800bea3cf 100644
--- a/spree/core/app/models/spree/media.rb
+++ b/spree/core/app/models/spree/media.rb
@@ -30,14 +30,6 @@ module Spree
EXTERNAL_URL_CUSTOM_FIELD_KEY = 'external.url'
MEDIA_TYPES = %w[image video external_video].freeze
- # What a file can be placed on. Product and Variant carry galleries;
- # Category and Collection place their image slots here so the library sees
- # them (a future category gallery is additive rows on the same
- # association). An allowlist because the column is polymorphic: without it
- # any constant name could be written, and everything downstream — store
- # resolution, counters, the usage panel — reasons about the known set.
- VIEWABLE_TYPES = %w[Spree::Product Spree::Variant Spree::Category Spree::Collection].freeze
-
# Domain attributes a client may write, shared by every write path — the
# media endpoints and the inline `media:` list on a product. Each path adds
# its own transport keys (an upload's signed id, a row id) on top. Adding a
@@ -103,14 +95,10 @@ module Spree
delegate :key, :attached?, :variant, :variable?, :blob, :filename, :variation, to: :attachment
- # Additive for extensions placing media on their own models, like
- # additional_permitted_attributes: always `+=`, never `=`.
- #
- # Spree::Media.viewable_types += ['MyApp::Lookbook']
- class_attribute :viewable_types, instance_writer: false, default: VIEWABLE_TYPES
-
validates :media_type, inclusion: { in: MEDIA_TYPES }
- validates :viewable_type, inclusion: { in: ->(record) { record.class.viewable_types } },
+ # Registered in Spree.media_viewable_types — an extension placing media on
+ # its own model appends there rather than editing this list.
+ validates :viewable_type, inclusion: { in: -> (_record) { Spree.media_viewable_types } },
allow_nil: true
validates :attachment, attached: true, content_type: Rails.application.config.active_storage.web_image_content_types,
if: :image?
@@ -357,8 +345,12 @@ module Spree
# is for: media follows the thing it is a picture of. A library upload has
# no viewable yet, so it falls back to the concern's current-store default.
def ensure_store
+ # An unregistered viewable_type raises on load rather than reaching the
+ # inclusion validation, which is the thing that should reject it.
self.store_id = viewable.try(:store_id) || product&.store_id
super unless store_id?
+ rescue NameError
+ super
end
private
diff --git a/spree/core/app/services/spree/media/usage.rb b/spree/core/app/services/spree/media/usage.rb
index 2ba52a60c1..673740a744 100644
--- a/spree/core/app/services/spree/media/usage.rb
+++ b/spree/core/app/services/spree/media/usage.rb
@@ -114,30 +114,20 @@ module Spree
# almost certainly embedding that file. Searched with LIKE, which no index
# can serve — a deliberate cost paid on one admin screen, never in a
# listing, and only over the store's own rows.
+ #
+ # Every model declaring rich text is searched. Which editors can embed a
+ # file is the dashboard's decision — only the product, category and
+ # collection descriptions use the picker-backed editor — so a second
+ # list here would only restate that, and go stale when it changes.
def rich_text_references(media, blob_ids)
keys = ActiveStorage::Blob.where(id: blob_ids).pluck(:key)
return [] if keys.empty?
- searchable_models.flat_map do |model, attributes|
+ Spree::SanitizableRichText.declaring_models.flat_map do |model, attributes|
attributes.flat_map { |attribute| rich_text_matches(media, model, attribute, keys) }
end
end
- # Rich text a merchant writes about their catalog, which is where an
- # embedded library image can plausibly appear.
- #
- # Deliberately not every model declaring rich text: an internal note on an
- # order or a customer is staff correspondence, not content, and those are
- # the two largest tables in the schema — scanning them unindexed on an
- # admin click costs far more than the answer is worth.
- def searchable_models
- Spree::SanitizableRichText.declaring_models.select do |model, _attributes|
- CONTENT_MODELS.include?(model.name)
- end
- end
-
- CONTENT_MODELS = %w[Spree::Product Spree::Category Spree::Collection Spree::Seller].freeze
-
def rich_text_matches(media, model, attribute, keys)
return [] unless model.column_names.include?(attribute)
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 54c672648a..0ba1a358f3 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -299,6 +299,24 @@ module Spree
Rails.application.config.spree.adjusters = value
end
+ # Model names a {Spree::Media} row may be placed on — where a file *lives*.
+ # The viewable column is polymorphic, so this is what keeps it from accepting
+ # any constant, and what store resolution, counter caches and the usage panel
+ # reason about.
+ #
+ # Append, never assign, so an extension does not drop what another added:
+ #
+ # Spree.media_viewable_types += ['MyApp::Lookbook']
+ #
+ # @return [Array<String>]
+ def self.media_viewable_types
+ Rails.application.config.spree.media_viewable_types
+ end
+
+ def self.media_viewable_types=(value)
+ Rails.application.config.spree.media_viewable_types = value
+ end
+
# The tax engine used when a market names none — the fallback behind
# {Spree::Purchase::Taxation#tax_provider}, which is what call sites actually
# use. Defaults to {Spree::TaxProvider::Internal}.
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index c112f7ac13..1c7ccae924 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -10,6 +10,7 @@ module Spree
:dependencies,
:payment_methods,
:adjusters,
+ :media_viewable_types,
:default_tax_provider,
:tax_providers,
:password_validator,
@@ -223,6 +224,19 @@ module Spree
Spree::Adjusters::Promotion
]
+ # What a media file can be placed on. The polymorphic viewable column
+ # would otherwise accept any constant name, and everything downstream —
+ # store resolution, counter caches, the usage panel — reasons about the
+ # registered set. An extension placing media on its own model appends
+ # to this from an initializer.
+ Rails.application.config.spree.media_viewable_types = %w[
+ Spree::Product
+ Spree::Variant
+ Spree::Category
+ Spree::Collection
+ ]
+
+
# The fallback engine when a market names none (see docs/plans/6.0-tax-provider.md).
# Assigned only if an initializer file has not already named one — an app
# that picks its own default must keep it.
diff --git a/spree/core/spec/models/spree/media_spec.rb b/spree/core/spec/models/spree/media_spec.rb
index db78d84c6e..2c16939952 100644
--- a/spree/core/spec/models/spree/media_spec.rb
+++ b/spree/core/spec/models/spree/media_spec.rb
@@ -74,6 +74,36 @@ describe Spree::Media, type: :model do
end
end
+ describe 'viewable types' do
+ def media_on(type)
+ build(:image, viewable: nil).tap do |media|
+ media.viewable_type = type
+ media.viewable_id = 1
+ end
+ end
+
+ # The polymorphic column would otherwise accept any constant name, and an
+ # unknown one raises on load rather than reaching this validation.
+ it 'rejects a type that is not registered' do
+ media = media_on('Nope::Model')
+
+ expect(media).not_to be_valid
+ expect(media.errors[:viewable_type]).to be_present
+ end
+
+ it 'accepts a type an extension registered' do
+ original = Spree.media_viewable_types
+ Spree.media_viewable_types += ['MyApp::Lookbook']
+
+ media = media_on('MyApp::Lookbook')
+ media.valid?
+
+ expect(media.errors[:viewable_type]).to be_empty
+ ensure
+ Spree.media_viewable_types = original
+ end
+ end
+
describe 'a row that predates the store column' do
# Between db:migrate and spree:upgrade:backfill_media_store_ids every
# existing row carries nil. Editing one must not fail validation.
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index 31a3bead60..15ab0218c3 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -644,10 +644,10 @@ describe Spree::Product, type: :model do
# An extension placing media on its own model registers the type; the
# allowlist rejects unregistered constants.
around do |example|
- original = Spree::Media.viewable_types
- Spree::Media.viewable_types += ['ThirdParty::Extension']
+ original = Spree.media_viewable_types
+ Spree.media_viewable_types += ['ThirdParty::Extension']
example.run
- Spree::Media.viewable_types = original
+ Spree.media_viewable_types = original
end
before do