Class: Spree::Media::MigrateProductAssetsJob

Inherits:
BaseJob
  • Object
show all
Defined in:
app/jobs/spree/media/migrate_product_assets_job.rb

Overview

Per-product worker for the 5.4 → 5.5 media migration. Idempotent.

Instance Method Summary collapse

Instance Method Details

#perform(product_id) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'app/jobs/spree/media/migrate_product_assets_job.rb', line 7

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