Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Introducing new Product Media system (#14000)
Damian Legawiecd65c0f3eea94
diff --git a/docs/developer/core-concepts/media.mdx b/docs/developer/core-concepts/media.mdxindex b436c4cc36..8d0854bd39 100644--- a/docs/developer/core-concepts/media.mdx+++ b/docs/developer/core-concepts/media.mdx@@ -12,19 +12,78 @@ Spree handles uploads, processing, and delivery for product media. Images are au## Product Media-Product media uses the `Spree::Asset` model, which provides:+A media record carries:-- **Multiple media per product** with ordering-- **Media types** — `image`, `video`, `external_video`+- **Position** for ordering within the gallery+- **Media type** — `image`, `video`, or `external_video` (defaults to `image`)- **Alt text** for accessibility and SEO- **Focal point** coordinates for smart cropping- **Preprocessed named variants** for fast delivery+- **`variant_ids`** — which product variants the media represents. An empty array means it represents the product as a whole.-Each media item has a `media_type` field that defaults to `image`. The `variant_ids` field indicates which product variants the media is associated with — an empty array means the media belongs to the product as a whole.+### Product-level Gallery <Since version="5.5" />-<Note>-`Spree::Image` is a backward-compatible subclass of `Spree::Asset` that sets `media_type` to `image`. New code should use `Spree::Asset` directly.-</Note>+In Spree 5.5 the **product** is the default owner of media. Before 5.5, every image was pinned to a specific variant (usually the master), and sharing the same image across variants meant re-uploading the file. From 5.5 onward, an image lives on the product, and any subset of variants can reference it through `variant_ids` — without duplicating the underlying file.++#### Uploading a product-level image++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({ baseUrl, secretKey })++// `signed_id` comes from a direct upload; see the Active Storage docs for+// generating one client-side.+const media = await client.products.media.create('prod_86Rf07xd4z', {+ signed_id: signedBlobId,+ alt: 'Front view',+ position: 1,+})+```++```bash cURL+curl -X POST 'https://api.mystore.com/api/v3/admin/products/prod_86Rf07xd4z/media' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{+ "signed_id": "<signed-blob-id>",+ "alt": "Front view",+ "position": 1+ }'+```++</CodeGroup>++#### Sharing a single image across variants++Pass a `variant_ids` array on the same media endpoint to link/unlink variants. The server replaces the asset's link set on every call — empty array clears all links, omitting the field leaves them untouched.++<CodeGroup>++```typescript Admin SDK+await client.products.media.update('prod_86Rf07xd4z', 'media_k5nR8xLq', {+ variant_ids: ['variant_redM', 'variant_redL'],+})+```++```bash cURL+curl -X PATCH 'https://api.mystore.com/api/v3/admin/products/prod_86Rf07xd4z/media/media_k5nR8xLq' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "variant_ids": ["variant_redM", "variant_redL"] }'+```++</CodeGroup>++Variants belonging to a different product are silently dropped — the API rejects cross-product tampering at the model layer. Reordering happens once on the product gallery; every linked variant inherits the new order.++#### Storefront gallery resolution++The Store API's `media` field on a product returns its gallery — product-level media when present, falling back to legacy variant-pinned images during the transition. On a variant, `media` returns the assets linked to that variant via `variant_ids`, falling back to direct variant uploads.++This dual rendering means existing storefronts keep working during the upgrade; new uploads attach to the product, and you opt into a [one-shot migration](/developer/upgrades/5.4-to-5.5) to re-home legacy variant-pinned data when convenient.### Named Variant Sizes <Since version="5.3" />@@ -142,8 +201,9 @@ curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=media,vari| `focal_point_x` | number \| null | Horizontal focal point (0.0–1.0) || `focal_point_y` | number \| null | Vertical focal point (0.0–1.0) || `external_video_url` | string \| null | External video URL (YouTube/Vimeo) |-| `original_url` | string \| null | Full-size image URL |+| `original_url` | string \| null | Full-size image URL (inline disposition) || `mini_url` ... `xlarge_url` | string \| null | Named variant URLs |+| `download_url` | string \| null | Same blob as `original_url` but with `Content-Disposition: attachment`. Admin API only. <Since version="5.5" /> |## Image Processingdiff --git a/docs/developer/upgrades/5.4-to-5.5.mdx b/docs/developer/upgrades/5.4-to-5.5.mdxindex 2733e2927f..f5332fb926 100644--- a/docs/developer/upgrades/5.4-to-5.5.mdx+++ b/docs/developer/upgrades/5.4-to-5.5.mdx@@ -21,6 +21,26 @@ description: This guide covers upgrading a Spree 5.4 application to Spree 5.5.bin/rake spree:install:migrations && bin/rails db:migrate```+### Migrate legacy variant-pinned media++In 5.5 the [product is the default owner of media](/developer/core-concepts/media#product-level-gallery). Existing variant-pinned images keep rendering, but new admin uploads attach to the product. To consolidate both into a single gallery, run:++```bash+bin/rails spree:media:migrate_master_images_to_product_media+```++The task enqueues one `Spree::Media::MigrateProductAssetsJob` per product onto the `images` queue — make sure your job runner is processing that queue. Each job is idempotent, so re-running the task is safe; it skips products that no longer have variant-pinned assets.++For larger catalogs, tune the batching with `BATCH_SIZE`:++```bash+bin/rails spree:media:migrate_master_images_to_product_media BATCH_SIZE=1000+```++<Warning>+ Run the task locally and on production. It does not block storefront rendering — new uploads attach to the product immediately — but until the enqueued jobs finish, old assets remain pinned to variants.+</Warning>+### Run the channels upgradeSpree 5.5 promotes `Order#channel` from a free-text string column to a real `Spree::Channel` FK. **Run this rake task immediately after `db:migrate`** — it seeds the channel rows your existing stores need and backfills `spree_orders.channel_id` from the legacy string column:diff --git a/docs/plans/5.4-6.0-product-media-system.md b/docs/plans/5.4-6.0-product-media-system.mdindex 3f6351e5a5..fbe11bdd2b 100644--- a/docs/plans/5.4-6.0-product-media-system.md+++ b/docs/plans/5.4-6.0-product-media-system.md@@ -1,10 +1,10 @@# Product Media System**Status:** In Progress-**Target:** Spree 5.4 (foundation) + Spree 6.0 (full flip)+**Target:** Spree 5.4 (foundation) + Spree 5.5 (data model + admin UIs) + Spree 6.0 (cleanup with master removal)**Depends on:** None**Author:** Damian + Claude-**Last updated:** 2026-03-16+**Last updated:** 2026-05-11## Summary@@ -20,8 +20,9 @@ This plan moves to a **product-level media gallery** (the industry standard) whe4. **Single `Spree::Asset` class** — `Spree::Image` logic merged into `Spree::Asset`. `Spree::Image` kept as thin subclass (sets `media_type: 'image'`). No STI.5. **`media_type` defaults to `'image'`** — always present, never null.6. **No dedicated Store media endpoint** — media is served via `expand=media` on products/variants (industry standard).-7. **VariantMedia join table deferred to 6.0** — not needed until data migration moves images from variants to products.-8. **Rename `Spree::Asset` → `Spree::Media` in 6.0** — aligns model/table/prefix with API naming.+7. **VariantMedia join table lands in 5.5** — enables variants to reference product-level assets without duplicating blobs. Direct variant `images` association stays for backward compatibility. The join is internal plumbing, not an API surface: callers manage variant assignment via `PATCH /products/:id/media/:asset_id { variant_ids: [...] }` (the `Spree::Asset#variant_ids=` setter resolves prefixed IDs and enforces same-product). Named `VariantMedia` (table `spree_variant_media`) — matches the industry convention (Shopify, Vendure, BigCommerce all expose a `variant_media` or `productVariantMedia` join concept).+8. **Rename `Spree::Asset` → `Spree::Media` in 6.0** — aligns model/table/prefix with API naming. Coincides with master removal cleanup.+9. **Product is the default upload target in 5.5** — `POST /api/v3/admin/products/:id/media` and the legacy admin product form both attach to `Spree::Product` directly. Master-pinned images keep displaying via `gallery_media` until merchants opt into the migration rake (or 6.0 sweeps them up).## Design Details@@ -42,14 +43,16 @@ Spree::Product#gallery_media → media.any? ? media : variant_imagesSpree::Variant- has_many :images, as: :viewable ← kept (legacy)- #gallery_media → images ← 6.0: will use join table+ has_many :images, as: :viewable ← kept (direct variant uploads)+ has_many :variant_media ← 5.5: links to product-level Assets+ has_many :associated_media, through: :variant_media, source: :asset+ #gallery_media → associated_media (if any) else images-Spree::VariantMedia (6.0)+Spree::VariantMedia (5.5, table: spree_variant_media)belongs_to :variant- belongs_to :asset- position (per-variant ordering)- unique index on [variant_id, asset_id]+ belongs_to :asset (FK: media_id, points at spree_assets in 5.5 / spree_media in 6.0)+ unique index on [variant_id, media_id]+ no position column — gallery order comes from the asset's product-level position```### Store API (5.4)@@ -94,48 +97,94 @@ Spree::VariantMedia (6.0)- TypeScript types, Zod schemas, OpenAPI spec regenerated- Docs updated throughout-### 6.0 — TODO+### 5.5 — TODO++5.5 delivers the **data model, API, and both admin UIs** for product-level media as a parallel path. Variant-level media keeps working unchanged. The data-migration rake ships as **opt-in** so existing merchants choose when to re-home master-pinned images. Master removal stays in 6.0.++**Why before master removal?** `Asset#viewable` is already polymorphic across `Spree::Variant` and `Spree::Product`. Both polymorphic targets coexist cleanly in 5.5 — old master-pinned assets keep displaying via `gallery_media`'s fallback, new uploads go to Product. 6.0 then re-homes the remaining master-pinned assets as part of master removal Phase 2.**Phase 1: VariantMedia join table**- Create `spree_variant_media` table + `Spree::VariantMedia` model- `Variant#variant_media`, `Variant#associated_media` associations-- Update `Variant#gallery_media` to prefer associated_media over direct images-- Admin API: media CRUD endpoints for products and variant media association--**Phase 2: Admin UI**-- Product form uploads to `Product` (not master `Variant`)-- Variant edit shows media picker (select from product gallery, drag-to-reorder)-- Focal point UI on asset edit dialog--**Phase 3: Data migration**-- Rake task `spree:migrate_images_to_product_media`-- Move master variant images to product level-- Move non-master variant images to product + create VariantMedia records-- Deduplicate shared blobs-- Recalculate counter caches and thumbnails--**Phase 4: Video support (can be deferred)**-- `Spree::Video` or media_type='external_video' with URL validation-- Admin UI: "Add video" button for YouTube/Vimeo URLs--**Phase 5: Rename Asset → Media**+- Update `Variant#gallery_media` to prefer `associated_media` (join table) over direct `images`, falling back to `images` when the join is empty+- Unique index on `[variant_id, media_id]`. No per-variant ordering — gallery order is inherited from the asset's product-level `position` so merchants reorder once on the product gallery and every variant follows.++**Phase 2: Admin API — Product is the default parent**+- `POST /api/v3/admin/products/:product_id/media` defaults to `viewable_type: 'Spree::Product'` (was master variant). Existing `?variant_id=...` path keeps creating `viewable_type: 'Spree::Variant'`+- New endpoints for variant↔product-asset linking:+ - Variant assignment travels on the existing media endpoint as a `variant_ids` array — no dedicated link/unlink routes:+ - `PATCH /api/v3/admin/products/:product_id/media/:asset_id { variant_ids: ["variant_xyz", ...] }`+ - The `Spree::Asset#variant_ids=` setter resolves prefixed IDs to internal IDs scoped to the asset's product (anything else is silently dropped) and uses Rails' `has_many :through` setter under the hood. Empty array clears all links; omitting the field leaves them untouched.+- `Asset#should_touch_product_variants?` gains a `Spree::Product` branch so reordering product-level media still busts variant cache keys+- Per the [admin-sdk-unreleased policy](../../memory/feedback-admin-sdk-unreleased.md), this ships as a clean break — no deprecation alias for the master-default behavior++**Phase 3: Legacy Rails admin — flip product upload to Product-typed**+- `_form.html.erb`: `viewable: @product, viewable_type: 'Spree::Product'` (was `@product.master`, `'Spree::Variant'`)+- `products_controller.rb`: rename `assign_master_images` → `assign_session_uploaded_assets`, retarget to `viewable_id: @product.id, viewable_type: 'Spree::Product'`. Session bucket key changes to `'Spree::Product'`+- `load_variants_data`: variant thumbnail map falls back to `@product.primary_media` when a variant has no `primary_media`+- Variant edit page (`variants/edit.html.erb`) keeps `viewable_type: 'Spree::Variant'` — variant-level direct uploads work unchanged+- Skip building a "select from product gallery" picker in legacy admin — that UX is SPA-only++**Phase 4: Admin SPA UI**+- Product detail page → Media tab: drag-and-drop upload to Product, drag-to-reorder, focal-point picker, alt text editor (consumes existing `use-product-media` hook)+- Variant detail tab → Media section: "Select from product gallery" multi-select dialog + drag-to-reorder. Each picked asset gets `PATCH /products/:id/media/:asset_id { variant_ids: [...current, this_variant] }`+- Rebuild `@spree/admin-sdk` (`pnpm build` from root) so the SPA picks up the new endpoints++**Phase 5: Data migration rake (opt-in)**+- `rake spree:migrate_master_images_to_product_media`+- For each Product: move master-pinned images to `viewable_type: 'Spree::Product'` when master has no line items, copy them when master has line items+- Recalculate `media_count` counter caches and `primary_media_id`+- Idempotent — re-runs are no-ops+- **Not run automatically on upgrade.** Documented as opt-in for merchants who want a clean state. Becomes mandatory in 6.0 (run by master-removal Phase 2)++### 6.0 — TODO++By 6.0, master variant is being removed (see `6.0-remove-master-variant.md`). Master-removal Phase 2 absorbs the residual image re-homing so no asset is orphaned when its master viewable is deleted.++**Phase 1: Master image re-homing (owned by master removal)**+- Master-removal Phase 2 runs the 5.5 rake's logic for any merchant who didn't run it themselves+- After this step, no asset has `viewable_type: 'Spree::Variant', viewable.is_master: true`++**Phase 2: Video support (can be deferred)**+- `media_type='external_video'` URL validation polish+- Admin UI: "Add video" button for YouTube/Vimeo URLs (5.5 SPA can ship this opportunistically)++**Phase 3: Rename Asset → Media**- Rename table `spree_assets` → `spree_media`- Rename model `Spree::Asset` → `Spree::Media`- Prefix ID already `media_xxx` since 5.4 — no change needed- Remove `Spree::Image` subclass-**Phase 6: Cleanup**-- Remove `Product#variant_images` (use `Product#media`)-- Remove `viewable_id/type` from Admin API-- Update Duplicator and CSV presenter+**Phase 4: Cleanup**+- Remove `Product#variant_images` and `Product#variant_images_without_master` (callers use `Product#media` / `Product#gallery_media`)+- Remove `viewable_id`/`viewable_type` from Admin API responses+- Update Duplicator and CSV presenter to operate on product-level media + VariantMedia rows+- Drop `Product#master_images` alias## Constraints on Current Work- **Always use `expand=media`** (not `expand=images`) in new Store API code and SDK examples- **Always use `Spree::Asset`** for new code; `Spree::Image` is for backward compat only-- **Use `gallery_media`** as the unified accessor on Product and Variant-- **Do not create `VariantMedia` records** — the join table doesn't exist yet in 5.4+- **Use `gallery_media`** as the unified accessor on Product and Variant — never `master.images`, never `variant_images` directly+- **Default new product-level uploads to `viewable_type: 'Spree::Product'`** — do not pin to `@product.master` in any new admin code+- **Variant-level direct uploads stay valid in 5.5** via `viewable_type: 'Spree::Variant'`. Prefer `VariantMedia` rows linking to product-level assets when sharing a blob across variants- **`media_type` is never null** — defaults to `'image'`, always validate inclusion+- **Do not run the master-image migration rake automatically on upgrade** — it must stay opt-in in 5.5 (becomes mandatory in 6.0 via master removal)++## Scope Boundary: Merchandising Media, Not a DAM++`Spree::Asset` (renamed `Spree::Media` in 6.0) is **merchandising media for commerce entities** — product photography, variant shots, swatches, eventually category/brand hero images. It is intentionally **not a general-purpose Digital Asset Management system**.++Storytelling, editorial content, blog posts, landing-page copy, lifestyle imagery, marketing collateral — none of this is Spree's job in a headless world. Headless storefronts pair Spree with a CMS (Payload, Sanity, Strapi, Hygraph, etc.) and that CMS owns its own asset library. Spree's role is to expose CDN URLs the storefront consumes; everything upstream of that URL is somebody else's surface.++**Implications:**++- **No "Files" page in admin.** No central library, no cross-entity picker, no tag taxonomy, no "where is this used" reverse lookup, no bulk replace. Each commerce entity owns its own gallery via the polymorphic `viewable` association.+- **Active Storage already deduplicates blobs by checksum** — uploading the same file twice creates two cheap `Asset` rows pointing at one S3 object. The economic case for a shared library is weak; the UX case in pure-commerce admin doesn't materialize until file counts get huge, at which point the merchant should be on a real DAM (Cloudinary MAM, Bynder, Brandfolder) feeding URLs into Spree.+- **Polymorphism stays narrow.** `viewable_type` extends to commerce entities only — Product, Variant, eventually Taxon if a real customer ask lands. Adding `viewable_type: 'Spree::Post'` or `'Spree::Page'` would imply Spree is a CMS; we don't go there.+- **Storage abstraction is the escape hatch.** Merchants needing a real DAM configure a custom storage service (or a `Spree.cdn_host`) that points at their managed asset platform. The platform owns curation; Spree owns the URL contract.++If a future request asks for cross-entity sharing inside Spree (e.g., "this hero shot belongs to both a Product and the Taxon it's on"), revisit this boundary deliberately — don't drift into it. The default answer remains: **no shared library, scope to commerce entities, defer broader media management to upstream tools.**## Open Questionsdiff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex b9dac6a696..45ef2b33aa 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -206,11 +206,17 @@ export interface MediaCreateParams {type?: stringurl?: stringsigned_id?: string+ // Prefixed or raw variant IDs to link this product-level media to. Variants+ // not on the same product are silently dropped server-side.+ variant_ids?: Array<string>}export interface MediaUpdateParams {alt?: stringposition?: number+ // Replaces the full set of variants this media is linked to. Empty array+ // clears all links; omit the field entirely to leave links untouched.+ variant_ids?: Array<string>}export interface ProductCreateParams {diff --git a/packages/admin-sdk/src/types/generated/Media.ts b/packages/admin-sdk/src/types/generated/Media.tsindex 6c5f7b2f0d..8a8a961afd 100644--- a/packages/admin-sdk/src/types/generated/Media.ts+++ b/packages/admin-sdk/src/types/generated/Media.ts@@ -1,4 +1,4 @@-// Typelizer digest e53e1b7e1e95ba9a2734772080dbfb1b+// Typelizer digest 569c2ab4356afb4f012fa1cbcab0cc13//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -22,6 +22,7 @@ interface Media {created_at: string;updated_at: string;viewable_id: string;+ download_url: string | null;metadata: Record<string, unknown>;viewable_type: string;}diff --git a/packages/admin/package.json b/packages/admin/package.jsonindex 032ac9ab48..e4e8f95834 100644--- a/packages/admin/package.json+++ b/packages/admin/package.json@@ -17,6 +17,9 @@},"dependencies": {"@base-ui/react": "^1.4.1",+ "@dnd-kit/core": "^6.3.1",+ "@dnd-kit/sortable": "^10.0.0",+ "@dnd-kit/utilities": "^3.2.2","@fontsource-variable/geist": "^5.2.8","@fontsource-variable/geist-mono": "^5.2.7","@hookform/resolvers": "^5.2.2",diff --git a/packages/admin/src/components/spree/products/media-edit-sheet.tsx b/packages/admin/src/components/spree/products/media-edit-sheet.tsxnew file mode 100644index 0000000000..9e6da99d9f--- /dev/null+++ b/packages/admin/src/components/spree/products/media-edit-sheet.tsx@@ -0,0 +1,195 @@+import type { Media, Variant } from '@spree/admin-sdk'+import { CheckIcon, DownloadIcon, ExternalLinkIcon, ImagePlusIcon, Loader2Icon } from 'lucide-react'+import { useEffect, useState } from 'react'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Field, FieldLabel } from '@/components/ui/field'+import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from '@/components/ui/sheet'+import { Textarea } from '@/components/ui/textarea'+import { useUpdateProductMedia } from '@/hooks/use-product-media'++type Props = {+ productId: string+ mediaItem: Media | null+ variants: Variant[]+ open: boolean+ onOpenChange: (open: boolean) => void+}++export function MediaEditSheet({ productId, mediaItem, variants, open, onOpenChange }: Props) {+ const updateMedia = useUpdateProductMedia(productId)++ const [alt, setAlt] = useState('')+ const [selectedVariantIds, setSelectedVariantIds] = useState<Set<string>>(new Set())++ // Sync local state to mediaItem so switching assets doesn't leak edits.+ useEffect(() => {+ if (mediaItem) {+ setAlt(mediaItem.alt ?? '')+ setSelectedVariantIds(new Set(mediaItem.variant_ids ?? []))+ }+ }, [mediaItem])++ const initialAlt = mediaItem?.alt ?? ''+ const initialVariantIds = mediaItem?.variant_ids ?? []+ const altChanged = alt !== initialAlt+ const variantsChanged =+ initialVariantIds.length !== selectedVariantIds.size ||+ initialVariantIds.some((id) => !selectedVariantIds.has(id))++ const toggleVariant = (variantId: string) => {+ setSelectedVariantIds((prev) => {+ const next = new Set(prev)+ if (next.has(variantId)) next.delete(variantId)+ else next.add(variantId)+ return next+ })+ }++ const handleSave = async () => {+ if (!mediaItem) return++ try {+ const patch: { id: string; alt?: string; variant_ids?: string[] } = { id: mediaItem.id }+ if (altChanged) patch.alt = alt+ if (variantsChanged) patch.variant_ids = Array.from(selectedVariantIds)+ await updateMedia.mutateAsync(patch)++ toast.success('Media updated')+ onOpenChange(false)+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed to update image'+ toast.error(message)+ }+ }++ // Prefer the largest pre-rendered variant for the in-sheet preview; fall back+ // to the original. The full-size link points at original_url; download_url+ // is the same blob with disposition=attachment so cloud storage saves instead+ // of inlines.+ const previewUrl =+ mediaItem?.large_url ||+ mediaItem?.medium_url ||+ mediaItem?.small_url ||+ mediaItem?.original_url ||+ null+ const fullSizeUrl = mediaItem?.original_url ?? null+ const downloadUrl = mediaItem?.download_url ?? null++ const dirty = altChanged || variantsChanged++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent side="right" showCloseButton className="flex flex-col">+ <SheetHeader>+ <SheetTitle>Edit media</SheetTitle>+ </SheetHeader>++ <div className="flex-1 overflow-y-auto p-4 flex flex-col gap-5">+ <div className="group relative overflow-hidden rounded-lg border border-border bg-muted">+ {previewUrl ? (+ <img src={previewUrl} alt={alt} className="w-full max-h-[60vh] object-contain" />+ ) : (+ <div className="flex aspect-square w-full items-center justify-center text-muted-foreground">+ <ImagePlusIcon className="size-8" />+ </div>+ )}+ {(fullSizeUrl || downloadUrl) && (+ <div className="absolute bottom-2 right-2 flex gap-1.5 opacity-0 transition-opacity group-hover:opacity-100">+ {fullSizeUrl && (+ <a+ href={fullSizeUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-1 rounded-md bg-background/90 px-2 py-1 text-xs font-medium text-foreground shadow-sm hover:bg-background"+ >+ <ExternalLinkIcon className="size-3" />+ View full size+ </a>+ )}+ {downloadUrl && (+ <a+ href={downloadUrl}+ className="inline-flex items-center gap-1 rounded-md bg-background/90 px-2 py-1 text-xs font-medium text-foreground shadow-sm hover:bg-background"+ >+ <DownloadIcon className="size-3" />+ Download+ </a>+ )}+ </div>+ )}+ </div>++ <Field>+ <FieldLabel htmlFor="media-alt">Alt text</FieldLabel>+ <Textarea+ id="media-alt"+ value={alt}+ onChange={(e) => setAlt(e.target.value)}+ rows={3}+ placeholder="Describe the image for accessibility and SEO"+ />+ </Field>++ {variants.length > 0 && (+ <Field>+ <FieldLabel>Assigned variants</FieldLabel>+ <p className="text-xs text-muted-foreground">+ Pick the variants this image represents. Leave blank to apply to all variants.+ </p>+ <div className="flex flex-wrap gap-2 pt-2">+ {variants.map((v) => {+ const id = v.id+ if (!id) return null+ const selected = selectedVariantIds.has(id)+ const label = variantLabel(v)+ return (+ <button+ key={id}+ type="button"+ onClick={() => toggleVariant(id)}+ aria-pressed={selected}+ className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-colors ${+ selected+ ? 'border-primary bg-primary text-primary-foreground'+ : 'border-border bg-background text-muted-foreground hover:border-muted-foreground hover:text-foreground'+ }`}+ >+ {selected && <CheckIcon className="size-3" />}+ {label}+ </button>+ )+ })}+ </div>+ </Field>+ )}+ </div>++ <SheetFooter>+ <Button+ variant="ghost"+ onClick={() => onOpenChange(false)}+ disabled={updateMedia.isPending}+ >+ Cancel+ </Button>+ <Button onClick={handleSave} disabled={!dirty || updateMedia.isPending}>+ {updateMedia.isPending ? (+ <>+ <Loader2Icon className="size-4 animate-spin" />+ Saving…+ </>+ ) : (+ 'Save'+ )}+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ )+}++function variantLabel(v: Variant): string {+ const named = v as { options_text?: string; name?: string; sku?: string | null }+ return named.options_text || named.name || named.sku || v.id || 'Variant'+}diff --git a/packages/admin/src/components/spree/products/variant-media-picker.tsx b/packages/admin/src/components/spree/products/variant-media-picker.tsxnew file mode 100644index 0000000000..606b025633--- /dev/null+++ b/packages/admin/src/components/spree/products/variant-media-picker.tsx@@ -0,0 +1,151 @@+import { CheckIcon, ImagePlusIcon, Loader2Icon } from 'lucide-react'+import { useMemo, useState } from 'react'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { useProductMedia, useUpdateProductMedia } from '@/hooks/use-product-media'+import { useVariantMedia } from '@/hooks/use-variant-media'++type Props = {+ productId: string+ variantId: string+ triggerLabel?: string+ triggerVariant?: 'default' | 'outline' | 'ghost' | 'destructive' | 'link'+}++export function VariantMediaPicker({+ productId,+ variantId,+ triggerLabel = 'Select from product gallery',+ triggerVariant = 'outline',+}: Props) {+ const [open, setOpen] = useState(false)+ const [selectedMediaIds, setSelectedMediaIds] = useState<Set<string>>(new Set())++ const productMediaQuery = useProductMedia(productId)+ const variantMediaQuery = useVariantMedia(productId, variantId)+ const updateMedia = useUpdateProductMedia(productId)++ const productMedia = productMediaQuery.data?.data ?? []+ const variantLinkedMediaIds = useMemo(+ () => new Set((variantMediaQuery.data?.data ?? []).map((m) => m.id)),+ [variantMediaQuery.data],+ )++ const linkable = productMedia.filter((m) => !variantLinkedMediaIds.has(m.id))++ const toggle = (mediaId: string) => {+ setSelectedMediaIds((prev) => {+ const next = new Set(prev)+ if (next.has(mediaId)) {+ next.delete(mediaId)+ } else {+ next.add(mediaId)+ }+ return next+ })+ }++ const handleAdd = async () => {+ await Promise.all(+ Array.from(selectedMediaIds).map((mediaId) => {+ const asset = productMedia.find((m) => m.id === mediaId)+ const next = new Set(asset?.variant_ids ?? [])+ next.add(variantId)+ return updateMedia.mutateAsync({ id: mediaId, variant_ids: Array.from(next) })+ }),+ )+ setSelectedMediaIds(new Set())+ setOpen(false)+ }++ return (+ <>+ <Button variant={triggerVariant} size="sm" onClick={() => setOpen(true)}>+ {triggerLabel}+ </Button>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>Select from product gallery</DialogTitle>+ </DialogHeader>+ <DialogBody>+ {productMediaQuery.isLoading ? (+ <div className="flex items-center justify-center py-12 text-muted-foreground">+ <Loader2Icon className="size-5 animate-spin" />+ </div>+ ) : linkable.length === 0 ? (+ <div className="flex flex-col items-center justify-center gap-2 py-12 text-muted-foreground">+ <ImagePlusIcon className="size-6" />+ <p className="text-sm">+ {productMedia.length === 0+ ? 'No product media yet — upload images on the product first.'+ : 'All product media is already linked to this variant.'}+ </p>+ </div>+ ) : (+ <div className="grid grid-cols-3 gap-3 sm:grid-cols-4">+ {linkable.map((mediaItem) => {+ const selected = selectedMediaIds.has(mediaItem.id)+ const url = mediaItem.small_url || mediaItem.mini_url || mediaItem.original_url+ return (+ <button+ key={mediaItem.id}+ type="button"+ onClick={() => toggle(mediaItem.id)}+ aria-pressed={selected}+ className={`group relative aspect-square overflow-hidden rounded-lg border-2 transition-colors ${+ selected ? 'border-primary' : 'border-border hover:border-muted-foreground'+ }`}+ >+ {url ? (+ <img+ src={url}+ alt={mediaItem.alt ?? ''}+ className="size-full object-cover"+ />+ ) : (+ <div className="flex size-full items-center justify-center bg-muted text-muted-foreground">+ <ImagePlusIcon className="size-6" />+ </div>+ )}+ {selected && (+ <span className="absolute top-1.5 right-1.5 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground size-5 shadow-sm">+ <CheckIcon className="size-3" />+ </span>+ )}+ </button>+ )+ })}+ </div>+ )}+ </DialogBody>+ <DialogFooter>+ <Button variant="ghost" onClick={() => setOpen(false)}>+ Cancel+ </Button>+ <Button+ onClick={handleAdd}+ disabled={selectedMediaIds.size === 0 || updateMedia.isPending}+ >+ {updateMedia.isPending ? (+ <>+ <Loader2Icon className="size-4 animate-spin" />+ Adding…+ </>+ ) : (+ `Add ${selectedMediaIds.size || ''}`.trim()+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ )+}diff --git a/packages/admin/src/hooks/use-direct-upload.ts b/packages/admin/src/hooks/use-direct-upload.tsindex 2f017f0684..5fa0dba0ab 100644--- a/packages/admin/src/hooks/use-direct-upload.ts+++ b/packages/admin/src/hooks/use-direct-upload.ts@@ -39,6 +39,18 @@ interface UploadResult {previewUrl: string}+function sameOriginIfRailsDisk(url: string): string {+ try {+ const parsed = new URL(url)+ if (parsed.pathname.startsWith('/rails/active_storage/')) {+ return parsed.pathname + parsed.search+ }+ return url+ } catch {+ return url+ }+}+export function useDirectUpload() {return useMutation({mutationFn: async (file: File): Promise<UploadResult> => {@@ -62,8 +74,17 @@ export function useDirectUpload() {throw new Error(`Presign failed: ${err instanceof Error ? err.message : err}`)}- // Step 2: Upload file directly to storage- const uploadResponse = await fetch(response.direct_upload.url, {+ // Step 2: Upload file directly to storage.+ //+ // Active Storage's Disk service issues an absolute URL against the Rails+ // origin (e.g. http://localhost:3000/rails/active_storage/disk/...). In+ // dev the SPA runs on a different port and that controller doesn't speak+ // CORS, so the browser blocks the cross-origin PUT before any response+ // ("Failed to fetch"). When the URL points at a `/rails/active_storage/`+ // path we drop the host so the request goes through Vite's `/rails`+ // proxy and stays same-origin. Production S3 URLs are untouched.+ const uploadUrl = sameOriginIfRailsDisk(response.direct_upload.url)+ const uploadResponse = await fetch(uploadUrl, {method: 'PUT',headers: response.direct_upload.headers,body: file,diff --git a/packages/admin/src/hooks/use-product-media.ts b/packages/admin/src/hooks/use-product-media.tsindex ecc5bedc34..c1b8d1ad01 100644--- a/packages/admin/src/hooks/use-product-media.ts+++ b/packages/admin/src/hooks/use-product-media.ts@@ -1,6 +1,9 @@+import type { Media } from '@spree/admin-sdk'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { adminClient } from '@/client'+type MediaListSnapshot = { data: Media[] }+export function useProductMedia(productId: string) {return useQuery({queryKey: ['products', productId, 'media'],@@ -13,23 +16,73 @@ export function useCreateProductMedia(productId: string) {const queryClient = useQueryClient()return useMutation({- mutationFn: (params: { signed_id: string; alt?: string; position?: number }) =>- adminClient.products.media.create(productId, params),- onSuccess: () => {+ mutationFn: (params: {+ signed_id: string+ alt?: string+ position?: number+ variant_ids?: string[]+ }) => adminClient.products.media.create(productId, params),+ onSuccess: (_data, variables) => {queryClient.invalidateQueries({ queryKey: ['products', productId, 'media'] })queryClient.invalidateQueries({ queryKey: ['products', productId] })+ if (variables.variant_ids !== undefined) {+ queryClient.invalidateQueries({ queryKey: ['products', productId, 'variants'] })+ }},})}export function useUpdateProductMedia(productId: string) {const queryClient = useQueryClient()+ const queryKey = ['products', productId, 'media']return useMutation({- mutationFn: ({ id, ...params }: { id: string; alt?: string; position?: number }) =>- adminClient.products.media.update(productId, id, params),- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['products', productId, 'media'] })+ mutationFn: ({+ id,+ ...params+ }: {+ id: string+ alt?: string+ position?: number+ variant_ids?: string[]+ }) => adminClient.products.media.update(productId, id, params),++ // Optimistically splice on `position` change — server-side acts_as_list+ // shifts siblings, so the post-success refetch will match.+ onMutate: async ({ id, position }) => {+ if (position === undefined) return undefined++ await queryClient.cancelQueries({ queryKey })+ const previous = queryClient.getQueryData<MediaListSnapshot>(queryKey)+ if (!previous) return undefined++ const items = [...previous.data]+ const fromIndex = items.findIndex((m) => m.id === id)+ if (fromIndex === -1) return { previous }++ const toIndex = Math.max(0, Math.min(items.length - 1, position - 1))+ const [moved] = items.splice(fromIndex, 1)+ items.splice(toIndex, 0, moved)++ queryClient.setQueryData<MediaListSnapshot>(queryKey, {+ ...previous,+ data: items,+ })++ return { previous }+ },++ onError: (_err, _vars, context) => {+ if (context?.previous) {+ queryClient.setQueryData(queryKey, context.previous)+ }+ },++ onSettled: (_data, _err, variables) => {+ queryClient.invalidateQueries({ queryKey })+ if (variables.variant_ids !== undefined) {+ queryClient.invalidateQueries({ queryKey: ['products', productId, 'variants'] })+ }},})}diff --git a/packages/admin/src/hooks/use-product.ts b/packages/admin/src/hooks/use-product.tsindex eea796bf2a..ec16ce2922 100644--- a/packages/admin/src/hooks/use-product.ts+++ b/packages/admin/src/hooks/use-product.ts@@ -11,7 +11,6 @@ export function useProduct(id: string) {'default_variant.prices','variants','variants.prices',- 'images','option_types','categories','tax_category',diff --git a/packages/admin/src/hooks/use-variant-media.ts b/packages/admin/src/hooks/use-variant-media.tsnew file mode 100644index 0000000000..8ee478a662--- /dev/null+++ b/packages/admin/src/hooks/use-variant-media.ts@@ -0,0 +1,12 @@+import { useQuery } from '@tanstack/react-query'+import { adminClient } from '@/client'++// Lists media linked to a variant. Mutations go through useUpdateProductMedia+// with `variant_ids` — there's no variant-scoped mutation endpoint.+export function useVariantMedia(productId: string, variantId: string) {+ return useQuery({+ queryKey: ['products', productId, 'variants', variantId, 'media'],+ queryFn: () => adminClient.products.variants.media.list(productId, variantId),+ enabled: !!productId && !!variantId,+ })+}diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsxindex 29b16252e4..b68b69291b 100644--- a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -13,9 +13,24 @@ type Product = Omit<BaseProduct, 'default_variant' | 'variants'> & {variants?: Variant[]}+import {+ DndContext,+ type DragEndEvent,+ KeyboardSensor,+ PointerSensor,+ useSensor,+ useSensors,+} from '@dnd-kit/core'+import {+ rectSortingStrategy,+ SortableContext,+ sortableKeyboardCoordinates,+ useSortable,+} from '@dnd-kit/sortable'+import { CSS } from '@dnd-kit/utilities'import { zodResolver } from '@hookform/resolvers/zod'import { createFileRoute, useRouter } from '@tanstack/react-router'-import { ImagePlusIcon, Loader2Icon, XIcon } from 'lucide-react'+import { ImagePlusIcon, Loader2Icon, PencilIcon, TrashIcon } from 'lucide-react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { Controller, type UseFormReturn, useForm } from 'react-hook-form'import { toast } from 'sonner'@@ -25,10 +40,12 @@ import { CustomFieldsCard } from '@/components/spree/custom-fields/custom-fieldsimport { FormActions, useFormSubmitShortcut } from '@/components/spree/form-actions'import { MetadataCard } from '@/components/spree/metadata/metadata-card'import { PageHeader } from '@/components/spree/page-header'+import { MediaEditSheet } from '@/components/spree/products/media-edit-sheet'import { ResourceLayout } from '@/components/spree/resource-layout'import { ErrorState } from '@/components/spree/route-error-boundary'import { TagCombobox } from '@/components/spree/tag-combobox'import { StatusBadge } from '@/components/ui/badge'+import { Button } from '@/components/ui/button'import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'import {Combobox,@@ -63,6 +80,7 @@ import {useCreateProductMedia,useDeleteProductMedia,useProductMedia,+ useUpdateProductMedia,} from '@/hooks/use-product-media'import { useTaxCategories } from '@/hooks/use-tax-categories'import { useStore } from '@/providers/store-provider'@@ -216,7 +234,7 @@ function ProductForm({ product }: { product: Product }) {main={<><GeneralCard form={form} />- <MediaCard productId={productId} />+ <MediaCard productId={productId} variants={product.variants ?? []} />{!hasVariants && <PricingCard form={form} />}{!hasVariants && <InventoryCard form={form} />}<CustomFieldsCard@@ -299,15 +317,53 @@ interface PendingUpload {progress: 'uploading' | 'attaching' | 'done' | 'error'}-function MediaCard({ productId }: { productId: string }) {+function MediaCard({ productId, variants }: { productId: string; variants: Variant[] }) {const { data: mediaResponse } = useProductMedia(productId)const createMedia = useCreateProductMedia(productId)+ const updateMedia = useUpdateProductMedia(productId)const deleteMedia = useDeleteProductMedia(productId)const directUpload = useDirectUpload()+ const confirm = useConfirm()const [pending, setPending] = useState<PendingUpload[]>([])+ const [editingMediaId, setEditingMediaId] = useState<string | null>(null)const fileInputRef = useRef<HTMLInputElement>(null)const mediaItems = mediaResponse?.data ?? []+ const editingMedia = useMemo(+ () => mediaItems.find((m) => m.id === editingMediaId) ?? null,+ [mediaItems, editingMediaId],+ )++ // dnd-kit sensors: pointer for mouse/touch, keyboard for accessibility (Space+ // to grab, arrow keys to move, Space to drop). distance:5 prevents the grip+ // button from hijacking single clicks elsewhere on the thumbnail.+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),+ )++ // dnd-kit gives us source + destination indices in the array; convert to a+ // 1-indexed position that acts_as_list on Spree::Asset can act on. Server+ // shifts siblings; we only PATCH the moved item.+ const handleDragEnd = useCallback(+ async (event: DragEndEvent) => {+ const { active, over } = event+ if (!over || active.id === over.id) return++ const fromIndex = mediaItems.findIndex((m) => m.id === active.id)+ const toIndex = mediaItems.findIndex((m) => m.id === over.id)+ if (fromIndex === -1 || toIndex === -1) return++ const newPosition = toIndex + 1+ try {+ await updateMedia.mutateAsync({ id: String(active.id), position: newPosition })+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Reorder failed'+ toast.error(message)+ }+ },+ [mediaItems, updateMedia],+ )const handleFiles = useCallback(async (files: FileList | File[]) => {@@ -362,94 +418,177 @@ function MediaCard({ productId }: { productId: string }) {}, [])const handleDeleteMedia = async (mediaId: string) => {+ const confirmed = await confirm({+ message: 'Delete this media? This cannot be undone.',+ variant: 'destructive',+ confirmLabel: 'Delete',+ })+ if (!confirmed) return+try {await deleteMedia.mutateAsync(mediaId)- toast.success('Image deleted')+ toast.success('Media deleted')} catch {- toast.error('Failed to delete image')+ toast.error('Failed to delete media')}}return (- <Card>- <CardHeader>- <CardTitle>Media</CardTitle>- </CardHeader>- <CardContent className="flex flex-col gap-4">- {/* Image grid */}- {(mediaItems.length > 0 || pending.length > 0) && (- <div className="grid grid-cols-4 gap-3">- {mediaItems.map((mediaItem) => (- <MediaThumbnail- key={mediaItem.id}- mediaItem={mediaItem as unknown as Media}- onDelete={() => handleDeleteMedia(mediaItem.id)}- />- ))}- {pending.map((upload) => (- <div- key={upload.id}- className="relative aspect-square overflow-hidden rounded-lg border border-border bg-muted"- >- <img src={upload.preview} alt="" className="size-full object-cover opacity-60" />- <div className="absolute inset-0 flex items-center justify-center">- {upload.progress === 'error' ? (- <span className="text-xs text-destructive font-medium">Failed</span>- ) : (- <Loader2Icon className="size-5 animate-spin text-muted-foreground" />- )}+ <>+ <Card>+ <CardHeader>+ <CardTitle>Media</CardTitle>+ </CardHeader>+ <CardContent className="flex flex-col gap-4">+ {/* Media grid — sortable items first, pending uploads appended after */}+ {(mediaItems.length > 0 || pending.length > 0) && (+ <DndContext sensors={sensors} onDragEnd={handleDragEnd}>+ <SortableContext items={mediaItems.map((m) => m.id)} strategy={rectSortingStrategy}>+ <div className="grid grid-cols-4 gap-3">+ {mediaItems.map((mediaItem) => (+ <SortableMediaThumbnail+ key={mediaItem.id}+ mediaItem={mediaItem as unknown as Media}+ onEdit={() => setEditingMediaId(mediaItem.id)}+ onDelete={() => handleDeleteMedia(mediaItem.id)}+ />+ ))}+ {pending.map((upload) => (+ <div+ key={upload.id}+ className="relative aspect-square overflow-hidden rounded-lg border border-border bg-muted"+ >+ <img+ src={upload.preview}+ alt=""+ className="size-full object-cover opacity-60"+ />+ <div className="absolute inset-0 flex items-center justify-center">+ {upload.progress === 'error' ? (+ <span className="text-xs text-destructive font-medium">Failed</span>+ ) : (+ <Loader2Icon className="size-5 animate-spin text-muted-foreground" />+ )}+ </div>+ </div>+ ))}</div>- </div>- ))}- </div>- )}+ </SortableContext>+ </DndContext>+ )}- {/* Drop zone */}- <button- type="button"- onDrop={handleDrop}- onDragOver={handleDragOver}- className="flex w-full flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-border p-6 text-center transition-colors hover:border-foreground/30 cursor-pointer"- onClick={() => fileInputRef.current?.click()}- >- <ImagePlusIcon className="size-8 text-muted-foreground" />- <p className="text-sm text-muted-foreground">- Drag & drop images here, or click to browse- </p>- <p className="text-xs text-muted-foreground">PNG, JPG, WebP up to 10MB</p>- </button>- <input- ref={fileInputRef}- type="file"- accept="image/*"- multiple- className="hidden"- onChange={(e) => e.target.files && handleFiles(e.target.files)}- />- </CardContent>- </Card>+ {/* Drop zone */}+ <button+ type="button"+ onDrop={handleDrop}+ onDragOver={handleDragOver}+ className="flex w-full flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed border-border p-6 text-center transition-colors hover:border-foreground/30 cursor-pointer"+ onClick={() => fileInputRef.current?.click()}+ >+ <ImagePlusIcon className="size-8 text-muted-foreground" />+ <p className="text-sm text-muted-foreground">+ Drag & drop media here, or click to browse+ </p>+ <p className="text-xs text-muted-foreground">PNG, JPG, WebP up to 10MB</p>+ </button>+ <input+ ref={fileInputRef}+ type="file"+ accept="image/*"+ multiple+ className="hidden"+ onChange={(e) => e.target.files && handleFiles(e.target.files)}+ />+ </CardContent>+ </Card>+ <MediaEditSheet+ productId={productId}+ mediaItem={editingMedia as unknown as Media}+ variants={variants}+ open={!!editingMediaId}+ onOpenChange={(open) => {+ if (!open) setEditingMediaId(null)+ }}+ />+ </>)}-function MediaThumbnail({ mediaItem, onDelete }: { mediaItem: Media; onDelete: () => void }) {+function SortableMediaThumbnail({+ mediaItem,+ onEdit,+ onDelete,+}: {+ mediaItem: Media+ onEdit: () => void+ onDelete: () => void+}) {+ // The whole thumbnail is the drag source — listeners/attributes attach to+ // the wrapper. PointerSensor's distance:5 on the parent DndContext lets+ // brief clicks on the action buttons fall through without starting a drag.+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({+ id: mediaItem.id,+ })const imageUrl = mediaItem.small_url || mediaItem.mini_url || mediaItem.original_url+ const style = {+ transform: CSS.Transform.toString(transform),+ transition,+ }+return (- <div className="group relative aspect-square overflow-hidden rounded-lg border border-border bg-muted">+ <div+ ref={setNodeRef}+ style={style}+ {...attributes}+ {...listeners}+ className={`group relative aspect-square cursor-grab overflow-hidden rounded-md border border-border bg-muted touch-none active:cursor-grabbing ${+ isDragging ? 'opacity-40 ring-2 ring-primary/40' : ''+ }`}+ >{imageUrl ? (- <img src={imageUrl} alt={mediaItem.alt ?? ''} className="size-full object-cover" />+ <img+ src={imageUrl}+ alt={mediaItem.alt ?? ''}+ draggable={false}+ className="size-full object-cover transition-transform duration-300 ease-out group-hover:scale-105"+ />) : (<div className="flex size-full items-center justify-center text-muted-foreground"><ImagePlusIcon className="size-6" /></div>)}- <button- type="button"- onClick={onDelete}- className="absolute top-1.5 right-1.5 hidden group-hover:inline-flex items-center justify-center rounded-md size-6 bg-background/90 text-muted-foreground hover:text-destructive hover:bg-background shadow-sm transition-colors"- >- <XIcon className="size-3.5" />- </button>++ <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-end gap-1 p-1.5 opacity-0 translate-y-1 transition-all duration-200 ease-out group-hover:pointer-events-auto group-hover:opacity-100 group-hover:translate-y-0 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-focus-within:translate-y-0">+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ aria-label="Edit media"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => {+ e.stopPropagation()+ onEdit()+ }}+ className="shadow-sm"+ >+ <PencilIcon />+ </Button>+ <Button+ type="button"+ variant="outline"+ size="icon-sm"+ aria-label="Delete image"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => {+ e.stopPropagation()+ onDelete()+ }}+ className="shadow-sm hover:text-destructive"+ >+ <TrashIcon />+ </Button>+ </div></div>)}diff --git a/packages/admin/vite.config.ts b/packages/admin/vite.config.tsindex 73ce709353..3ddb19146a 100644--- a/packages/admin/vite.config.ts+++ b/packages/admin/vite.config.ts@@ -28,6 +28,17 @@ export default defineConfig({'http://localhost:3000',changeOrigin: true,},+ // Active Storage's Disk service issues presigned URLs against `/rails/active_storage/...`+ // on the Rails origin. Without proxying, the SPA's PUT from :5173 hits :3000+ // cross-origin and the browser blocks it ("Failed to fetch") because+ // ActiveStorage::DiskController doesn't speak CORS. Proxying keeps it same-origin.+ '/rails': {+ target:+ process.env.VITE_API_PROXY_TARGET ||+ process.env.VITE_SPREE_API_URL ||+ 'http://localhost:3000',+ changeOrigin: true,+ },},},})diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b3646e5b5b..08cc64b05b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -24,6 +24,15 @@ importers:'@base-ui/react':specifier: ^1.4.1version: 1.4.1(@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])+ '@dnd-kit/core':+ specifier: ^6.3.1+ '@dnd-kit/sortable':+ specifier: ^10.0.0+ version: 10.0.0(@dnd-kit/[email protected]([email protected]([email protected]))([email protected]))([email protected])+ '@dnd-kit/utilities':+ specifier: ^3.2.2+ version: 3.2.2([email protected])'@fontsource-variable/geist':specifier: ^5.2.8version: 5.2.8@@ -598,6 +607,28 @@ packages:'@date-fns/[email protected]':resolution: {integrity: sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==}+ '@dnd-kit/[email protected]':+ resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}+ peerDependencies:+ react: '>=16.8.0'++ '@dnd-kit/[email protected]':+ resolution: {integrity: sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==}+ peerDependencies:+ react: '>=16.8.0'+ react-dom: '>=16.8.0'++ '@dnd-kit/[email protected]':+ resolution: {integrity: sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==}+ peerDependencies:+ '@dnd-kit/core': ^6.3.0+ react: '>=16.8.0'++ '@dnd-kit/[email protected]':+ resolution: {integrity: sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==}+ peerDependencies:+ react: '>=16.8.0'+'@dotenvx/[email protected]':resolution: {integrity: sha512-v4FA/Lw3pTEloLxBqTOaYDX6MNo0Jo7lGBsPZhwnJBqRJp0AzQg1ZZNxrFsh6HVC6QWeWrfIKLn0y2eyIXaVDg==}hasBin: true@@ -4382,6 +4413,31 @@ snapshots:'@date-fns/[email protected]': {}+ '@dnd-kit/[email protected]([email protected])':+ dependencies:+ react: 19.2.6+ tslib: 2.8.1++ dependencies:+ '@dnd-kit/accessibility': 3.1.1([email protected])+ '@dnd-kit/utilities': 3.2.2([email protected])+ react: 19.2.6+ react-dom: 19.2.6([email protected])+ tslib: 2.8.1++ '@dnd-kit/[email protected](@dnd-kit/[email protected]([email protected]([email protected]))([email protected]))([email protected])':+ dependencies:+ '@dnd-kit/utilities': 3.2.2([email protected])+ react: 19.2.6+ tslib: 2.8.1++ '@dnd-kit/[email protected]([email protected])':+ dependencies:+ react: 19.2.6+ tslib: 2.8.1+'@dotenvx/[email protected]':dependencies:commander: 11.1.0diff --git a/spree/admin/app/controllers/spree/admin/assets_controller.rb b/spree/admin/app/controllers/spree/admin/assets_controller.rbindex 73dd5ff024..a240daadb3 100644--- a/spree/admin/app/controllers/spree/admin/assets_controller.rb+++ b/spree/admin/app/controllers/spree/admin/assets_controller.rb@@ -38,8 +38,14 @@ module Spreeprivate+ # Includes :variant_ids so the variant-assignment checkboxes mass-assign+ # straight into Spree::Asset#variant_ids= — the model resolves prefixed+ # ids and rejects cross-product variants.def permitted_resource_params- params.require(:asset).permit(Spree::PermittedAttributes.asset_attributes)+ params.require(:asset).permit(+ *Spree::PermittedAttributes.asset_attributes,+ variant_ids: []+ )enddef create_turbo_stream_enabled?diff --git a/spree/admin/app/controllers/spree/admin/products_controller.rb b/spree/admin/app/controllers/spree/admin/products_controller.rbindex 4fe8b54d05..ff2c84e266 100644--- a/spree/admin/app/controllers/spree/admin/products_controller.rb+++ b/spree/admin/app/controllers/spree/admin/products_controller.rb@@ -21,7 +21,7 @@ module Spreenew_action.before :build_master_stock_itemsedit_action.before :build_master_pricesedit_action.before :build_master_stock_items- create.after :assign_master_images+ create.after :assign_session_uploaded_assetsupdate.before :skip_updating_statusupdate.before :update_statusupdate.before :remove_empty_params@@ -185,7 +185,7 @@ module Spree@product_variant_ids[variant.human_name] = variant.id.to_s@product_variant_prefix_ids[variant.human_name] = variant.to_param- image = variant.primary_media+ image = variant.primary_media || @product.primary_mediaif image.present? && image.attached? && image.variable?@product_variant_images[variant.human_name] = helpers.spree_image_url(image, variant: :mini)end@@ -287,15 +287,13 @@ module Spree{}end- def assign_master_images- return unless @product.master.persisted?-- uploaded_assets = session_uploaded_assets('Spree::Variant')+ def assign_session_uploaded_assets+ uploaded_assets = session_uploaded_assets('Spree::Product')return if uploaded_assets.empty?- uploaded_assets.update_all(viewable_id: @product.master.id, viewable_type: 'Spree::Variant', updated_at: Time.current)- clear_session_for_uploaded_assets('Spree::Variant')+ uploaded_assets.update_all(viewable_id: @product.id, viewable_type: 'Spree::Product', updated_at: Time.current)+ clear_session_for_uploaded_assets('Spree::Product')enddef check_slug_availabilitydiff --git a/spree/admin/app/helpers/spree/admin/assets_helper.rb b/spree/admin/app/helpers/spree/admin/assets_helper.rbindex e1559127be..7b1f76175a 100644--- a/spree/admin/app/helpers/spree/admin/assets_helper.rb+++ b/spree/admin/app/helpers/spree/admin/assets_helper.rb@@ -3,7 +3,11 @@ module Spreemodule AssetsHelperdef media_form_assets(viewable, viewable_type)if viewable&.persisted?- viewable.images+ # Product#images delegates to the master variant (legacy alias), so+ # 5.5+ product-level uploads wouldn't show. gallery_media returns+ # product-level media when present and falls back to legacy+ # variant-pinned images during the transition.+ viewable.respond_to?(:gallery_media) ? viewable.gallery_media : viewable.imageselsif session_uploaded_assets(viewable_type).any?Spree::Asset.accessible_by(current_ability, :manage).where(id: session_uploaded_assets(viewable_type))elsediff --git a/spree/admin/app/views/spree/admin/assets/edit.html.erb b/spree/admin/app/views/spree/admin/assets/edit.html.erbindex 18a09fb9c8..076067c20e 100644--- a/spree/admin/app/views/spree/admin/assets/edit.html.erb+++ b/spree/admin/app/views/spree/admin/assets/edit.html.erb@@ -1,17 +1,72 @@-<%= turbo_frame_tag :dialog do %>- <%= dialog_header(Spree.t(:edit) + ' ' + Spree.t(:image)) %>+<%= turbo_frame_tag :drawer do %><%= form_with model: @asset, url: spree.admin_asset_path(@asset), method: :put, scope: :asset do |f| %>- <div class="dialog-body pb-0" data-turbo-permanent id="asset-<%= @asset.key.parameterize %>">- <%= f.spree_file_field :attachment, width: 200, height: 200, can_delete: false, label: Spree.t(:image) %>+ <%= drawer_header(Spree.t(:edit) + ' ' + Spree.t(:image)) %>++ <div class="drawer-body">+ <% if @asset.attachment.attached? %>+ <% blob_url_opts = { host: request.host_with_port, protocol: (request.ssl? ? 'https' : 'http') } %>+ <% download_url = Rails.application.routes.url_helpers.rails_blob_url(@asset.attachment.blob, **blob_url_opts, disposition: 'attachment') %>+ <% original_url = Rails.application.routes.url_helpers.rails_blob_url(@asset.attachment.blob, **blob_url_opts) %>+ <div class="mb-4 rounded-lg border bg-light overflow-hidden">+ <a href="<%= original_url %>"+ target="_blank"+ rel="noopener"+ title="<%= Spree.t(:view_full_size) %>"+ style="display: block; position: relative; cursor: zoom-in;">+ <%= spree_image_tag(@asset.attachment, variant: :large, alt: @asset.alt, class: 'w-full max-h-96 object-contain') %>+ <span style="position: absolute; top: 8px; right: 8px; display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 6px; background: rgba(255,255,255,0.95); color: #4b5563; box-shadow: 0 1px 2px rgba(0,0,0,0.1); pointer-events: none;">+ <%= icon('zoom-in', class: 'mr-0') %>+ </span>+ </a>+ </div>+ <div class="flex gap-2 mb-4">+ <%= link_to original_url, target: '_blank', rel: 'noopener', class: 'btn btn-light btn-sm' do %>+ <%= icon('external-link', class: 'mr-1') %><%= Spree.t(:view_full_size) %>+ <% end %>+ <%= link_to download_url, target: '_blank', rel: 'noopener', class: 'btn btn-light btn-sm' do %>+ <%= icon('download', class: 'mr-1') %><%= Spree.t(:download) %>+ <% end %>+ </div>+ <% else %>+ <%= f.spree_file_field :attachment, width: 200, height: 200, can_delete: false, label: Spree.t(:image) %>+ <% end %>++ <%= f.spree_text_area :alt, label: Spree.t(:alt_text), rows: 3 %>++ <%# Variant assignment shows only for product-level assets — variant-pinned assets+ already live on a single variant via the polymorphic viewable, so the+ join-table UI doesn't apply. Empty submission (no boxes ticked) clears+ all links thanks to the hidden field below. %>+ <% if @asset.viewable_type == 'Spree::Product' && @asset.viewable.present? && @asset.viewable.variants.any? %>+ <% product = @asset.viewable %>+ <% linked_ids = @asset.variant_media.pluck(:variant_id).to_set %>+ <div class="mt-4 pt-4 border-t">+ <label class="form-label"><%= Spree.t(:assigned_variants) %></label>+ <p class="text-muted small mb-2">+ <%= Spree.t(:assigned_variants_help) %>+ </p>+ <%= hidden_field_tag 'asset[variant_ids][]', '' %>+ <div class="flex flex-col gap-1">+ <% product.variants.each do |variant| %>+ <% chip_id = "asset_variant_#{variant.id}" %>+ <div class="custom-control form-checkbox rounded-lg hover:bg-gray-100 p-2 transition-colors duration-100 ease-linear">+ <%= check_box_tag('asset[variant_ids][]', variant.to_param, linked_ids.include?(variant.id), id: chip_id, class: 'custom-control-input') %>+ <%= label_tag chip_id, class: 'custom-control-label' do %>+ <%= variant.descriptive_name.presence || variant.sku %>+ <% end %>+ </div>+ <% end %>+ </div>+ </div>+ <% end %></div>- <div class="dialog-body" style="min-height: 200px">- <%= f.spree_text_area :alt, label: Spree.t(:alt_text), rows: 4 %>- </div>- <div class="dialog-footer">++ <div class="drawer-footer gap-3"><%= turbo_save_button_tag %>+ <%= drawer_discard_button %><%= link_to Spree.t('actions.destroy'), object_url(@asset),data: { turbo_method: :delete, turbo_confirm: Spree.t(:are_you_sure_delete), turbo_frame: '_top' },class: 'btn btn-danger ml-auto' if can?(:destroy, @asset) %></div><% end %>-<% end %>\ No newline at end of file+<% end %>diff --git a/spree/admin/app/views/spree/admin/products/_form.html.erb b/spree/admin/app/views/spree/admin/products/_form.html.erbindex a7e3cb6618..4cfc99ac71 100644--- a/spree/admin/app/views/spree/admin/products/_form.html.erb+++ b/spree/admin/app/views/spree/admin/products/_form.html.erb@@ -1,7 +1,7 @@<div class="grid grid-cols-12 gap-6" data-controller="product-form slug-form seo-form" data-seo-form-editor-value="tinymce"><div class="col-span-12 md:col-span-8"><%= render 'spree/admin/products/form/base', f: f %>- <%= render 'spree/admin/shared/media_form', viewable: @product.master, viewable_type: 'Spree::Variant' %>+ <%= render 'spree/admin/shared/media_form', viewable: @product, viewable_type: 'Spree::Product' %><%= f.fields_for :master, @product.master do |vf| %><%= render 'spree/admin/variants/form/pricing', f: vf %><% end unless @product.has_variants? %>diff --git a/spree/admin/app/views/spree/admin/shared/_media_asset.html.erb b/spree/admin/app/views/spree/admin/shared/_media_asset.html.erbindex bd0817083c..3e6c612cbf 100644--- a/spree/admin/app/views/spree/admin/shared/_media_asset.html.erb+++ b/spree/admin/app/views/spree/admin/shared/_media_asset.html.erb@@ -7,7 +7,7 @@<button class="btn btn-light btn-sm px-1"><%= icon('grip-vertical', class: 'mr-0') %></button></div>- <%= link_to spree.edit_admin_asset_path(asset), data: { turbo_frame: 'dialog', action: 'dialog#open' } do %>+ <%= link_to spree.edit_admin_asset_path(asset), data: { turbo_frame: 'drawer', action: 'drawer#open' } do %><%= spree_image_tag(asset.attachment, width: 200, height: 200, alt: asset.alt, class: 'w-full block h-full absolute') %><% end %></div>diff --git a/spree/admin/app/views/spree/admin/variants/edit.html.erb b/spree/admin/app/views/spree/admin/variants/edit.html.erbindex 57b3d3762f..c50d65ae05 100644--- a/spree/admin/app/views/spree/admin/variants/edit.html.erb+++ b/spree/admin/app/views/spree/admin/variants/edit.html.erb@@ -10,7 +10,6 @@<%= render 'spree/admin/variants/form/basic', f: f %><%= render 'spree/admin/variants/form/pricing', f: f %><%= render 'spree/admin/variants/form/inventory', f: f %>- <%= render 'spree/admin/shared/media_form', viewable: @variant, viewable_type: 'Spree::Variant' %><%= render 'spree/admin/shared/edit_resource_links', f: f %></div></div>diff --git a/spree/admin/spec/controllers/spree/admin/assets_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/assets_controller_spec.rbindex ccede6604e..16df07895c 100644--- a/spree/admin/spec/controllers/spree/admin/assets_controller_spec.rb+++ b/spree/admin/spec/controllers/spree/admin/assets_controller_spec.rb@@ -46,6 +46,74 @@ describe Spree::Admin::AssetsController, type: :controller doendend+ context 'with product viewable' do+ subject { post :create, params: params, format: :turbo_stream }++ let(:params) do+ { asset: { alt: 'product image', attachment: attachment, viewable_id: product.id, viewable_type: 'Spree::Product' } }+ end++ it 'attaches the asset to the product' do+ expect { subject }.to change(Spree::Asset, :count).by(1)++ expect(response).to have_http_status(:ok)+ expect(asset.viewable).to eq(product)+ expect(asset.viewable_type).to eq('Spree::Product')+ end++ it 'increments product media_count counter cache' do+ expect { subject }.to change { product.reload.media_count }.by(1)+ end+ end++ context 'with product viewable and variant_ids' do+ subject { post :create, params: params, format: :turbo_stream }++ let!(:variant_a) { create(:variant, product: product) }+ let!(:variant_b) { create(:variant, product: product) }+ let(:params) do+ {+ asset: {+ alt: 'shared image',+ attachment: attachment,+ viewable_id: product.id,+ viewable_type: 'Spree::Product',+ variant_ids: [variant_a.to_param, variant_b.to_param]+ }+ }+ end++ it 'permits variant_ids and creates VariantMedia rows for each picked variant' do+ expect { subject }+ .to change(Spree::Asset, :count).by(1)+ .and change(Spree::VariantMedia, :count).by(2)++ expect(response).to have_http_status(:ok)+ created = Spree::Asset.last+ expect(created.variant_media.pluck(:variant_id)).to contain_exactly(variant_a.id, variant_b.id)+ end++ it 'rejects variant_ids belonging to a different product' do+ other_variant = create(:variant, product: create(:product, stores: [store]))++ expect {+ post :create,+ params: {+ asset: {+ alt: 'tampered',+ attachment: attachment,+ viewable_id: product.id,+ viewable_type: 'Spree::Product',+ variant_ids: [variant_a.to_param, other_variant.to_param]+ }+ },+ format: :turbo_stream+ }.to change(Spree::VariantMedia, :count).by(1)++ expect(asset.variant_media.pluck(:variant_id)).to contain_exactly(variant_a.id)+ end+ end+context 'with viewable and type Spree::Image' dosubject { post :create, params: params, format: :turbo_stream }@@ -81,6 +149,69 @@ describe Spree::Admin::AssetsController, type: :controller doexpect(response).to have_http_status(:ok)expect(image.reload.alt).to eq('Alt text')end++ context 'when assigning variants on a product-level asset' do+ let!(:asset) { create(:image, viewable: product) }+ let!(:variant_a) { create(:variant, product: product) }+ let!(:variant_b) { create(:variant, product: product) }++ let(:put_with_variants) do+ ->(ids) {+ put :update,+ params: { id: asset.to_param, asset: { alt: 'x', variant_ids: ids } },+ as: :turbo_stream+ }+ end++ it 'creates VariantMedia rows for the picked variants' do+ expect { put_with_variants.call([variant_a.to_param]) }+ .to change(Spree::VariantMedia, :count).by(1)++ expect(asset.variant_media.pluck(:variant_id)).to contain_exactly(variant_a.id)+ end++ it 'unlinks variants that were unchecked' do+ Spree::VariantMedia.create!(asset: asset, variant: variant_a)+ Spree::VariantMedia.create!(asset: asset, variant: variant_b)++ expect { put_with_variants.call([variant_a.to_param]) }+ .to change(Spree::VariantMedia, :count).by(-1)++ expect(asset.variant_media.pluck(:variant_id)).to contain_exactly(variant_a.id)+ end++ it 'clears all links when no variants are checked' do+ Spree::VariantMedia.create!(asset: asset, variant: variant_a)+ # The form posts an empty hidden field plus zero checkboxes; the+ # controller treats that as "unlink everything".+ expect { put_with_variants.call([]) }+ .to change(Spree::VariantMedia, :count).by(-1)+ end++ it 'rejects variant ids belonging to a different product' do+ other_product = create(:product, stores: [store])+ other_variant = create(:variant, product: other_product)++ expect { put_with_variants.call([other_variant.to_param]) }+ .not_to change(Spree::VariantMedia, :count)+ end+ end++ context 'when the asset is variant-pinned (legacy)' do+ let!(:asset) { create(:image, viewable: product.master) }+ let!(:variant_a) { create(:variant, product: product) }++ it 'ignores variant_ids — variant-level assets do not use the join table' do+ expect {+ put :update,+ params: {+ id: asset.to_param,+ asset: { alt: 'x', variant_ids: [variant_a.to_param] },+ },+ as: :turbo_stream+ }.not_to change(Spree::VariantMedia, :count)+ end+ endenddescribe '#destroy' do@@ -109,4 +240,37 @@ describe Spree::Admin::AssetsController, type: :controller doexpect(response).to have_http_status(:ok)endend++ describe '#edit' do+ subject { get :edit, params: { id: asset.to_param } }++ context 'for a product-level asset with sibling variants' do+ let!(:asset) { create(:image, viewable: product) }+ let!(:variant_a) { create(:variant, product: product) }++ it 'renders a checkbox per variant for variant_ids' do+ subject++ expect(response).to have_http_status(:ok)+ expect(response.body).to match(%r{<input[^>]+type="checkbox"[^>]+name="asset\[variant_ids\]\[\]"[^>]+value="#{variant_a.to_param}"})+ end++ it 'links to the original blob for download with attachment disposition' do+ subject++ expect(response.body).to include('disposition=attachment')+ end+ end++ context 'for a variant-pinned asset (legacy)' do+ let!(:asset) { create(:image, viewable: product.master) }++ it 'does not render variant_ids inputs' do+ subject++ expect(response).to have_http_status(:ok)+ expect(response.body).not_to include('name="asset[variant_ids][]"')+ end+ end+ endenddiff --git a/spree/admin/spec/helpers/spree/admin/assets_helper_spec.rb b/spree/admin/spec/helpers/spree/admin/assets_helper_spec.rbindex 7de9c7b9e6..f73a1cb086 100644--- a/spree/admin/spec/helpers/spree/admin/assets_helper_spec.rb+++ b/spree/admin/spec/helpers/spree/admin/assets_helper_spec.rb@@ -17,6 +17,24 @@ describe Spree::Admin::AssetsHelper doendend+ context 'when product is persisted with product-level media (5.5+)' do+ let(:product) { create(:product) }+ let!(:product_image) { create(:image, viewable: product) }++ it 'returns the product-level assets via gallery_media' do+ expect(helper.media_form_assets(product, 'Spree::Product')).to include(product_image)+ end+ end++ context 'when product is persisted with legacy variant-pinned media' do+ let(:product) { create(:product) }+ let!(:master_image) { create(:image, viewable: product.master) }++ it 'falls back to variant images via gallery_media' do+ expect(helper.media_form_assets(product, 'Spree::Product')).to include(master_image)+ end+ end+context 'when variant is not persisted' dolet(:variant) { build(:variant, id: nil) }diff --git a/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/media_controller.rbindex df9dc7ff8e..4cc430b532 100644--- a/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/media_controller.rb@@ -39,12 +39,30 @@ module Spree@parent = if params[:variant_id].present?@product.variants_including_master.find_by_prefix_id!(params[:variant_id])else- @product.master+ @productendend+ # Variants store assets via the polymorphic `images` association; products own+ # their gallery via `media`. Both resolve to `Spree::Asset` rows with different+ # `viewable_type` values.def parent_association- :images+ params[:variant_id].present? ? :images : :media+ end++ # For product-scoped listings we surface BOTH product-level assets and any+ # legacy master-pinned assets, so existing data keeps showing up while+ # merchants migrate. New uploads land on `Spree::Product` (see #set_parent).+ def scope+ return super if params[:variant_id].present?++ Spree::Asset.where(+ viewable_type: 'Spree::Product', viewable_id: @product.id+ ).or(+ Spree::Asset.where(+ viewable_type: 'Spree::Variant', viewable_id: @product.master&.id+ )+ ).order(:position)endALLOWED_MEDIA_TYPES = -> { [Spree::Asset, *Spree::Asset.descendants].map(&:name).to_set.freeze }@@ -56,14 +74,14 @@ module Spreeraise ArgumentError, "Invalid media type: #{media_type}"end- media = @parent.images.build(permitted_params.except(:type, :url, :signed_id))+ media = @parent.send(parent_association).build(permitted_params.except(:type, :url, :signed_id))media.type = media_typemediaenddef permitted_params- params.permit(:type, :alt, :position, :attachment, :url, :signed_id)+ params.permit(:type, :alt, :position, :attachment, :url, :signed_id, variant_ids: [])enddef create_from_urldiff --git a/spree/api/app/serializers/spree/api/v3/admin/media_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/media_serializer.rbindex 1c44338557..bf856ebe5d 100644--- a/spree/api/app/serializers/spree/api/v3/admin/media_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/media_serializer.rb@@ -4,7 +4,8 @@ module Spreemodule Adminclass MediaSerializer < V3::MediaSerializertypelize viewable_type: :string, viewable_id: :string,- metadata: 'Record<string, unknown>'+ metadata: 'Record<string, unknown>',+ download_url: [:string, nullable: true]attributes created_at: :iso8601, updated_at: :iso8601@@ -12,6 +13,26 @@ module Spreeasset.viewable&.prefixed_idend+ # Forces Content-Disposition: attachment so admins downloading from+ # cloud storage (S3) get a save-as instead of an inline view. Mirrors+ # the host resolution from the `:cdn_image` direct route since+ # rails_blob_url itself doesn't fall back to Spree.cdn_host or the+ # current store's domain.+ attribute :download_url do |asset|+ next nil unless asset.attachment&.attached?++ host = Spree.cdn_host.presence ||+ Rails.application.routes.default_url_options[:host] ||+ Spree::Store.current&.url_or_custom_domain+ helpers = Rails.application.routes.url_helpers++ if host.present?+ helpers.rails_blob_url(asset.attachment.blob, disposition: 'attachment', host: host)+ else+ helpers.rails_blob_path(asset.attachment.blob, disposition: 'attachment')+ end+ end+attributes :metadata, :viewable_typeendenddiff --git a/spree/api/app/serializers/spree/api/v3/media_serializer.rb b/spree/api/app/serializers/spree/api/v3/media_serializer.rbindex c63d72aa4e..0e478710d1 100644--- a/spree/api/app/serializers/spree/api/v3/media_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/media_serializer.rb@@ -19,13 +19,15 @@ module Spreeend# Returns prefixed IDs of variants this media is associated with.- # Currently: single variant via viewable (legacy). In 6.0: multiple via VariantMedia join table.+ # Two paths coexist in 5.5:+ # - legacy: asset.viewable IS the variant (direct upload, viewable_type 'Spree::Variant')+ # - new: asset.variants — product-level asset linked via VariantMedia rows+ # Both are reported so the admin can show a unified "assigned variants" list.attribute :variant_ids do |asset|- if asset.viewable_type == 'Spree::Variant'- [asset.viewable&.prefixed_id].compact- else- []- end+ ids = []+ ids << asset.viewable&.prefixed_id if asset.viewable_type == 'Spree::Variant' && asset.viewable+ ids.concat(asset.variants.map(&:prefixed_id)) if asset.viewable_type == 'Spree::Product'+ ids.compact.uniqendattributes :position, :alt, :media_type,diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rbindex 807c4407cc..1d270da6e4 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/products/media_controller_spec.rb@@ -6,7 +6,7 @@ RSpec.describe Spree::Api::V3::Admin::MediaController, type: :controller doinclude_context 'API v3 Admin authenticated'let!(:product) { create(:product, stores: [store]) }- let!(:image) { create(:image, viewable: product.master) }+ let!(:image) { create(:image, viewable: product) }before { request.headers.merge!(headers) }@@ -43,7 +43,7 @@ RSpec.describe Spree::Api::V3::Admin::MediaController, type: :controller doexpect(response).to have_http_status(:unprocessable_content)end- it 'enqueues SaveFromUrlJob when url is provided' do+ it 'enqueues SaveFromUrlJob for the product when url is provided' doexpect {post :create, params: {product_id: product.prefixed_id,@@ -51,8 +51,8 @@ RSpec.describe Spree::Api::V3::Admin::MediaController, type: :controller doposition: 2}, as: :json}.to have_enqueued_job(Spree::Images::SaveFromUrlJob).with(- product.master.id,- 'Spree::Variant',+ product.id,+ 'Spree::Product','https://example.com/image.jpg',nil,2@@ -85,6 +85,50 @@ RSpec.describe Spree::Api::V3::Admin::MediaController, type: :controller doexpect(response).to have_http_status(:ok)expect(image.reload.position).to eq(5)end++ context 'with variant_ids on a product-level asset' do+ let!(:product_asset) { create(:image, viewable: product) }+ let!(:variant_a) { create(:variant, product: product) }+ let!(:variant_b) { create(:variant, product: product) }++ it 'links the picked variants' do+ expect {+ patch :update, params: {+ product_id: product.prefixed_id,+ id: product_asset.prefixed_id,+ variant_ids: [variant_a.to_param, variant_b.to_param]+ }, as: :json+ }.to change(Spree::VariantMedia, :count).by(2)++ expect(response).to have_http_status(:ok)+ expect(product_asset.variant_media.pluck(:variant_id)).to contain_exactly(variant_a.id, variant_b.id)+ end++ it 'replaces the link set on subsequent calls' do+ Spree::VariantMedia.create!(asset: product_asset, variant: variant_a)++ patch :update, params: {+ product_id: product.prefixed_id,+ id: product_asset.prefixed_id,+ variant_ids: [variant_b.to_param]+ }, as: :json++ expect(product_asset.variant_media.pluck(:variant_id)).to contain_exactly(variant_b.id)+ end++ it 'silently rejects variants from a different product' do+ other_variant = create(:variant, product: create(:product, stores: [store]))++ patch :update, params: {+ product_id: product.prefixed_id,+ id: product_asset.prefixed_id,+ variant_ids: [other_variant.to_param]+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(product_asset.variant_media).to be_empty+ end+ endenddescribe 'DELETE #destroy' do@@ -94,11 +138,22 @@ RSpec.describe Spree::Api::V3::Admin::MediaController, type: :controller doproduct_id: product.prefixed_id,id: image.prefixed_id}, as: :json- }.to change(product.master.images, :count).by(-1)+ }.to change(product.media, :count).by(-1)expect(response).to have_http_status(:no_content)endend++ context 'with legacy master-pinned assets' do+ let!(:legacy_master_image) { create(:image, viewable: product.master) }++ it 'still surfaces legacy assets in the listing' do+ get :index, params: { product_id: product.prefixed_id }, as: :json++ ids = json_response['data'].map { |a| a['id'] }+ expect(ids).to include(legacy_master_image.prefixed_id)+ end+ endenddescribe 'variant assets' dodiff --git a/spree/core/app/jobs/spree/images/save_from_url_job.rb b/spree/core/app/jobs/spree/images/save_from_url_job.rbindex 04f2014bac..21238b8833 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@@ -11,7 +11,7 @@ module Spreediscard_on URI::InvalidURIErrordiscard_on SsrfFilter::Error- def perform(viewable_id, viewable_type, external_url, external_id = nil, position = nil)+ 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::Image.ensure_metafield_definition_exists!(Spree::Image::EXTERNAL_URL_METAFIELD_KEY)@@ -30,9 +30,14 @@ module Spree# don't re-download the image if it's already been downloaded# still trigger save! if position has changed- image.save! and return if image_already_saved?(image, external_url)+ if image_already_saved?(image, external_url)+ image.save!+ link_to_variant(image, link_variant_id)+ return+ enddownload_and_attach_image(external_url, image, external_id)+ link_to_variant(image, link_variant_id)rescue ActiveStorage::IntegrityError => eraise e unless Rails.env.test?end@@ -85,21 +90,31 @@ module Spreeimage.persisted? && image.attachment.attached? && image.external_url.present? && external_url == image.external_urlend+ # `Product#images` delegates to the master variant (legacy alias) — use+ # `Product#media` so 5.5 product-level uploads don't get re-pinned to master.+ def viewable_assets(viewable)+ viewable.is_a?(Spree::Product) ? viewable.media : viewable.images+ end+def image_scope(viewable)- if Spree::Image.respond_to?(:with_deleted)- viewable.images.with_deleted- else- viewable.images- end+ scope = viewable_assets(viewable)+ scope.respond_to?(:with_deleted) ? scope.with_deleted : scopeenddef find_or_initialize_image(viewable, external_url, external_id = nil)if external_id.present? && viewable.respond_to?(:external_id)image_scope(viewable).find_or_initialize_by(external_id: external_id)else- image_scope(viewable).with_external_url(external_url).first || viewable.images.new+ image_scope(viewable).with_external_url(external_url).first || viewable_assets(viewable).newendend++ def link_to_variant(image, variant_id)+ return if variant_id.blank?+ return unless image.persisted? && image.viewable_type == 'Spree::Product'++ Spree::VariantMedia.find_or_create_by(variant_id: variant_id, media_id: image.id)+ endendendenddiff --git a/spree/core/app/jobs/spree/media/migrate_product_assets_job.rb b/spree/core/app/jobs/spree/media/migrate_product_assets_job.rbnew file mode 100644index 0000000000..990440b31c--- /dev/null+++ b/spree/core/app/jobs/spree/media/migrate_product_assets_job.rb@@ -0,0 +1,83 @@+module Spree+ module Media+ # Per-product worker for the 5.4 → 5.5 media migration. Idempotent.+ class MigrateProductAssetsJob < Spree::BaseJob+ queue_as Spree.queues.images++ def perform(product_id)+ product = Spree::Product.includes(:master, :variants).find_by(id: product_id)+ return unless product++ # One query for all variant-pinned assets on the product (master ++ # non-master). Grouping by viewable_id avoids N queries per variant.+ viewable_ids = product.variants.map(&:id)+ viewable_ids << product.master.id if product.master+ return if viewable_ids.empty?++ assets_by_variant = Spree::Asset+ .where(viewable_type: 'Spree::Variant', viewable_id: viewable_ids)+ .pluck(:id, :viewable_id)+ .group_by(&:last)+ .transform_values { |rows| rows.map(&:first) }+ return if assets_by_variant.empty?++ master_id = product.master&.id+ touched_variants = []++ product.variants.each do |variant|+ asset_ids = assets_by_variant[variant.id]+ next if asset_ids.blank?++ move_assets_to_product(asset_ids, product)+ link_assets_to_variant(asset_ids, variant.id)+ touched_variants << variant+ end++ if master_id && (master_asset_ids = assets_by_variant[master_id]).present?+ move_assets_to_product(master_asset_ids, product)+ touched_variants << product.master+ end++ # update_all + upsert_all skip callbacks, so refresh thumbnails by hand.+ touched_variants.each(&:update_thumbnail!)+ recalculate_counters(product)+ end++ private++ def move_assets_to_product(asset_ids, product)+ Spree::Asset.where(id: asset_ids).update_all(+ viewable_type: 'Spree::Product',+ viewable_id: product.id,+ updated_at: Time.current+ )+ end++ def link_assets_to_variant(asset_ids, variant_id)+ rows = asset_ids.map { |asset_id| { variant_id: variant_id, media_id: asset_id } }++ # MySQL infers the conflict target from the unique index; only PG/SQLite+ # need the explicit `unique_by:`.+ opts = { on_duplicate: :skip }+ if %w[PostgreSQL SQLite].include?(ActiveRecord::Base.connection.adapter_name)+ opts[:unique_by] = :idx_variant_media_unique+ end++ Spree::VariantMedia.upsert_all(rows, **opts)+ end++ def recalculate_counters(product)+ new_count = product.media.count+ new_primary_id = product.media.order(:position).pick(:id)++ return if product.media_count == new_count && product.primary_media_id == new_primary_id++ product.update_columns(+ media_count: new_count,+ primary_media_id: new_primary_id,+ updated_at: Time.current+ )+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/asset.rb b/spree/core/app/models/spree/asset.rbindex 053c4b2faa..c0dbb73f98 100644--- a/spree/core/app/models/spree/asset.rb+++ b/spree/core/app/models/spree/asset.rb@@ -28,6 +28,9 @@ module Spreeafter_initialize { self.media_type ||= 'image' }belongs_to :viewable, polymorphic: true, touch: true+ has_many :variant_media, class_name: 'Spree::VariantMedia', foreign_key: :media_id,+ dependent: :destroy, inverse_of: :asset+ has_many :variants, through: :variant_media, source: :variant, class_name: 'Spree::Variant'acts_as_list scope: [:viewable_id, :viewable_type]delegate :key, :attached?, :variant, :variable?, :blob, :filename, :variation, to: :attachment@@ -91,6 +94,15 @@ module Spreeendend+ # Accepts prefixed IDs ("variant_abc") or raw IDs from admin forms.+ # Variants from a different product are silently dropped — the security+ # boundary against form tampering.+ def variant_ids=(ids)+ return if viewable_type != 'Spree::Product' || product.blank?++ super(Spree::VariantMedia.resolve_variant_ids(product, ids || []))+ end+def focal_pointreturn nil if focal_point_x.nil? || focal_point_y.nil?@@ -142,14 +154,21 @@ module Spreeprivatedef touch_product_variants- viewable.product.variants.touch_all+ product = viewable.is_a?(Spree::Product) ? viewable : viewable.product+ product.variants.touch_allenddef should_touch_product_variants?- viewable.is_a?(Spree::Variant) &&- viewable.is_master? &&- viewable.product.has_variants? &&- saved_change_to_position?+ return false unless saved_change_to_position?++ case viewable+ when Spree::Product+ true+ when Spree::Variant+ viewable.is_master? && viewable.product.has_variants?+ else+ false+ endenddef increment_viewable_media_count@@ -179,6 +198,10 @@ module Spreeviewable.product.update_thumbnail!when 'Spree::Product'viewable.update_thumbnail!+ # Linked variants resolve their own thumbnail through gallery_media,+ # which sorts by this asset's product-level position. Reorders or+ # destroys here can change a linked variant's first asset.+ variants.find_each(&:update_thumbnail!)endenddiff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex 9c4481a974..46234e89da 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -49,6 +49,15 @@ module Spreehas_many :option_values, through: :option_value_variants, dependent: :destroy, class_name: 'Spree::OptionValue'has_many :images, -> { order(:position) }, as: :viewable, dependent: :destroy, class_name: 'Spree::Asset'++ has_many :variant_media, class_name: 'Spree::VariantMedia', dependent: :destroy+ # Order through the asset's product-level position so a variant's gallery+ # follows whatever ordering the merchant set on the product. There's no+ # per-variant reordering — link/unlink only.+ has_many :associated_media,+ -> { order(Spree::Asset.arel_table[:position].asc) },+ through: :variant_media, source: :asset, class_name: 'Spree::Asset'+belongs_to :primary_media, class_name: 'Spree::Asset', optional: true, foreign_key: :primary_media_idhas_many :prices,@@ -262,16 +271,21 @@ module Spreeend# Returns the variant's media gallery.- # Currently returns direct images. In 6.0 will use variant_media join table.+ # Prefers product-level media linked via variant_media (5.5+) — these reuse+ # a single blob across variants. Falls back to direct variant images for+ # legacy uploads.# @return [ActiveRecord::Relation]def gallery_media+ return associated_media if has_associated_media?+imagesend- # Returns true if the variant has media.- # Uses loaded association when available, otherwise falls back to counter cache.+ # Returns true if the variant has media (linked product-level or direct images).+ # Uses loaded associations when available, otherwise falls back to counter cache.# @return [Boolean]def has_media?+ return true if has_associated_media?return images.any? if images.loaded?media_count.positive?@@ -279,6 +293,13 @@ module Spreealias has_images? has_media?+ # @return [Boolean] true if any product-level media is linked to this variant+ def has_associated_media?+ return variant_media.any? if variant_media.loaded?++ variant_media.exists?+ end+# @deprecated Use #primary_media instead.def default_imageSpree::Deprecation.warn('Spree::Variant#default_image is deprecated and will be removed in Spree 6.0. Please use Spree::Variant#primary_media instead.')@@ -287,8 +308,10 @@ module Spree# Updates primary_media_id to the first media item by position.# Called when media is added, removed, or reordered.+ # Uses gallery_media so product-level assets linked via VariantMedia are+ # considered alongside legacy variant-pinned images.def update_thumbnail!- first_media = images.order(:position).first+ first_media = gallery_media.firstupdate_column(:primary_media_id, first_media&.id)enddiff --git a/spree/core/app/models/spree/variant_media.rb b/spree/core/app/models/spree/variant_media.rbnew file mode 100644index 0000000000..e2ab45f180--- /dev/null+++ b/spree/core/app/models/spree/variant_media.rb@@ -0,0 +1,46 @@+module Spree+ # FK column is `media_id` (not `asset_id`) to match the 6.0 rename+ # Spree::Asset → Spree::Media. The `:asset` association name follows the+ # current parent class; in 6.0 it renames to `:media` without a column change.+ class VariantMedia < Spree.base_class+ self.table_name = 'spree_variant_media'++ belongs_to :variant, class_name: 'Spree::Variant', touch: true+ belongs_to :asset, class_name: 'Spree::Asset', foreign_key: :media_id, inverse_of: :variant_media++ validates :variant, :asset, presence: true+ validates :media_id, uniqueness: { scope: :variant_id }+ validate :asset_belongs_to_variant_product++ after_commit :refresh_variant_thumbnail, on: %i[create destroy]++ # Resolves an array of variant identifiers (prefixed ids or raw ids) to the+ # numeric ids of variants that belong to `product`. Anything else — bad+ # prefix, foreign product, garbage — is dropped. This is the security+ # boundary used by Spree::Asset#variant_ids=, so callers (forms, API params)+ # can't link assets to variants from another product.+ def self.resolve_variant_ids(product, variant_ids)+ ids = Array(variant_ids).reject(&:blank?)+ return [] if ids.empty?++ product.variants.filter_map do |variant|+ token = variant.id.to_s+ prefixed = variant.prefixed_id+ variant.id if ids.any? { |id| id.to_s == token || id == prefixed }+ end+ end++ private++ def asset_belongs_to_variant_product+ return if asset.blank? || variant.blank?+ return if asset.product&.id == variant.product_id++ errors.add(:asset, 'must belong to the same product as the variant')+ end++ def refresh_variant_thumbnail+ variant&.update_thumbnail!+ end+ end+enddiff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rbindex b39dcc00c7..5d904c80e0 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@@ -177,8 +177,20 @@ module Spreereturn if image_urls.empty?+ # Always attach to the product so blobs aren't duplicated across+ # variants. For non-master rows, pass the variant id so the job links+ # the resulting product-level asset to that variant via VariantMedia.+ link_variant_id = variant.is_master? ? nil : variant.id+image_urls.each do |image_url|- Spree::Images::SaveFromUrlJob.perform_later(variant.id, 'Spree::Variant', image_url)+ Spree::Images::SaveFromUrlJob.perform_later(+ product.id,+ 'Spree::Product',+ image_url,+ nil,+ nil,+ link_variant_id+ )endenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 59716a8821..966ead2d71 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -785,6 +785,8 @@ en:are_you_sure: Are you sure?are_you_sure_delete: Are you sure you want to delete this record?assets: Media+ assigned_variants: Assigned variants+ assigned_variants_help: Pick the variants this image represents. Leave blank to apply to all variants.associated_adjustment_closed: The associated adjustment is closed, and will not be recalculated. Do you want to open it?at_symbol: "@"attachments: Attachments@@ -2488,6 +2490,7 @@ en:view: Viewview_all: View allview_full_details: View full details+ view_full_size: View full sizeview_store: View storeview_your_store: View your storevisibility: Visibilitydiff --git a/spree/core/db/migrate/20260507162651_create_spree_variant_media.rb b/spree/core/db/migrate/20260507162651_create_spree_variant_media.rbnew file mode 100644index 0000000000..e84b02339f--- /dev/null+++ b/spree/core/db/migrate/20260507162651_create_spree_variant_media.rb@@ -0,0 +1,23 @@+class CreateSpreeVariantMedia < ActiveRecord::Migration[7.2]+ # `media_id` references spree_assets.id in 5.5 — the parent table renames to+ # spree_media in 6.0 (see 5.4-6.0-product-media-system.md Phase 3 of the 6.0+ # cleanup). Using `media_id` from the start saves a column rename in 6.0.+ #+ # Table name is `spree_variant_media` (not the Rails default `spree_variant_medias`)+ # since "media" reads as collective; the model overrides `self.table_name`.+ #+ # No per-variant `position` column — gallery order comes from the asset's+ # product-level position (Asset#position). Variant gallery resolution filters+ # product media down to the linked subset and inherits the product's order.+ def change+ create_table :spree_variant_media do |t|+ t.references :variant, null: false, index: false+ t.bigint :media_id, null: false+ t.timestamps+ end++ add_index :spree_variant_media, [:variant_id, :media_id], unique: true,+ name: 'idx_variant_media_unique'+ add_index :spree_variant_media, :media_id, name: 'idx_variant_media_media'+ end+enddiff --git a/spree/core/lib/tasks/media.rake b/spree/core/lib/tasks/media.rakeindex 073900dd2a..4652926e3d 100644--- a/spree/core/lib/tasks/media.rake+++ b/spree/core/lib/tasks/media.rake@@ -16,5 +16,32 @@ namespace :spree doputs 'Done!'end++ # Enqueues Spree::Media::MigrateProductAssetsJob for every product that+ # still has at least one variant-pinned asset. The job is idempotent, so+ # re-running this task is safe.+ #+ # ENV vars:+ # BATCH_SIZE — products fetched per scope batch (default: 500)+ desc 'Enqueue jobs to migrate legacy variant-pinned images to product-level media (opt-in, 5.5)'+ task migrate_master_images_to_product_media: :environment do+ batch_size = ENV.fetch('BATCH_SIZE', 500).to_i+ batch_size = 500 if batch_size < 1++ # Subquery (not pluck) so the product set doesn't materialize in Ruby —+ # important for catalogs with millions of products.+ variant_product_ids = Spree::Variant+ .joins("INNER JOIN #{Spree::Asset.table_name} ON " \+ "#{Spree::Asset.table_name}.viewable_id = #{Spree::Variant.table_name}.id " \+ "AND #{Spree::Asset.table_name}.viewable_type = 'Spree::Variant'")+ .select(:product_id)++ relation = Spree::Product.where(id: variant_product_ids)+ relation.find_each(batch_size: batch_size) do |product|+ Spree::Media::MigrateProductAssetsJob.perform_later(product.id)+ end++ puts "Enqueued migration jobs for #{relation.count} products on the #{Spree.queues.images} queue."+ endendenddiff --git a/spree/core/spec/jobs/spree/images/save_from_url_job_spec.rb b/spree/core/spec/jobs/spree/images/save_from_url_job_spec.rbindex 12567dde8d..75dae72c9f 100644--- a/spree/core/spec/jobs/spree/images/save_from_url_job_spec.rb+++ b/spree/core/spec/jobs/spree/images/save_from_url_job_spec.rb@@ -99,5 +99,39 @@ RSpec.describe Spree::Images::SaveFromUrlJob, type: :job doexpect { subject }.to raise_error(StandardError, /exceeds the maximum allowed size/)endend++ context 'when link_variant_id is provided for a product-level upload' do+ let(:product) { create(:product) }+ let!(:linked_variant) { create(:variant, product: product) }+ let(:viewable_id) { product.id }+ let(:viewable_type) { 'Spree::Product' }++ subject { described_class.new(viewable_id, viewable_type, external_url, external_id, position, linked_variant.id).perform_now }++ it 'creates a VariantMedia row linking the asset to the variant' do+ expect { subject }.to change(Spree::VariantMedia, :count).by(1)++ link = Spree::VariantMedia.last+ expect(link.variant_id).to eq(linked_variant.id)+ expect(link.media_id).to eq(Spree::Image.last.id)+ end++ it 'is idempotent on repeat invocations' do+ described_class.new(viewable_id, viewable_type, external_url, external_id, position, linked_variant.id).perform_now+ expect {+ described_class.new(viewable_id, viewable_type, external_url, external_id, position, linked_variant.id).perform_now+ }.not_to change(Spree::VariantMedia, :count)+ end+ end++ context 'when link_variant_id is provided but the upload targets a Variant (legacy)' do+ let!(:linked_variant) { create(:variant) }++ subject { described_class.new(variant.id, 'Spree::Variant', external_url, external_id, position, linked_variant.id).perform_now }++ it 'does not create a VariantMedia row (variant-pinned uploads bypass the join)' do+ expect { subject }.not_to change(Spree::VariantMedia, :count)+ end+ endendenddiff --git a/spree/core/spec/jobs/spree/media/migrate_product_assets_job_spec.rb b/spree/core/spec/jobs/spree/media/migrate_product_assets_job_spec.rbnew file mode 100644index 0000000000..c27721ba6d--- /dev/null+++ b/spree/core/spec/jobs/spree/media/migrate_product_assets_job_spec.rb@@ -0,0 +1,136 @@+require 'spec_helper'++RSpec.describe Spree::Media::MigrateProductAssetsJob, type: :job do+ subject { described_class.perform_now(product.id) }++ describe '#perform' do+ context 'with master-pinned assets' do+ let!(:product) { create(:product) }+ let!(:asset) { create(:image, viewable: product.master) }++ it 'moves master-pinned assets to the product' do+ expect { subject }+ .to change { asset.reload.viewable_type }.from('Spree::Variant').to('Spree::Product')++ expect(asset.reload.viewable_id).to eq(product.id)+ end++ it 'does not create VariantMedia rows for master-pinned assets' do+ expect { subject }.not_to change(Spree::VariantMedia, :count)+ end++ it 'updates media_count' do+ subject+ expect(product.reload.media_count).to eq(1)+ end++ it 'updates primary_media_id' do+ subject+ expect(product.reload.primary_media_id).to eq(asset.id)+ end+ end++ context 'with non-master variant-pinned assets' do+ let!(:product) { create(:product) }+ let!(:variant) { create(:variant, product: product) }+ let!(:asset) { create(:image, viewable: variant) }++ it 'moves the asset to the product and creates a VariantMedia row' do+ expect { subject }+ .to change { asset.reload.viewable_type }.from('Spree::Variant').to('Spree::Product')+ .and change(Spree::VariantMedia, :count).by(1)++ link = Spree::VariantMedia.find_by(variant_id: variant.id, media_id: asset.id)+ expect(link).to be_present+ end++ it 'links each variant-pinned asset to its original variant' do+ other_variant = create(:variant, product: product)+ other_asset = create(:image, viewable: other_variant)++ subject++ expect(Spree::VariantMedia.where(asset: asset).pluck(:variant_id)).to eq([variant.id])+ expect(Spree::VariantMedia.where(asset: other_asset).pluck(:variant_id)).to eq([other_variant.id])+ end++ it 'refreshes primary_media_id on the linked variant' do+ # update_all + upsert_all skip callbacks; the job must trigger+ # update_thumbnail! explicitly so the variants matrix shows distinct+ # thumbnails after migration.+ subject+ expect(variant.reload.primary_media_id).to eq(asset.id)+ end++ it 'does not duplicate assets even when historical line items exist' do+ create(:line_item, variant: variant)+ expect { subject }.not_to change(Spree::Asset, :count)+ end+ end++ context 'with mixed master + non-master assets' do+ let!(:product) { create(:product) }+ let!(:variant) { create(:variant, product: product) }+ let!(:master_asset) { create(:image, viewable: product.master) }+ let!(:variant_asset) { create(:image, viewable: variant) }++ it 'moves both, but only creates a join row for the non-master one' do+ expect { subject }+ .to change(Spree::VariantMedia, :count).by(1)++ expect(master_asset.reload.viewable).to eq(product)+ expect(variant_asset.reload.viewable).to eq(product)+ expect(Spree::VariantMedia.find_by(media_id: variant_asset.id, variant_id: variant.id)).to be_present+ expect(Spree::VariantMedia.where(media_id: master_asset.id)).to be_empty+ end+ end++ context 'idempotency' do+ let!(:product) { create(:product) }+ let!(:variant) { create(:variant, product: product) }+ let!(:asset) { create(:image, viewable: variant) }++ it 're-running the job is a no-op once everything is migrated' do+ described_class.perform_now(product.id)++ expect { described_class.perform_now(product.id) }.not_to change(Spree::VariantMedia, :count)+ expect(Spree::Asset.count).to eq(1)+ end+ end++ context 'when there is nothing to migrate' do+ let!(:product) { create(:product) }++ it 'is a no-op for asset counts' do+ expect { subject }.not_to change(Spree::Asset, :count)+ end++ it 'is a no-op for VariantMedia counts' do+ expect { subject }.not_to change(Spree::VariantMedia, :count)+ end++ it 'does not touch counter caches when nothing changed' do+ expect { subject }.not_to change { product.reload.updated_at }+ end+ end++ context 'when the product has been deleted' do+ let!(:product) { create(:product) }++ before { product.destroy }++ it 'returns without raising' do+ expect { described_class.perform_now(product.id) }.not_to raise_error+ end+ end++ context 'queueing' do+ let(:product) { create(:product) }++ it 'enqueues on the images queue' do+ expect { described_class.perform_later(product.id) }+ .to have_enqueued_job(described_class).on_queue(Spree.queues.images)+ end+ end+ end+enddiff --git a/spree/core/spec/lib/tasks/media_spec.rb b/spree/core/spec/lib/tasks/media_spec.rbnew file mode 100644index 0000000000..ece8275038--- /dev/null+++ b/spree/core/spec/lib/tasks/media_spec.rb@@ -0,0 +1,66 @@+require 'spec_helper'+require 'rake'++describe 'spree:media:migrate_master_images_to_product_media' do+ subject { Rake::Task[task_name] }++ let(:task_name) { 'spree:media:migrate_master_images_to_product_media' }++ # Load the rake file once for the whole describe block. Loading it inside `before`+ # would chain the task body with each example, so a single `invoke` would execute+ # the migration N times after N tests, creating duplicate rows.+ before(:all) do+ Rake::Task.define_task(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'media.rake')+ end++ before { subject.reenable }++ context 'with products that need migration' do+ let!(:product_with_master_image) { create(:product) }+ let!(:product_with_variant_image) { create(:product) }+ let!(:variant) { create(:variant, product: product_with_variant_image) }+ let!(:clean_product) { create(:product) }+ let!(:master_image) { create(:image, viewable: product_with_master_image.master) }+ let!(:variant_image) { create(:image, viewable: variant) }++ it 'enqueues a job for each product with variant-pinned assets' do+ expect { subject.invoke }.to have_enqueued_job(Spree::Media::MigrateProductAssetsJob)+ .with(product_with_master_image.id)+ .and have_enqueued_job(Spree::Media::MigrateProductAssetsJob)+ .with(product_with_variant_image.id)+ end++ it 'does not enqueue jobs for products without variant-pinned assets' do+ subject.invoke++ enqueued = ActiveJob::Base.queue_adapter.enqueued_jobs.map { |j| j[:args].first }+ expect(enqueued).not_to include(clean_product.id)+ end+ end++ context 'with no variant-pinned assets in the database' do+ let!(:product) { create(:product) }++ it 'enqueues nothing' do+ expect { subject.invoke }.not_to have_enqueued_job(Spree::Media::MigrateProductAssetsJob)+ end+ end++ context 'when run twice' do+ let!(:product) { create(:product) }+ let!(:variant) { create(:variant, product: product) }+ let!(:asset) { create(:image, viewable: variant) }++ it 'still enqueues for products that have not been processed yet' do+ # First invocation enqueues but doesn't run inline; the asset is still+ # variant-pinned, so the second invocation should enqueue again. The job+ # itself is what enforces idempotency once it runs.+ subject.invoke+ subject.reenable++ expect { subject.invoke }.to have_enqueued_job(Spree::Media::MigrateProductAssetsJob)+ .with(product.id)+ end+ end+enddiff --git a/spree/core/spec/models/spree/asset_media_spec.rb b/spree/core/spec/models/spree/asset_media_spec.rbdeleted file mode 100644index a7b8a25ad2..0000000000--- a/spree/core/spec/models/spree/asset_media_spec.rb+++ /dev/null@@ -1,161 +0,0 @@-require 'spec_helper'--RSpec.describe 'Product media system', type: :model do- describe 'Spree::Asset' do- describe '#focal_point' do- let(:asset) { build(:asset, focal_point_x: 0.5, focal_point_y: 0.3) }-- it 'returns hash with x and y' do- expect(asset.focal_point).to eq({ x: 0.5, y: 0.3 })- end-- it 'returns nil when coordinates are not set' do- asset.focal_point_x = nil- expect(asset.focal_point).to be_nil- end- end-- describe '#focal_point=' do- let(:asset) { build(:asset) }-- it 'sets x and y from hash' do- asset.focal_point = { x: 0.25, y: 0.75 }- expect(asset.focal_point_x).to eq(0.25)- expect(asset.focal_point_y).to eq(0.75)- end-- it 'clears focal point when set to nil' do- asset.focal_point = { x: 0.5, y: 0.5 }- asset.focal_point = nil- expect(asset.focal_point_x).to be_nil- expect(asset.focal_point_y).to be_nil- end- end-- describe '#product' do- it 'returns product when viewable is a Product' do- product = create(:product)- asset = create(:image, viewable: product)- expect(asset.product).to eq(product)- end- end-- describe 'media_type validation' do- it 'accepts valid media types' do- %w[image video external_video].each do |type|- asset = build(:asset, media_type: type)- asset.valid?- expect(asset.errors[:media_type]).to be_empty- end- end-- it 'rejects invalid media types' do- asset = build(:asset, media_type: 'audio')- expect(asset).not_to be_valid- expect(asset.errors[:media_type]).to be_present- end-- it 'defaults to image' do- asset = Spree::Asset.new- expect(asset.media_type).to eq('image')- end-- it 'defaults to image for Spree::Image subclass' do- image = Spree::Image.new- expect(image.media_type).to eq('image')- end- end-- describe 'counter caches with product viewable' do- let(:product) { create(:product) }-- it 'increments media_count on product when image is created' do- expect {- create(:image, viewable: product)- }.to change { product.reload.media_count }.by(1)- end-- it 'decrements media_count on product when image is destroyed' do- image = create(:image, viewable: product)- expect {- image.destroy- }.to change { product.reload.media_count }.by(-1)- end- end-- describe 'thumbnail updates with product viewable' do- let(:product) { create(:product) }-- it 'sets product primary_media_id when image is created' do- image = create(:image, viewable: product)- expect(product.reload.primary_media_id).to eq(image.id)- end-- it 'clears product primary_media_id when last image is destroyed' do- image = create(:image, viewable: product)- image.destroy- expect(product.reload.primary_media_id).to be_nil- end- end- end-- describe 'Spree::Product' do- let(:product) { create(:product) }-- describe '#media' do- it 'returns product-level assets' do- image = create(:image, viewable: product)- expect(product.media).to include(image)- end-- it 'does not include variant images' do- variant_image = create(:image, viewable: product.master)- expect(product.media).not_to include(variant_image)- end-- it 'is ordered by position' do- img2 = create(:image, viewable: product, position: 2)- img1 = create(:image, viewable: product, position: 1)- expect(product.media.to_a).to eq([img1, img2])- end- end-- describe '#gallery_media' do- it 'returns product media when present' do- product_image = create(:image, viewable: product)- create(:image, viewable: product.master) # variant image- expect(product.reload.gallery_media).to include(product_image)- end-- it 'falls back to variant_images when no product media' do- variant_image = create(:image, viewable: product.master)- expect(product.reload.gallery_media).to include(variant_image)- end- end-- describe '#update_thumbnail!' do- it 'uses product media first' do- product_image = create(:image, viewable: product)- expect(product.reload.primary_media_id).to eq(product_image.id)- end-- it 'falls back to variant images when no product media' do- variant_image = create(:image, viewable: product.master)- product.update_thumbnail!- expect(product.reload.primary_media_id).to eq(variant_image.id)- end- end- end-- describe 'Spree::Variant' do- let(:product) { create(:product) }- let(:variant) { create(:variant, product: product) }-- describe '#gallery_media' do- it 'returns direct images' do- direct_image = create(:image, viewable: variant)- expect(variant.gallery_media).to include(direct_image)- end- end- end-enddiff --git a/spree/core/spec/models/spree/asset_spec.rb b/spree/core/spec/models/spree/asset_spec.rbindex 928e09fcad..22cc1361fa 100644--- a/spree/core/spec/models/spree/asset_spec.rb+++ b/spree/core/spec/models/spree/asset_spec.rb@@ -24,11 +24,102 @@ describe Spree::Asset, type: :model doenddescribe '#product' do- it 'returns the product for the asset' do+ it 'returns the product when viewable is a Variant' dovariant = create(:variant)asset = create(:asset, viewable: variant)expect(asset.product).to eq(variant.product)end++ it 'returns the product when viewable is a Product' do+ product = create(:product)+ asset = create(:image, viewable: product)+ expect(asset.product).to eq(product)+ end+ end++ describe '#focal_point' do+ let(:asset) { build(:asset, focal_point_x: 0.5, focal_point_y: 0.3) }++ it 'returns hash with x and y' do+ expect(asset.focal_point).to eq({ x: 0.5, y: 0.3 })+ end++ it 'returns nil when coordinates are not set' do+ asset.focal_point_x = nil+ expect(asset.focal_point).to be_nil+ end+ end++ describe '#focal_point=' do+ let(:asset) { build(:asset) }++ it 'sets x and y from hash' do+ asset.focal_point = { x: 0.25, y: 0.75 }+ expect(asset.focal_point_x).to eq(0.25)+ expect(asset.focal_point_y).to eq(0.75)+ end++ it 'clears focal point when set to nil' do+ asset.focal_point = { x: 0.5, y: 0.5 }+ asset.focal_point = nil+ expect(asset.focal_point_x).to be_nil+ expect(asset.focal_point_y).to be_nil+ end+ end++ describe 'media_type' do+ it 'accepts valid media types' do+ %w[image video external_video].each do |type|+ asset = build(:asset, media_type: type)+ asset.valid?+ expect(asset.errors[:media_type]).to be_empty+ end+ end++ it 'rejects invalid media types' do+ asset = build(:asset, media_type: 'audio')+ expect(asset).not_to be_valid+ expect(asset.errors[:media_type]).to be_present+ end++ it 'defaults to image' do+ asset = Spree::Asset.new+ expect(asset.media_type).to eq('image')+ end++ it 'defaults to image for Spree::Image subclass' do+ image = Spree::Image.new+ expect(image.media_type).to eq('image')+ end+ end++ describe 'counter caches with product viewable' do+ let(:product) { create(:product) }++ it 'increments media_count on product when image is created' do+ expect { create(:image, viewable: product) }+ .to change { product.reload.media_count }.by(1)+ end++ it 'decrements media_count on product when image is destroyed' do+ image = create(:image, viewable: product)+ expect { image.destroy }.to change { product.reload.media_count }.by(-1)+ end+ end++ describe 'thumbnail updates with product viewable' do+ let(:product) { create(:product) }++ it 'sets product primary_media_id when image is created' do+ image = create(:image, viewable: product)+ expect(product.reload.primary_media_id).to eq(image.id)+ end++ it 'clears product primary_media_id when image is destroyed' do+ image = create(:image, viewable: product)+ image.destroy+ expect(product.reload.primary_media_id).to be_nil+ endenddescribe 'delegated methods' dodiff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rbindex 63ce3331b8..2fcec6bccc 100644--- a/spree/core/spec/models/spree/product_spec.rb+++ b/spree/core/spec/models/spree/product_spec.rb@@ -796,6 +796,56 @@ describe Spree::Product, type: :model doendend+ describe '#media' do+ let(:product) { create(:product, stores: [store]) }++ it 'returns product-level assets' do+ image = create(:image, viewable: product)+ expect(product.media).to include(image)+ end++ it 'does not include variant images' do+ variant_image = create(:image, viewable: product.master)+ expect(product.media).not_to include(variant_image)+ end++ it 'is ordered by position' do+ img2 = create(:image, viewable: product, position: 2)+ img1 = create(:image, viewable: product, position: 1)+ expect(product.media.to_a).to eq([img1, img2])+ end+ end++ describe '#gallery_media' do+ let(:product) { create(:product, stores: [store]) }++ it 'returns product media when present' do+ product_image = create(:image, viewable: product)+ create(:image, viewable: product.master)+ expect(product.reload.gallery_media).to include(product_image)+ end++ it 'falls back to variant_images when no product media' do+ variant_image = create(:image, viewable: product.master)+ expect(product.reload.gallery_media).to include(variant_image)+ end+ end++ describe '#update_thumbnail!' do+ let(:product) { create(:product, stores: [store]) }++ it 'uses product media first' do+ product_image = create(:image, viewable: product)+ expect(product.reload.primary_media_id).to eq(product_image.id)+ end++ it 'falls back to variant images when no product media' do+ variant_image = create(:image, viewable: product.master)+ product.update_thumbnail!+ expect(product.reload.primary_media_id).to eq(variant_image.id)+ end+ end+describe '#has_variant_images?' dolet(:product) { create(:product, stores: [store]) }diff --git a/spree/core/spec/models/spree/variant_media_spec.rb b/spree/core/spec/models/spree/variant_media_spec.rbnew file mode 100644index 0000000000..6350ca3899--- /dev/null+++ b/spree/core/spec/models/spree/variant_media_spec.rb@@ -0,0 +1,199 @@+require 'spec_helper'++RSpec.describe Spree::VariantMedia, type: :model do+ let(:product) { create(:product) }+ let(:variant) { create(:variant, product: product) }+ let(:asset) { create(:image, viewable: product) }++ describe 'validations' do+ it 'is valid when the asset belongs to the variant product' do+ vm = described_class.new(variant: variant, asset: asset)+ expect(vm).to be_valid+ end++ it 'rejects an asset attached to a different product' do+ other_asset = create(:image, viewable: create(:product))+ vm = described_class.new(variant: variant, asset: other_asset)+ expect(vm).not_to be_valid+ expect(vm.errors[:asset]).to be_present+ end++ it 'enforces uniqueness on (variant_id, media_id)' do+ described_class.create!(variant: variant, asset: asset)+ dup = described_class.new(variant: variant, asset: asset)+ expect(dup).not_to be_valid+ end+ end++ describe 'touch propagation' do+ it 'touches the variant on save' do+ link = described_class.create!(variant: variant, asset: asset)+ # MySQL stores DATETIME at second precision, so touching within the same+ # second as create wouldn't move updated_at. Advance the clock first.+ Timecop.travel(Time.current + 1.second) do+ expect { link.touch }.to change { variant.reload.updated_at }+ end+ end+ end++ describe 'thumbnail propagation' do+ let(:product_for_thumb) { create(:product) }+ let(:variant_for_thumb) { create(:variant, product: product_for_thumb) }+ let(:product_asset) { create(:image, viewable: product_for_thumb) }++ it 'sets the variant primary_media_id when the link is created' do+ expect {+ described_class.create!(variant: variant_for_thumb, asset: product_asset)+ }.to change { variant_for_thumb.reload.primary_media_id }.from(nil).to(product_asset.id)+ end++ it 'clears the variant primary_media_id when the only link is destroyed' do+ link = described_class.create!(variant: variant_for_thumb, asset: product_asset)+ expect { link.destroy }+ .to change { variant_for_thumb.reload.primary_media_id }.from(product_asset.id).to(nil)+ end+ end++ describe 'cleanup' do+ it 'destroys variant_media when the variant is destroyed' do+ described_class.create!(variant: variant, asset: asset)+ expect { variant.destroy }.to change(described_class, :count).by(-1)+ end++ it 'destroys variant_media when the asset is destroyed' do+ described_class.create!(variant: variant, asset: asset)+ expect { asset.destroy }.to change(described_class, :count).by(-1)+ end+ end++end++RSpec.describe Spree::Asset, type: :model do+ describe '#variant_ids=' do+ let(:product) { create(:product) }+ let(:product_asset) { create(:image, viewable: product) }+ let!(:variant_a) { create(:variant, product: product) }+ let!(:variant_b) { create(:variant, product: product) }++ it 'creates links for newly-picked variants' do+ expect {+ product_asset.variant_ids = [variant_a.to_param]+ }.to change(Spree::VariantMedia, :count).by(1)++ expect(product_asset.variant_media.pluck(:variant_id)).to contain_exactly(variant_a.id)+ end++ it 'destroys links for unpicked variants' do+ Spree::VariantMedia.create!(asset: product_asset, variant: variant_a)+ Spree::VariantMedia.create!(asset: product_asset, variant: variant_b)++ expect {+ product_asset.variant_ids = [variant_a.to_param]+ }.to change(Spree::VariantMedia, :count).by(-1)++ expect(product_asset.variant_media.pluck(:variant_id)).to contain_exactly(variant_a.id)+ end++ it 'clears all links when given an empty array' do+ Spree::VariantMedia.create!(asset: product_asset, variant: variant_a)++ expect {+ product_asset.variant_ids = []+ }.to change(Spree::VariantMedia, :count).by(-1)+ end++ it 'rejects variant ids belonging to a different product' do+ other_product = create(:product)+ foreign_variant = create(:variant, product: other_product)++ expect {+ product_asset.variant_ids = [foreign_variant.to_param]+ }.not_to change(Spree::VariantMedia, :count)+ end++ it 'accepts raw integer ids alongside prefixed ones' do+ expect {+ product_asset.variant_ids = [variant_a.id, variant_b.to_param]+ }.to change(Spree::VariantMedia, :count).by(2)+ end++ it 'is a no-op for variant-pinned assets (legacy viewable_type)' do+ legacy_asset = create(:image, viewable: variant_a)++ expect {+ legacy_asset.variant_ids = [variant_b.to_param]+ }.not_to change(Spree::VariantMedia, :count)+ end++ it 'works through ActiveRecord update with mass-assignment' do+ product_asset.update(variant_ids: [variant_a.to_param])+ expect(product_asset.variant_media.pluck(:variant_id)).to contain_exactly(variant_a.id)+ end+ end++end++RSpec.describe Spree::Variant, type: :model do+ describe 'media gallery' do+ let(:product) { create(:product) }+ let(:variant) { create(:variant, product: product) }++ context 'with associated media linked from the product' do+ let!(:product_asset) { create(:image, viewable: product) }+ let!(:link) { Spree::VariantMedia.create!(variant: variant, asset: product_asset) }++ it 'returns associated_media from gallery_media' do+ expect(variant.gallery_media.to_a).to eq([product_asset])+ end++ it 'reports has_associated_media?' do+ expect(variant.reload.has_associated_media?).to be(true)+ end++ it 'reports has_media?' do+ expect(variant.reload.has_media?).to be(true)+ end+ end++ context 'with multiple linked assets' do+ let!(:second_asset) { create(:image, viewable: product) }+ let!(:first_asset) { create(:image, viewable: product) }++ before do+ # Reverse position order: first_asset is created second but pinned to the+ # top of the gallery via product-level position. Variant gallery should+ # follow the same product-level ordering.+ first_asset.update_columns(position: 1)+ second_asset.update_columns(position: 2)+ Spree::VariantMedia.create!(variant: variant, asset: second_asset)+ Spree::VariantMedia.create!(variant: variant, asset: first_asset)+ end++ it 'inherits gallery order from the product-level asset position' do+ expect(variant.associated_media.to_a).to eq([first_asset, second_asset])+ end+ end++ context 'with only direct images (legacy path)' do+ let!(:direct_image) { create(:image, viewable: variant) }++ it 'returns direct images from gallery_media' do+ expect(variant.gallery_media.to_a).to eq([direct_image])+ end++ it 'reports has_media? via images count' do+ expect(variant.reload.has_media?).to be(true)+ end+ end++ context 'without any media' do+ it 'returns an empty gallery' do+ expect(variant.gallery_media.to_a).to be_empty+ end++ it 'reports no media' do+ expect(variant.has_media?).to be(false)+ end+ end+ end+enddiff --git a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rbindex b44c64b81a..14ce90f7a8 100644--- a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb+++ b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb@@ -292,7 +292,7 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service doendend- context 'with images' do+ context 'with images on a master variant row (no options)' dolet!(:product) docreate(:product, slug: 'denim-shirt', name: 'Denim Shirt', stores: [store])end@@ -306,11 +306,42 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do)end- it 'saves the images' do- expect { subject.process! }.to have_enqueued_job(Spree::Images::SaveFromUrlJob).exactly(3).times.on_queue(Spree.queues.images)- .and have_enqueued_job(Spree::Images::SaveFromUrlJob).with(variant.id, 'Spree::Variant', row_data['image1_src'])- .and have_enqueued_job(Spree::Images::SaveFromUrlJob).with(variant.id, 'Spree::Variant', row_data['image2_src'])- .and have_enqueued_job(Spree::Images::SaveFromUrlJob).with(variant.id, 'Spree::Variant', row_data['image3_src'])+ it 'enqueues SaveFromUrlJob attached to the product (no variant link)' do+ expect { subject.process! }+ .to have_enqueued_job(Spree::Images::SaveFromUrlJob).exactly(3).times.on_queue(Spree.queues.images)+ .and have_enqueued_job(Spree::Images::SaveFromUrlJob).with(product.id, 'Spree::Product', row_data['image1_src'], nil, nil, nil)+ .and have_enqueued_job(Spree::Images::SaveFromUrlJob).with(product.id, 'Spree::Product', row_data['image2_src'], nil, nil, nil)+ .and have_enqueued_job(Spree::Images::SaveFromUrlJob).with(product.id, 'Spree::Product', row_data['image3_src'], nil, nil, nil)+ end+ end++ context 'with images on a non-master variant row' do+ let!(:product) do+ create(:product, slug: 'denim-shirt', name: 'Denim Shirt', stores: [store])+ end+ let!(:option_type) { create(:option_type, name: 'color', presentation: 'Color') }+ let!(:option_value) { create(:option_value, name: 'blue', presentation: 'Blue', option_type: option_type) }++ let(:row_data) do+ csv_row_hash(+ 'slug' => 'denim-shirt',+ 'sku' => 'DENIM-SHIRT-BLUE',+ 'price' => '62.99',+ 'option1_name' => 'Color',+ 'option1_value' => 'Blue',+ 'image1_src' => 'https://example.com/blue1.jpg'+ )+ end++ it 'enqueues SaveFromUrlJob attached to the product, linking the variant' do+ result = nil+ expect { result = subject.process! }+ .to have_enqueued_job(Spree::Images::SaveFromUrlJob).exactly(1).times++ created_variant = result+ expect(created_variant).not_to be_is_master+ expect(Spree::Images::SaveFromUrlJob).to have_been_enqueued+ .with(product.id, 'Spree::Product', row_data['image1_src'], nil, nil, created_variant.id)endend