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.

Namespace the media services under Spree::Media

Damian Legawiec8bd842e05b17
diff --git a/CLAUDE.md b/CLAUDE.md
index 09174b595a..349b0f4c9e 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::MediaUsage` 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::MediaDeletion` (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):** `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-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 9eef6dc524..539c558daa 100644
--- a/docs/plans/6.0-media-library.md
+++ b/docs/plans/6.0-media-library.md
@@ -89,7 +89,7 @@ the storage level.
from "refuse until the merchant clears each use"). `DELETE /admin/media/:id`
on a file in use returns 422 with the usage list; passing `detach=true` —
which the dashboard sends after a confirmation naming the count — runs
- `Spree::MediaDeletion`, removing the file from every placement and plain
+ `Spree::Media::Destroy`, removing the file from every placement and plain
attachment in its store, then deleting the row so the blob purges. Clearing
each use by hand was busywork the usage list already knew how to do; the
refusal survives as the default so an API client cannot pull a file out from
@@ -185,7 +185,7 @@ the storage level.
Blob-level usage lookup (for the delete flow and the media detail panel): given
a row, find all `active_storage_attachments` sharing its blob ids, resolve to
owner records, and present them grouped. This is a read-side service —
-`Spree::MediaUsage` — not columns.
+`Spree::Media::Usage` — not columns.
### Admin API
@@ -247,7 +247,7 @@ grid reuses the existing small/thumbnail renditions.
- Never strip or "align" the `active_storage_attachments` → blobs foreign key
with the no-FK convention — blob-sharing deletion safety depends on it.
-- `Spree::MediaUsage` must stay store-scoped on every one of its three sources
+- `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
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 39c78de1fe..216fced2fa 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -3663,7 +3663,7 @@ rows on the same association. Until that gallery exists, reconciliation owns
every placement on these records. Sellers and stores stay bare attachments —
branding, not merchandising media. And **library delete detaches on
confirmation**: a file in use returns 422 with its usage list, and
-`detach=true` runs `Spree::MediaDeletion` — removing it from every placement
+`detach=true` runs `Spree::Media::Destroy` — removing it from every placement
and plain attachment in its store, then deleting the row so the blob purges.
The refusal stays the default so an API client cannot pull a file out from
under a catalog by accident; only the nested gallery destroy removes a single
@@ -3672,7 +3672,7 @@ placement.
Review then caught two tenancy holes worth stating as rules. `acts_as_list`
needed `store_id` in its scope: an unplaced library row has no viewable, so
without it every store's uploads shared one list and their positions bled
-across tenants. And `Spree::MediaUsage` had to scope all three of its sources
+across tenants. And `Spree::Media::Usage` had to scope all three of its sources
to the file's own store — a shared blob reaches other tenants' records, and
reporting them named another store's data to a merchant who cannot see it
anywhere else; its rich text search covers content models only, never order or
diff --git a/spree/api/app/controllers/spree/api/v3/admin/media_library_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/media_library_controller.rb
index 4a2beed8c7..f36a47f58e 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/media_library_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/media_library_controller.rb
@@ -28,7 +28,7 @@ module Spree
# product's gallery is the nested endpoint's destroy, which stays
# unguarded: that is removing a placement, not the file.
def destroy
- references = Spree::MediaUsage.call(media: @resource).value
+ references = Spree::Media::Usage.call(media: @resource).value
return super if references.empty?
unless detach_requested?
@@ -43,7 +43,7 @@ module Spree
)
end
- result = Spree::MediaDeletion.call(media: @resource)
+ result = Spree::Media::Destroy.call(media: @resource)
return head :no_content if result.success?
render_service_error(result.error)
@@ -53,7 +53,7 @@ module Spree
# plain image fields sharing it, and descriptions embedding it. What
# the dashboard shows before a merchant deletes something.
def usage
- references = Spree::MediaUsage.call(media: @resource).value
+ references = Spree::Media::Usage.call(media: @resource).value
render json: { data: references.map { |reference| reference_payload(reference) } }
end
diff --git a/spree/core/app/models/spree/media_usage_reference.rb b/spree/core/app/models/spree/media_usage_reference.rb
index 6ee66392f0..ac97ad7dec 100644
--- a/spree/core/app/models/spree/media_usage_reference.rb
+++ b/spree/core/app/models/spree/media_usage_reference.rb
@@ -1,6 +1,6 @@
module Spree
# One place a media file is in use. Ephemeral — computed by
- # +Spree::MediaUsage+ from the blob's attachment rows, never persisted.
+ # +Spree::Media::Usage+ from the blob's attachment rows, never persisted.
#
# A file is "in use" more broadly than a media row suggests: reusing a file
# on another product shares its blob, and so does picking it for a category
diff --git a/spree/core/app/services/spree/media/destroy.rb b/spree/core/app/services/spree/media/destroy.rb
new file mode 100644
index 0000000000..f6535e66b2
--- /dev/null
+++ b/spree/core/app/services/spree/media/destroy.rb
@@ -0,0 +1,82 @@
+module Spree
+ class Media
+ # Deletes a library file everywhere at once: every placement sharing its
+ # blob, every plain attachment (a category image slot, a store logo)
+ # holding it, then the row itself — whose purge takes the blob with it once
+ # nothing references it. The alternative was refusing until the merchant
+ # cleared each use by hand, which is busywork the usage list already knows
+ # how to do.
+ #
+ # Scoped to the file's own store: a blob another tenant happens to share
+ # keeps their attachments, and the foreign key keeps the file in storage
+ # for them. Rich text embeds are plain URLs with nothing to detach — those
+ # descriptions lose the image, which is what the caller's confirmation
+ # acknowledged.
+ class Destroy
+ prepend Spree::ServiceModule::Base
+
+ # @param media [Spree::Media] the library row being deleted
+ # @return [Spree::ServiceModule::Result]
+ def call(media:)
+ blob_ids = [media.attachment_blob&.id, media.poster_blob&.id].compact
+
+ # Detaching is collected inside the transaction and enqueued after it
+ # commits: purge_later hands the file to a worker that may run before
+ # the transaction ends, so a rollback would leave the rows intact with
+ # their file already gone.
+ detachable = nil
+
+ ApplicationRecord.transaction do
+ destroy_placements(media, blob_ids)
+ detachable = plain_attachments(media, blob_ids)
+ media.destroy!
+ end
+
+ # ActiveRecord::Rollback is swallowed by the transaction block, so a
+ # surviving row is how a rolled-back delete reports itself. Detaching
+ # then would strip the file from records the delete did not remove.
+ return failure(media) if media.persisted?
+
+ detachable.each(&:purge_later)
+
+ success(media)
+ end
+
+ private
+
+ # Other rows sharing the file — placements on products, categories,
+ # collections. destroy, not delete: the callbacks are what refresh the
+ # owners' thumbnails and counters.
+ def destroy_placements(media, blob_ids)
+ return if blob_ids.empty?
+
+ Spree::Media
+ .where(store_id: media.store_id)
+ .where.not(id: media.id)
+ .joins(:attachment_attachment)
+ .where(ActiveStorage::Attachment.table_name => { blob_id: blob_ids })
+ .find_each(&:destroy!)
+ end
+
+ # The plain attachments this store holds on the file — a category image
+ # slot, a store logo. Media rows are handled by destroy_placements.
+ #
+ # @return [Array<ActiveStorage::Attachment>]
+ def plain_attachments(media, blob_ids)
+ ActiveStorage::Attachment.where(blob_id: blob_ids).select do |attachment|
+ owner = attachment.record
+ next false if owner.blank? || owner.is_a?(Spree::Media)
+
+ owned_by_store?(owner, media.store_id)
+ end
+ end
+
+ # Same rule as Spree::Media::Usage: a record that carries no store at all
+ # (the store itself) is this store's to manage.
+ def owned_by_store?(owner, store_id)
+ owner_store_id = owner.try(:store_id)
+ owner_store_id.blank? || owner_store_id == store_id
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/media/usage.rb b/spree/core/app/services/spree/media/usage.rb
new file mode 100644
index 0000000000..6e1e5fb021
--- /dev/null
+++ b/spree/core/app/services/spree/media/usage.rb
@@ -0,0 +1,186 @@
+module Spree
+ class Media
+ # Answers "what breaks if I delete this file" for the media library.
+ #
+ # Reuse in Spree shares the underlying blob rather than copying the file, so
+ # the question is about the blob, not about this row: the same file may be
+ # placed on several products and picked for a category or store image, and
+ # deleting one placement leaves the others working. This walks the blob's
+ # attachments to list every one of them.
+ #
+ # Rich text embeds are found separately and only approximately — an embedded
+ # image is a plain URL in stored markup, with no row tying it to the file —
+ # so a description referencing this blob's key is reported as a use, and
+ # markup that reaches the file some other way (a CDN alias, a copied URL from
+ # another environment) is not found at all. Treat the rich text half as a
+ # warning worth showing, never as proof a file is unused.
+ class Usage
+ prepend Spree::ServiceModule::Base
+
+ # @param media [Spree::Media] the library row being inspected
+ # @return [Array<Spree::MediaUsageReference>] every known use of its file
+ def call(media:)
+ blob_ids = [media.attachment_blob&.id, media.poster_blob&.id].compact
+ return success([]) if blob_ids.empty?
+
+ success(attachment_references(media, blob_ids) + rich_text_references(media, blob_ids))
+ end
+
+ private
+
+ # Every record whose attachment points at one of these blobs, minus
+ # anything belonging to another store — none of this store's business even
+ # when the two happen to share a file.
+ #
+ # The inspected row's own placement counts: the library shows a file, not a
+ # placement, so "where is this used" plainly includes the product it sits
+ # on. Leaving it out reported "not used anywhere else" about a file that is
+ # on a product, which is worst in the case the panel exists for — deciding
+ # whether deleting it is safe.
+ # One place can be reachable more than once — a video's file and poster
+ # are two blobs on one row, and a category holds a file both as its image
+ # slot and as the slot's library placement — hence the collapse to one
+ # reference per owner, preferring the placement, which is the library's
+ # own representation of the use and what the dashboard links.
+ def attachment_references(media, blob_ids)
+ # `record` is polymorphic, so preload it per type — reading it row by row
+ # is a query each, and a widely-reused file has many rows. Media owners
+ # additionally need their viewable, which build_reference reads.
+ attachments = ActiveStorage::Attachment.where(blob_id: blob_ids).to_a
+ owners = preloaded_owners(attachments)
+
+ references = attachments.filter_map do |attachment|
+ owner = owners[[attachment.record_type, attachment.record_id]]
+ next if owner.blank?
+ next unless owned_by_store?(owner, media.store_id)
+
+ build_reference(owner, attachment.name)
+ end
+
+ references
+ .group_by { |reference| [reference.owner_type, reference.owner_id] }
+ .map { |_owner, group| group.find { |reference| reference.kind == 'media' } || group.first }
+ end
+
+ # @return [Hash{Array(String, Integer) => ActiveRecord::Base}] owners by [type, id]
+ def preloaded_owners(attachments)
+ attachments.group_by(&:record_type).each_with_object({}) do |(type, rows), owners|
+ model = type.safe_constantize
+ next if model.blank?
+
+ scope = model.all
+ # A media owner's own viewable is what build_reference reports.
+ scope = scope.includes(:viewable) if model <= Spree::Media
+
+ scope.where(id: rows.map(&:record_id)).each do |record|
+ owners[[type, record.id]] = record
+ end
+ end
+ end
+
+ # A record is this store's if it says so. One that carries no store at all
+ # (the store record itself, a global) is reported — it is not another
+ # tenant's data.
+ def owned_by_store?(owner, store_id)
+ owner_store_id = owner.try(:store_id)
+ return true if owner_store_id.blank?
+
+ owner_store_id == store_id
+ end
+
+ def build_reference(owner, field)
+ if owner.is_a?(Spree::Media)
+ placement = owner.viewable
+ return if placement.blank?
+
+ Spree::MediaUsageReference.new(
+ kind: 'media',
+ name: display_name(placement),
+ owner_type: placement.class.name,
+ owner_id: placement.try(:prefixed_id),
+ field: field
+ )
+ else
+ Spree::MediaUsageReference.new(
+ kind: 'attachment',
+ name: display_name(owner),
+ owner_type: owner.class.name,
+ owner_id: owner.try(:prefixed_id),
+ field: field
+ )
+ end
+ end
+
+ # Blob keys are opaque and unique, so a description containing one is
+ # 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.
+ 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|
+ 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)
+
+ column = model.arel_table[attribute]
+ condition = keys.map { |key| column.matches("%#{key}%") }.reduce(:or)
+
+ scope_to_store(media, model).where(condition).limit(MATCH_LIMIT).map do |record|
+ Spree::MediaUsageReference.new(
+ kind: 'rich_text',
+ name: display_name(record),
+ owner_type: record.class.name,
+ owner_id: record.try(:prefixed_id),
+ field: attribute
+ )
+ end
+ rescue ActiveRecord::StatementInvalid
+ # A declared rich text attribute that isn't a plain searchable column
+ # (a Mobility-backed field on some adapters) should not take the whole
+ # usage panel down with it.
+ []
+ end
+
+ # A file belongs to one store, so its uses are that store's rows. Without
+ # this the panel would report — and name — records from every other tenant.
+ def scope_to_store(media, model)
+ return model.all unless model.column_names.include?('store_id')
+
+ model.where(store_id: media.store_id)
+ end
+
+ # Enough to tell a merchant "this is in use, here's where"; listing every
+ # match on a catalog-wide embed would be a scan with no added meaning.
+ MATCH_LIMIT = 25
+
+ def display_name(record)
+ %i[name title number email].each do |attribute|
+ value = record.try(attribute)
+ return value if value.present?
+ end
+
+ "#{record.class.name.demodulize} ##{record.id}"
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/media_deletion.rb b/spree/core/app/services/spree/media_deletion.rb
deleted file mode 100644
index a27c4c1e4c..0000000000
--- a/spree/core/app/services/spree/media_deletion.rb
+++ /dev/null
@@ -1,79 +0,0 @@
-module Spree
- # Deletes a library file everywhere at once: every placement sharing its
- # blob, every plain attachment (a category image slot, a store logo) holding
- # it, then the row itself — whose purge takes the blob with it once nothing
- # references it. The alternative was refusing until the merchant cleared
- # each use by hand, which is busywork the usage list already knows how to do.
- #
- # Scoped to the file's own store: a blob another tenant happens to share
- # keeps their attachments, and the foreign key keeps the file in storage for
- # them. Rich text embeds are plain URLs with nothing to detach — those
- # descriptions lose the image, which is what the caller's confirmation
- # acknowledged.
- class MediaDeletion
- prepend Spree::ServiceModule::Base
-
- # @param media [Spree::Media] the library row being deleted
- # @return [Spree::ServiceModule::Result]
- def call(media:)
- blob_ids = [media.attachment_blob&.id, media.poster_blob&.id].compact
-
- # Detaching is collected inside the transaction and enqueued after it
- # commits: purge_later hands the file to a worker that may run before
- # the transaction ends, so a rollback would leave the rows intact with
- # their file already gone.
- detachable = nil
-
- ApplicationRecord.transaction do
- destroy_placements(media, blob_ids)
- detachable = plain_attachments(media, blob_ids)
- media.destroy!
- end
-
- # ActiveRecord::Rollback is swallowed by the transaction block, so a
- # surviving row is how a rolled-back delete reports itself. Detaching
- # then would strip the file from records the delete did not remove.
- return failure(media) if media.persisted?
-
- detachable.each(&:purge_later)
-
- success(media)
- end
-
- private
-
- # Other rows sharing the file — placements on products, categories,
- # collections. destroy, not delete: the callbacks are what refresh the
- # owners' thumbnails and counters.
- def destroy_placements(media, blob_ids)
- return if blob_ids.empty?
-
- Spree::Media
- .where(store_id: media.store_id)
- .where.not(id: media.id)
- .joins(:attachment_attachment)
- .where(ActiveStorage::Attachment.table_name => { blob_id: blob_ids })
- .find_each(&:destroy!)
- end
-
- # The plain attachments this store holds on the file — a category image
- # slot, a store logo. Media rows are handled by destroy_placements.
- #
- # @return [Array<ActiveStorage::Attachment>]
- def plain_attachments(media, blob_ids)
- ActiveStorage::Attachment.where(blob_id: blob_ids).select do |attachment|
- owner = attachment.record
- next false if owner.blank? || owner.is_a?(Spree::Media)
-
- owned_by_store?(owner, media.store_id)
- end
- end
-
- # Same rule as Spree::MediaUsage: a record that carries no store at all
- # (the store itself) is this store's to manage.
- def owned_by_store?(owner, store_id)
- owner_store_id = owner.try(:store_id)
- owner_store_id.blank? || owner_store_id == store_id
- end
- end
-end
diff --git a/spree/core/app/services/spree/media_usage.rb b/spree/core/app/services/spree/media_usage.rb
deleted file mode 100644
index c31a85fd45..0000000000
--- a/spree/core/app/services/spree/media_usage.rb
+++ /dev/null
@@ -1,184 +0,0 @@
-module Spree
- # Answers "what breaks if I delete this file" for the media library.
- #
- # Reuse in Spree shares the underlying blob rather than copying the file, so
- # the question is about the blob, not about this row: the same file may be
- # placed on several products and picked for a category or store image, and
- # deleting one placement leaves the others working. This walks the blob's
- # attachments to list every one of them.
- #
- # Rich text embeds are found separately and only approximately — an embedded
- # image is a plain URL in stored markup, with no row tying it to the file —
- # so a description referencing this blob's key is reported as a use, and
- # markup that reaches the file some other way (a CDN alias, a copied URL from
- # another environment) is not found at all. Treat the rich text half as a
- # warning worth showing, never as proof a file is unused.
- class MediaUsage
- prepend Spree::ServiceModule::Base
-
- # @param media [Spree::Media] the library row being inspected
- # @return [Array<Spree::MediaUsageReference>] every known use of its file
- def call(media:)
- blob_ids = [media.attachment_blob&.id, media.poster_blob&.id].compact
- return success([]) if blob_ids.empty?
-
- success(attachment_references(media, blob_ids) + rich_text_references(media, blob_ids))
- end
-
- private
-
- # Every record whose attachment points at one of these blobs, minus
- # anything belonging to another store — none of this store's business even
- # when the two happen to share a file.
- #
- # The inspected row's own placement counts: the library shows a file, not a
- # placement, so "where is this used" plainly includes the product it sits
- # on. Leaving it out reported "not used anywhere else" about a file that is
- # on a product, which is worst in the case the panel exists for — deciding
- # whether deleting it is safe.
- # One place can be reachable more than once — a video's file and poster
- # are two blobs on one row, and a category holds a file both as its image
- # slot and as the slot's library placement — hence the collapse to one
- # reference per owner, preferring the placement, which is the library's
- # own representation of the use and what the dashboard links.
- def attachment_references(media, blob_ids)
- # `record` is polymorphic, so preload it per type — reading it row by row
- # is a query each, and a widely-reused file has many rows. Media owners
- # additionally need their viewable, which build_reference reads.
- attachments = ActiveStorage::Attachment.where(blob_id: blob_ids).to_a
- owners = preloaded_owners(attachments)
-
- references = attachments.filter_map do |attachment|
- owner = owners[[attachment.record_type, attachment.record_id]]
- next if owner.blank?
- next unless owned_by_store?(owner, media.store_id)
-
- build_reference(owner, attachment.name)
- end
-
- references
- .group_by { |reference| [reference.owner_type, reference.owner_id] }
- .map { |_owner, group| group.find { |reference| reference.kind == 'media' } || group.first }
- end
-
- # @return [Hash{Array(String, Integer) => ActiveRecord::Base}] owners by [type, id]
- def preloaded_owners(attachments)
- attachments.group_by(&:record_type).each_with_object({}) do |(type, rows), owners|
- model = type.safe_constantize
- next if model.blank?
-
- scope = model.all
- # A media owner's own viewable is what build_reference reports.
- scope = scope.includes(:viewable) if model <= Spree::Media
-
- scope.where(id: rows.map(&:record_id)).each do |record|
- owners[[type, record.id]] = record
- end
- end
- end
-
- # A record is this store's if it says so. One that carries no store at all
- # (the store record itself, a global) is reported — it is not another
- # tenant's data.
- def owned_by_store?(owner, store_id)
- owner_store_id = owner.try(:store_id)
- return true if owner_store_id.blank?
-
- owner_store_id == store_id
- end
-
- def build_reference(owner, field)
- if owner.is_a?(Spree::Media)
- placement = owner.viewable
- return if placement.blank?
-
- Spree::MediaUsageReference.new(
- kind: 'media',
- name: display_name(placement),
- owner_type: placement.class.name,
- owner_id: placement.try(:prefixed_id),
- field: field
- )
- else
- Spree::MediaUsageReference.new(
- kind: 'attachment',
- name: display_name(owner),
- owner_type: owner.class.name,
- owner_id: owner.try(:prefixed_id),
- field: field
- )
- end
- end
-
- # Blob keys are opaque and unique, so a description containing one is
- # 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.
- 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|
- 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)
-
- column = model.arel_table[attribute]
- condition = keys.map { |key| column.matches("%#{key}%") }.reduce(:or)
-
- scope_to_store(media, model).where(condition).limit(MATCH_LIMIT).map do |record|
- Spree::MediaUsageReference.new(
- kind: 'rich_text',
- name: display_name(record),
- owner_type: record.class.name,
- owner_id: record.try(:prefixed_id),
- field: attribute
- )
- end
- rescue ActiveRecord::StatementInvalid
- # A declared rich text attribute that isn't a plain searchable column
- # (a Mobility-backed field on some adapters) should not take the whole
- # usage panel down with it.
- []
- end
-
- # A file belongs to one store, so its uses are that store's rows. Without
- # this the panel would report — and name — records from every other tenant.
- def scope_to_store(media, model)
- return model.all unless model.column_names.include?('store_id')
-
- model.where(store_id: media.store_id)
- end
-
- # Enough to tell a merchant "this is in use, here's where"; listing every
- # match on a catalog-wide embed would be a scan with no added meaning.
- MATCH_LIMIT = 25
-
- def display_name(record)
- %i[name title number email].each do |attribute|
- value = record.try(attribute)
- return value if value.present?
- end
-
- "#{record.class.name.demodulize} ##{record.id}"
- end
- end
-end
diff --git a/spree/core/spec/services/spree/media_deletion_spec.rb b/spree/core/spec/services/spree/media/destroy_spec.rb
similarity index 98%
rename from spree/core/spec/services/spree/media_deletion_spec.rb
rename to spree/core/spec/services/spree/media/destroy_spec.rb
index 34b0e47fe7..aa07df8df5 100644
--- a/spree/core/spec/services/spree/media_deletion_spec.rb
+++ b/spree/core/spec/services/spree/media/destroy_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::MediaDeletion do
+describe Spree::Media::Destroy do
let(:product) { create(:product) }
let(:media) { create(:image, viewable: product) }
diff --git a/spree/core/spec/services/spree/media_usage_spec.rb b/spree/core/spec/services/spree/media/usage_spec.rb
similarity index 99%
rename from spree/core/spec/services/spree/media_usage_spec.rb
rename to spree/core/spec/services/spree/media/usage_spec.rb
index b0f11e1aed..4d98003430 100644
--- a/spree/core/spec/services/spree/media_usage_spec.rb
+++ b/spree/core/spec/services/spree/media/usage_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe Spree::MediaUsage do
+describe Spree::Media::Usage do
subject(:usage) { described_class.call(media: media).value }
let(:product) { create(:product, name: 'Original product') }