Class: Crm::ImageProfileManagerController

Inherits:
CrmController show all
Defined in:
app/controllers/crm/image_profile_manager_controller.rb

Overview

Controller for bulk image profile management across catalog items
Provides a visual drag-and-drop interface for assigning images to retailer-specific slots

Constant Summary

Constants included from Controllers::ReferenceFindable

Controllers::ReferenceFindable::ID_EMBEDDED_PATTERNS

Constants included from Controllers::AnalyticsEvents

Controllers::AnalyticsEvents::MAX_QUEUED_EVENTS, Controllers::AnalyticsEvents::SESSION_KEY

Constants included from Controllers::ErrorRendering

Controllers::ErrorRendering::NON_CONTENT_PATH_PREFIXES

Instance Method Summary collapse

Methods inherited from CrmController

#access_denied, #context_id, #context_object, #crm_home_path, #current_ability, #default_url_options, #download_temp, #get_tempfile_path_for_download, #init_status_job_collector, #initialize_crm_lazy_chunks, #persist_enqueued_status_jobs, #record_not_found, #redirect_to_job_or_fallback, #render_edit_action, #set_context, #set_download_path, #stash_file_for_temp_download, #sync_admin_presence_cookie, #touch_employee_last_seen

Methods inherited from ApplicationController

#account_impersonated?, #add_to_flash, #after_sign_in_path_for, #bypass_forgery_protection?, #chat_enabled?, #cloudflare_cleared?, #default_catalog, #default_url_options, #enable_turbo_frames, #find_publication, #fix_invalid_accept_header, #init_js_utils, #is_globals_call?, #layout_by_resource, #locale_store, #redirect_to, #require_employee_for_crm, #set_base_host, #set_real_ip, #set_report_errors_for, #should_render_layout?, #skip_layout_for_turbo_frame?, #stamp_impersonation_context, #tab_frame_breakout_request?, #warmlyyours_canada_ip?, #warmlyyours_ip?, #y

Methods included from Controllers::ReturnPathHandling

#check_for_return_path, #redirect_to_return_path_or_default

Methods included from Controllers::AnalyticsEvents

#consume_queued_analytics_events, #registration_lead_type, #track_event

Methods included from Controllers::DeviceDetection

#device_detector, #is_ie?

Methods included from Controllers::SubdomainDetection

#is_crm_request?, #is_www_request?, #json_request?

Methods included from Controllers::TurboSafeRedirect

#redirect_to

Methods included from Controllers::TrackingDetection

#bot_request?, #gdpr_country?, #gdpr_country_data, #prevent_bots, #set_tracking_cookie, #track_visitor?

Methods included from Controllers::AcceleratedFileSending

#send_file_accelerated, #send_upload_accelerated

Methods included from Controllers::ErrorRendering

#excp_string, #mail_to_for_error_reporting, #render_400, #render_404, #render_406, #render_410, #render_500, #render_invalid_authenticity_token, #render_ip_spoof_error, #render_unpermitted_parameters, #safe_referer_or_fallback

Methods included from Controllers::TurnstileVerification

#load_turnstile_script_tag, #turnstile_lazy_widget, #turnstile_script_tag, #turnstile_widget, #validate_turnstile!

Methods included from Controllers::CloudflareCaching

edge_cached, #edge_cached_action?, #reset_cloudflare_cache, #set_cloudflare_cache, #skip_edge_cache!, #skip_session

Methods included from Controllers::Webpackable

#preload_webpack_fonts, #webpack_css_include, #webpack_css_url, #webpack_js_include, #wpd_is_running?

Methods included from Controllers::Localizable

#cloudflare_country_locale, #determine_request_locale, #geocoder_locale, #guest_user_locale_check, #locale_optional_www_auth_path?, #param_locale, #set_locale, #set_request_locale, #skip_localization?, #warmlyyours_ip_locale

Methods included from Controllers::Authenticable

#access_denied, #authenticate_account, #authenticate_account!, #authenticate_account_from_login_token!, #check_is_a_manager, #check_is_a_sales_manager, #check_is_an_admin, #check_is_an_employee, #check_party, #clear_mismatched_guest_user, #create_guest_user, #credentials?, #current_or_guest_user, #current_or_guest_user_id_read_only, #current_user, #devise_mapping, #fully_logged_in?, #generate_bot_id, #guest_user, #identifiable?, #init_current_user, #initialize_guest, #load_context_user, #logging_in, #resource, #resource_name, #restrict_access_for_non_employees, #scrubbed_request_path, #user_object, #warn_on_session_guest_id_leak

Methods included from UrlsHelper

#catalog_breadcrumb_links, #catalog_link, #catalog_link_for_product_line, #catalog_link_for_sku, #cms_link, #delocalized_path, #path_to_sales_product_sku, #path_to_sales_product_sku_for_product_line, #path_to_sales_product_sku_for_product_line_slug, #product_line_from_catalog_link, #protocol_neutral_url, #sanitize_external_url, #valid_external_url?

Instance Method Details

#assign_profileObject

POST /crm/image_profile_manager/:id/assign_profile
Assigns an image to a specific profile slot



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 101

def assign_profile
  image = Image.find(params.expect(:image_id))
  image_type = params[:image_type]
  locale = params[:content_locale].presence || 'en'

  # Check if this image is already assigned to another slot in same CATEGORY - if so, move it
  # Categories: AMZ_*, WAL_*, WYS_I*, WYS_CARD, WYS_MAIN, WYS_LIFESTYLE (matching model validation logic)
  existing_in_category = @item.image_profiles
                              .where(locale: locale, image_id: image.id)
                              .where(*image_type_category_conditions(image_type))
                              .where.not(image_type: image_type)
                              .first

  if existing_in_category
    # Image exists in another slot in same category - move it by updating image_type
    source_type = existing_in_category.image_type
    existing_in_category.skip_uniqueness_validation = true
    existing_in_category.update!(image_type: image_type)
    render_success("Image moved from #{source_type} to #{image_type}")
  else
    # Simple assign - find or create profile for this slot
    profile = @item.image_profiles.find_or_initialize_by(image_type: image_type, locale: locale)
    profile.image = image
    if profile.save
      render_success("Image assigned to #{image_type}")
    else
      render_error(profile.errors.full_messages.join(', '))
    end
  end
rescue ActiveRecord::RecordInvalid => e
  render_error(e.message)
end

#available_imagesObject

GET /crm/image_profile_manager/:id/available_images
Returns available images for the item (for lazy loading or search)



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 194

def available_images
  @locale = params[:content_locale].presence || 'en'
  @marketplace = params[:marketplace].presence || 'AMZ'
  @tag_filter = params[:tag].presence
  @keyword_search = params[:keyword_search].presence

  # Build image query using the same pattern as images_controller
  # Always exclude hidden tags (installation-plan, pdf-thumbnail, etc.)
  @available_images = if @keyword_search.present?
                        search_available_images(@keyword_search)
                      else
                        retrieve_available_images(tag_filter: @tag_filter)
                      end

  # Get IDs of images already assigned
  @assigned_image_ids = @item.image_profiles
                             .where(locale: @locale)
                             .where(ImageProfile[:image_type].matches("#{@marketplace}_%", nil, true))
                             .pluck(:image_id)
                             .to_set

  respond_to do |format|
    format.html do
      render partial: 'available_images_section', locals: {
        item: @item,
        available_images: @available_images,
        assigned_image_ids: @assigned_image_ids,
        marketplace: @marketplace
      }
    end
    format.turbo_stream do
      render turbo_stream: [
        turbo_stream.update('available-images', partial: 'available_images_section', locals: {
          item: @item,
          available_images: @available_images,
          assigned_image_ids: @assigned_image_ids,
          marketplace: @marketplace
        }),
        turbo_stream.update('image-count', @available_images.count.to_s)
      ]
    end
  end
end

#bulk_assign_profilesObject

POST /crm/image_profile_manager/:id/bulk_assign_profiles
One slot per retailer. params[:slot] is a hash like { "AMZ" => "AMZ_MAIN", "WAL" => "", "WYS" => "WYS_I01" }.
Empty value means remove any existing assignment for that retailer.



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 362

def bulk_assign_profiles
  image  = Image.find(params.expect(:image_id))
  locale = params[:content_locale].presence || 'en'
  slot_params = (params[:slot] || {}).to_unsafe_h

  desired = desired_bulk_slot_assignments(slot_params)

  current_by_bucket = @item.image_profiles
                           .where(image_id: image.id, locale: locale)
                           .index_by { |p| bulk_assignment_bucket_for_image_type(p.image_type) }

  to_add    = []
  to_remove = []

  desired.each do |bucket, new_type|
    current_profile = current_by_bucket[bucket]
    current_type    = current_profile&.image_type

    if new_type.blank?
      to_remove << current_profile if current_profile
    elsif new_type != current_type
      to_remove << current_profile if current_profile
      to_add    << new_type
    end
  end

  errors = []

  ImageProfile.transaction do
    to_remove.compact.each(&:destroy!)

    to_add.each do |type|
      profile = @item.image_profiles.find_or_initialize_by(image_type: type, locale: locale)
      profile.image = image
      errors.concat(profile.errors.full_messages) unless profile.save
    end

    raise ActiveRecord::Rollback if errors.any?
  end

  if errors.any?
    respond_to do |format|
      format.turbo_stream do
        render turbo_stream: turbo_stream.update('image-profile-dialog-content',
                                                 partial: 'slot_assignment_result',
                                                 locals: { success: false, message: errors.first })
      end
      format.html { redirect_to item_path(@item, tab: 'images'), alert: errors.first }
    end
  else
    added   = to_add.size
    removed = to_remove.compact.size
    parts   = []
    parts << "#{added} slot#{'s' if added != 1} assigned"    if added   > 0
    parts << "#{removed} slot#{'s' if removed != 1} removed" if removed > 0
    parts << 'No changes' if parts.empty?
    message = parts.join(', ')

    respond_to do |format|
      format.turbo_stream do
        render turbo_stream: turbo_stream.update('image-profile-dialog-content',
                                                 partial: 'slot_assignment_result',
                                                 locals: { success: true, message: message })
      end
      format.html { redirect_to item_path(@item, tab: 'images'), notice: message }
    end
  end
rescue ActiveRecord::RecordInvalid => e
  respond_to do |format|
    format.turbo_stream do
      render turbo_stream: turbo_stream.update('image-profile-dialog-content',
                                               partial: 'slot_assignment_result',
                                               locals: { success: false, message: e.message })
    end
    format.html { redirect_to item_path(@item, tab: 'images'), alert: e.message }
  end
end

#bulk_sync_profilesObject

POST /crm/image_profile_manager/bulk_sync_profiles
Queues a background job to copy ALL profiles from the reference item to
ALL other items in the variation. Redirects to the job status page.



480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 480

def bulk_sync_profiles
  reference_item = Item.find(params.expect(:reference_item_id))
  marketplace = params[:marketplace].presence || 'AMZ'
  return_to = params[:return_to].presence || image_profile_manager_path(reference_item, marketplace: marketplace)

  job_options = {
    'reference_item_id' => reference_item.id,
    'marketplace'       => marketplace,
    'content_locale'    => params[:content_locale].presence || 'en',
    'return_to'         => return_to
  }

  job_id = ImageProfileBulkSyncWorker.perform_async(job_options)

  if job_id.present?
    redirect_to job_path(job_id)
  else
    flash[:error] = 'Could not queue the sync job. Please try again.'
    redirect_to return_to
  end
end

#compact_profilesObject

POST /crm/image_profile_manager/:id/compact_profiles
Shifts images to fill gaps in the slot sequence for a given marketplace prefix.
Uses a single SQL UPDATE to avoid unique constraint violations during the shift.



831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 831

def compact_profiles
  prefix = params[:marketplace].to_s.upcase
  locale = params[:content_locale].presence || 'en'

  unless %w[AMZ WAL WYS].include?(prefix)
    flash[:alert] = "Invalid marketplace: #{prefix}"
    redirect_back_or_to catalog_item_path(params[:catalog_item_id], tab: "images")
    return
  end

  ordered_types = ImageProfile.ordered_image_types_for_group(prefix)
  shiftable_types = ordered_types.reject { |t| t.end_with?('_SWCH') }

  conn = ActiveRecord::Base.lease_connection
  current_types = @item.image_profiles
                       .where(locale: locale)
                       .where(ImageProfile[:image_type].matches("#{prefix}_%", nil, true))
                       .where.not(ImageProfile[:image_type].matches('%_SWCH', nil, true))
                       .order(Arel.sql(
                         shiftable_types.each_with_index.map { |type_name, i| "CASE WHEN image_type = #{conn.quote(type_name)} THEN #{i} END" }.join(', ')
                       ))
                       .pluck(:image_type)

  target_types = shiftable_types.first(current_types.size)
  needs_shift = current_types != target_types

  if needs_shift
    ActiveRecord::Base.transaction do
      type_mapping = current_types.zip(target_types).reject { |from, to| from == to }

      whens = type_mapping.map { |from, to| "WHEN #{conn.quote(from)} THEN #{conn.quote(to)}" }.join(' ')
      from_types = type_mapping.map { |from, _| conn.quote(from) }.join(', ')

      sql = ActiveRecord::Base.sanitize_sql_array([
                                                    "UPDATE image_profiles SET image_type = CASE image_type #{whens} END, updated_at = NOW() " \
                                                    "WHERE item_id = ? AND locale = ? AND image_type IN (#{from_types})",
                                                    @item.id, locale
                                                  ])
      conn.exec_update(sql)
    end

    flash[:notice] = "Compacted #{prefix} images — shifted #{current_types.size} profiles to fill gaps"
  else
    flash[:notice] = "#{prefix} images are already compact — no gaps found"
  end

  if params[:catalog_item_id].present?
    redirect_to catalog_item_path(params[:catalog_item_id], tab: "images", content_locale: locale)
  elsif params[:catalog_id].blank?
    redirect_to item_path(@item, tab: "images")
  else
    redirect_to image_profile_manager_path(@item, catalog_id: params[:catalog_id], marketplace: prefix)
  end
end

#copy_to_marketplaceObject

GET /crm/image_profile_manager/:id/copy_to_marketplace
Shows mapping interface to copy profiles from one marketplace to another



504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 504

def copy_to_marketplace
  @source_marketplace = params[:source_marketplace].presence || 'AMZ'
  @target_marketplace = params[:target_marketplace].presence || (@source_marketplace == 'AMZ' ? 'WAL' : 'AMZ')
  @locale = params[:content_locale].presence || 'en'
  @title = "Copy #{@source_marketplace == 'AMZ' ? 'Amazon' : 'Walmart'} → #{@target_marketplace == 'AMZ' ? 'Amazon' : 'Walmart'}"

  # Get source profiles
  @source_profiles = @item.image_profiles
                          .where(locale: @locale)
                          .where(ImageProfile[:image_type].matches("#{@source_marketplace}_%", nil, true))
                          .includes(:image)
                          .index_by(&:image_type)

  @source_image_types = ordered_image_types_for_marketplace(@source_marketplace)
  @target_image_types = ordered_image_types_for_marketplace(@target_marketplace)

  # Get existing target profiles
  @target_profiles = @item.image_profiles
                          .where(locale: @locale)
                          .where(ImageProfile[:image_type].matches("#{@target_marketplace}_%", nil, true))
                          .includes(:image)
                          .index_by(&:image_type)

  # Default mapping: MAIN->MAIN, FRNT->AD01, SIDE->AD02, etc.
  @default_mapping = build_default_mapping(@source_marketplace, @target_marketplace)

  # Variation context — the per-marketplace family of items sharing this
  # item's Amazon parent listing(s) (VariantGroup amazon rows), including the
  # reference item itself. @variation is now just a participation flag for the
  # view's presence guard.
  @variation = @item.catalog_items.where.not(variant_group_id: nil).exists?
  @variation_items = @item.amazon_family_items.order(:sku)
end

#execute_copy_to_marketplaceObject

POST /crm/image_profile_manager/:id/execute_copy_to_marketplace
Executes the copy operation based on the provided mapping



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 540

def execute_copy_to_marketplace
  source_marketplace = params[:source_marketplace]
  target_marketplace = params[:target_marketplace]
  locale = params[:content_locale].presence || 'en'
  mapping = params[:mapping] || {}
  apply_to_variation = params[:apply_to_variation] == '1'
  import_mode = params[:import_mode] || 'override' # 'override' or 'missing'

  # Determine which items to update
  items_to_update = if apply_to_variation && @item.amazon_family_items.exists?
                      @item.amazon_family_items
                    else
                      [@item]
                    end

  success_count = 0
  profile_count = 0
  skipped_count = 0
  errors = []

  items_to_update.each do |item|
    # Get source profiles for this item
    source_profiles = item.image_profiles
                          .where(locale: locale)
                          .where(ImageProfile[:image_type].matches("#{source_marketplace}_%", nil, true))
                          .includes(:image)
                          .index_by(&:image_type)

    # Get existing target profiles if we need to skip them
    existing_target_types = if import_mode == 'missing'
                              item.image_profiles
                                  .where(locale: locale)
                                  .where(ImageProfile[:image_type].matches("#{target_marketplace}_%", nil, true))
                                  .pluck(:image_type)
                            else
                              []
                            end

    ActiveRecord::Base.transaction do
      mapping.each do |source_type, target_type|
        next if target_type.blank?
        next unless source_profiles[source_type]

        # Skip if mode is 'missing' and target already has an image
        if import_mode == 'missing' && existing_target_types.include?(target_type)
          skipped_count += 1
          next
        end

        source_image_id = source_profiles[source_type].image_id

        # Find or create target profile
        target_profile = item.image_profiles.find_or_initialize_by(
          image_type: target_type,
          locale: locale
        )
        target_profile.image_id = source_image_id
        target_profile.skip_uniqueness_validation = true
        target_profile.save!
        profile_count += 1
      end
      success_count += 1
    end
  rescue ActiveRecord::RecordInvalid => e
    errors << "#{item.sku}: #{e.message}"
  rescue StandardError => e
    errors << "#{item.sku}: #{e.message}"
  end

  message = "Copied #{profile_count} profiles to #{success_count} items"
  message += " (#{skipped_count} skipped - already assigned)" if skipped_count > 0
  message += ". Errors: #{errors.first(3).join('; ')}" if errors.any?

  flash[:notice] = message
  redirect_to image_profile_manager_path(@item,
    catalog_id: params[:catalog_id],
    marketplace: target_marketplace,
    state: params[:state])
end

#image_dialogObject

GET /crm/image_profile_manager/:id/image_dialog
Returns dialog content for viewing and managing a specific image profile
Uses native element instead of Bootstrap modal



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 443

def image_dialog
  @image_type = params[:image_type]
  @locale = params[:content_locale].presence || 'en'
  @marketplace = @image_type.to_s.split('_').first
  @catalog_id = params[:catalog_id]

  @profile = @item.image_profiles.find_by(image_type: @image_type, locale: @locale)
  @image = @profile&.image

  # Get all image types for the marketplace (for reassign dropdown)
  @image_types = ordered_image_types_for_marketplace(@marketplace)

  # Build gallery items for Fancybox
  all_profiles = @item.image_profiles
                      .where(locale: @locale)
                      .where(ImageProfile[:image_type].matches("#{@marketplace}_%", nil, true))
                      .includes(:image)
                      .order(:image_type)

  @gallery_images = all_profiles.filter_map do |p|
    next unless p.image

    {
      src: p.image.image_url(width: 1600, height: 1600),
      thumb: p.image.image_url(width: 200, height: 200, thumbnail: true),
      caption: "#{p.image_type} - Image ##{p.image_id}"
    }
  end

  @gallery_start_index = all_profiles.to_a.index(@profile) || 0

  render layout: false
end

#image_modalObject

GET /crm/image_profile_manager/:id/image_modal
Returns modal content for viewing and managing a specific image profile
Loaded via Turbo Frame into the modal slot



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 241

def image_modal
  @image_type = params[:image_type]
  @locale = params[:content_locale].presence || 'en'
  @marketplace = @image_type.to_s.split('_').first
  @catalog_id = params[:catalog_id]

  @profile = @item.image_profiles.find_by(image_type: @image_type, locale: @locale)
  @image = @profile&.image

  # Get all image types for the marketplace (for reassign dropdown)
  @image_types = ordered_image_types_for_marketplace(@marketplace)

  # Build gallery items for Fancybox
  all_profiles = @item.image_profiles
                      .where(locale: @locale)
                      .where(ImageProfile[:image_type].matches("#{@marketplace}_%", nil, true))
                      .includes(:image)
                      .order(:image_type)

  @gallery_images = all_profiles.filter_map do |p|
    next unless p.image

    {
      src: p.image.image_url(width: 1600, height: 1600),
      thumb: p.image.image_url(width: 200, height: 200, thumbnail: true),
      caption: "#{p.image_type} - Image ##{p.image_id}"
    }
  end

  @gallery_start_index = all_profiles.to_a.index(@profile) || 0

  render layout: false
end

#import_and_assignObject

POST /crm/image_profile_manager/:id/import_and_assign
Imports a live Amazon image and assigns it to a specific profile slot (via drag-drop)
Allows mapping any Amazon image to any profile slot



623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 623

def import_and_assign
  live_amazon_url = params[:live_amazon_url]
  amazon_variant = params[:amazon_variant]
  target_image_type = params[:target_image_type]
  locale = params[:content_locale].presence || 'en'
  params[:marketplace].presence || 'AMZ'

  return render_error('Missing required parameters') unless live_amazon_url.present? && target_image_type.present?

  # Import the image and assign to the target slot
  result = import_single_slot(amazon_variant, live_amazon_url, target_image_type, locale)

  if result[:success]
    render_success("Imported Amazon #{amazon_variant} → #{target_image_type}")
  else
    render_error("Import failed: #{result[:error]}")
  end
end

#import_single_amazon_imageObject

POST /crm/image_profile_manager/:id/import_single_amazon_image
Imports a single Amazon image slot from live Amazon data



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 644

def import_single_amazon_image
  amazon_variant = params[:amazon_variant] # e.g., 'MAIN', 'PT01', etc.
  locale = params[:content_locale].presence || 'en'

  # Find the specific catalog item if provided, otherwise use first active Amazon catalog item
  catalog_item = if params[:catalog_item_id].present?
                   @item.catalog_items.find_by(id: params[:catalog_item_id])
                 else
                   @item.catalog_items.amazons.active.first
                 end

  unless catalog_item
    flash[:alert] = 'No active Amazon catalog item found for this item'
    redirect_back_or_to image_profile_manager_path(@item, marketplace: 'AMZ')
    return
  end

  # Get live Amazon images
  live_images = catalog_item.amazon_current_images
  amazon_url = live_images[amazon_variant]

  if amazon_url.blank?
    flash[:alert] = "No live Amazon image found for slot #{amazon_variant}"
    redirect_back_or_to image_profile_manager_path(@item, marketplace: 'AMZ')
    return
  end

  # Check if we already have a profile for this slot
  profile_type = Catalog::AmazonImageBackfillService::AMAZON_TO_PROFILE_MAPPING[amazon_variant]

  unless profile_type
    flash[:alert] = "Unknown Amazon image variant: #{amazon_variant}"
    redirect_back_or_to image_profile_manager_path(@item, marketplace: 'AMZ')
    return
  end

  if @item.image_profiles.exists?(image_type: profile_type, locale: locale)
    flash[:alert] = "Slot #{profile_type} already has an image assigned"
    redirect_back_or_to image_profile_manager_path(@item, marketplace: 'AMZ')
    return
  end

  # Use the backfill service to import just this one slot
  result = import_single_slot(amazon_variant, amazon_url, profile_type, locale)

  if result[:success]
    flash[:notice] = "Successfully imported #{amazon_variant} → #{profile_type}"
  else
    flash[:alert] = "Import failed: #{result[:error]}"
  end

  redirect_back_or_to image_profile_manager_path(@item, marketplace: 'AMZ', catalog_id: params[:catalog_id])
end

#indexObject

GET /crm/image_profile_manager
Shows list of catalog items in a catalog with their image slot previews



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
45
46
47
48
49
50
51
52
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 15

def index
  @title = 'Image Profile Manager'

  # Build query for catalog items
  @marketplace = params[:marketplace].presence || 'AMZ'
  @state = params[:state].presence || 'active'
  @image_coverage = params[:image_coverage].presence
  @image_count = params[:image_count].presence

  # Get catalog items for this catalog with specific state
  # Exclude publications (manuals, spec sheets, etc.) which don't need image profiles
  non_publication_category_ids = ProductCategory.all_non_publication_goods_ids
  scope = @catalog.catalog_items
                  .joins(:item)
                  .where(items: { product_category_id: non_publication_category_ids })
                  .includes(item: [:primary_image, { image_profiles: :image }])
  scope = scope.where(state: @state) if @state.present? && @state != 'all'

  # Apply image coverage filter if specified
  scope = apply_image_coverage_filter(scope, @marketplace, @image_coverage) if @image_coverage.present?

  # Apply exact image count filter if specified
  scope = apply_image_count_filter(scope, @marketplace, @image_count.to_i) if @image_count.present?

  @q = scope.ransack(params[:q])
  @q.sorts = ['item_sku asc'] if @q.sorts.empty?
  per_page = params[:per_page].presence&.to_i || 25
  @pagy, @catalog_items = pagy(@q.result.joins(:item), limit: per_page, params: lambda { |p|
    p.merge(catalog_id: @catalog.id, marketplace: @marketplace, state: @state, image_coverage: @image_coverage, image_count: @image_count, per_page: per_page)
  })

  # Get ordered image types for the selected marketplace
  @image_types = ordered_image_types_for_marketplace(@marketplace)

  # Statistics
  @total_items = @catalog_items.count
  @items_with_complete_profiles = count_items_with_complete_profiles(@catalog_items, @image_types)
end

#library_image_dialogObject

GET /crm/image_profile_manager/:id/library_image_dialog
Returns dialog content for viewing an image from the library (not a profile slot)
Used when clicking on images in the Image Library accordion



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 308

def library_image_dialog
  @image = Image.find(params.expect(:image_id))
  @locale = params[:content_locale].presence || 'en'
  @marketplace = params[:marketplace].presence || 'AMZ'

  # Check if this image is assigned to any profile for this item
  @assigned_profiles = @item.image_profiles
                            .where(image_id: @image.id, locale: @locale)
                            .where(ImageProfile[:image_type].matches("#{@marketplace}_%", nil, true))
                            .pluck(:image_type)

  # Get all image types for the marketplace (for assign dropdown)
  @image_types = ordered_image_types_for_marketplace(@marketplace)

  # Get current profiles to show which slots are available
  @current_profiles = @item.image_profiles
                           .where(locale: @locale)
                           .where(ImageProfile[:image_type].matches("#{@marketplace}_%", nil, true))
                           .pluck(:image_type)

  render layout: false
end

#live_amazon_image_dialogObject

GET /crm/image_profile_manager/:id/live_amazon_image_dialog
Returns dialog content for viewing a live Amazon image (not yet imported)



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 277

def live_amazon_image_dialog
  @amazon_variant = params[:amazon_variant]
  @live_url = params[:live_url]
  @catalog_item_id = params[:catalog_item_id]
  @locale = params[:content_locale].presence || 'en'
  @marketplace = 'AMZ'

  # Get the profile type for this Amazon variant
  @profile_type = Catalog::AmazonImageBackfillService::AMAZON_TO_PROFILE_MAPPING[@amazon_variant]

  # Check if we already have this profile assigned
  @has_local_profile = @profile_type && @item.image_profiles.exists?(image_type: @profile_type, locale: @locale)

  # Get catalog item info
  @catalog_item = CatalogItem.find_by(id: @catalog_item_id)

  # Get all image types for the marketplace (for assign dropdown)
  @image_types = ordered_image_types_for_marketplace(@marketplace)

  # Get current profiles to show which slots are available
  @current_profiles = @item.image_profiles
                           .where(locale: @locale)
                           .where(ImageProfile[:image_type].matches("#{@marketplace}_%", nil, true))
                           .pluck(:image_type)

  render layout: false
end

#quick_importObject

Quick import using default mapping



699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 699

def quick_import
  source_marketplace = params[:source_marketplace]
  target_marketplace = params[:target_marketplace]
  locale = params[:content_locale].presence || 'en'
  import_mode = params[:import_mode] || 'override'
  sequential = params[:sequential] == '1'

  # Build default mapping based on position
  source_types = ImageProfile::IMAGE_TYPES.keys
                                          .select { |t| t.to_s.start_with?("#{source_marketplace}_") }
                                          .map(&:to_s)
  target_types = ImageProfile::IMAGE_TYPES.keys
                                          .select { |t| t.to_s.start_with?("#{target_marketplace}_") }
                                          .map(&:to_s)

  # Create mapping based on mode
  mapping = {}
  if sequential
    # Sequential mode: fill target slots from the beginning with available source images
    mapping = build_sequential_mapping(source_marketplace, target_marketplace, source_types, target_types, locale)
  else
    # Position-based mapping (legacy behavior)
    source_position_map = build_position_map(source_marketplace, source_types)
    target_position_map = build_type_from_position_map(target_marketplace, target_types)

    source_position_map.each do |source_type, position|
      target_type = target_position_map[position]
      mapping[source_type] = target_type if target_type
    end
  end

  # Get source profiles
  source_profiles = @item.image_profiles
                         .where(locale: locale)
                         .where(ImageProfile[:image_type].matches("#{source_marketplace}_%", nil, true))
                         .includes(:image)
                         .index_by(&:image_type)

  # Get existing target profiles if we need to skip them
  existing_target_types = if import_mode == 'missing'
                            @item.image_profiles
                                 .where(locale: locale)
                                 .where(ImageProfile[:image_type].matches("#{target_marketplace}_%", nil, true))
                                 .pluck(:image_type)
                          else
                            []
                          end

  profile_count = 0
  skipped_count = 0
  moved_count = 0

  ActiveRecord::Base.transaction do
    # Collect all image IDs we're going to assign to track moves
    mapping.filter_map do |source_type, target_type|
      next unless source_profiles[source_type]

      [source_profiles[source_type].image_id, target_type]
    end.to_h

    mapping.each do |source_type, target_type|
      next if target_type.blank?
      next unless source_profiles[source_type]

      if import_mode == 'missing' && existing_target_types.include?(target_type)
        skipped_count += 1
        next
      end

      source_image_id = source_profiles[source_type].image_id

      # Check if this image already exists in a different slot for the target marketplace
      # If so, we need to remove it from the old slot first (move it)
      existing_profile_with_same_image = @item.image_profiles
                                              .where(locale: locale)
                                              .where(ImageProfile[:image_type].matches("#{target_marketplace}_%", nil, true))
                                              .where(image_id: source_image_id)
                                              .where.not(image_type: target_type)
                                              .first

      if existing_profile_with_same_image
        # Delete the old profile to free up this image for the new slot
        existing_profile_with_same_image.destroy!
        moved_count += 1
      end

      target_profile = @item.image_profiles.find_or_initialize_by(
        image_type: target_type,
        locale: locale
      )
      target_profile.image_id = source_image_id
      target_profile.skip_uniqueness_validation = true
      target_profile.save!
      profile_count += 1
    end
  end

  mode_label = import_mode == 'missing' ? 'Imported' : 'Copied'
  message = "#{mode_label} #{profile_count} profiles from #{marketplace_name(source_marketplace)}"
  message += " (#{moved_count} moved to new slots)" if moved_count > 0
  message += " (#{skipped_count} skipped - already assigned)" if skipped_count > 0

  destination = quick_import_destination_url(target_marketplace, locale)

  respond_to do |format|
    format.turbo_stream do
      flash[:notice] = message
      render turbo_stream: turbo_stream.redirect(destination)
    end
    format.html do
      flash[:notice] = message
      redirect_to destination
    end
  end
rescue ActiveRecord::RecordInvalid => e
  error_destination = quick_import_destination_url(target_marketplace, locale)

  respond_to do |format|
    format.turbo_stream do
      flash[:alert] = "Import failed: #{e.message}"
      render turbo_stream: turbo_stream.redirect(error_destination)
    end
    format.html do
      flash[:alert] = "Import failed: #{e.message}"
      redirect_back_or_to error_destination
    end
  end
end

#showObject

GET /crm/image_profile_manager/:id
Shows single item with drag-drop image assignment interface



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 56

def show
  @title = "Image Profiles: #{@item.sku}"
  @marketplace = params[:marketplace].presence || 'AMZ'
  # Use content_locale param to avoid collision with the route's I18n locale param
  # Image profiles store locale as 'en', not 'en-US'
  @locale = params[:content_locale].presence || 'en'

  # Get ordered image types for the selected marketplace
  @image_types = ordered_image_types_for_marketplace(@marketplace)

  # Get current image profiles for this item/locale/marketplace
  @current_profiles = @item.image_profiles
                           .where(locale: @locale)
                           .where(ImageProfile[:image_type].matches("#{@marketplace}_%", nil, true))
                           .includes(:image)
                           .index_by(&:image_type)

  # Get all available images for this item
  @available_images = retrieve_available_images

  # Get IDs of images already assigned to any slot
  @assigned_image_ids = @current_profiles.values.filter_map(&:image_id).to_set

  # Catalog item context if coming from catalog
  @catalog_item = CatalogItem.find_by(id: params[:catalog_item_id])
  @catalog = @catalog_item&.catalog || Catalog.find_by(id: params[:catalog_id])

  # Try to find catalog_item from catalog and item if not explicitly passed
  @catalog_item ||= @item.catalog_items.find_by(catalog_id: @catalog.id) if @catalog

  # Navigation: Get previous/next items if in catalog context
  return unless @catalog

  @sibling_items = @catalog.catalog_items
                           .where(state: params[:state].presence || 'active')
                           .joins(:item)
                           .order('items.sku ASC')
                           .pluck('items.id')
  current_index = @sibling_items.index(@item.id)
  @prev_item_id = @sibling_items[current_index - 1] if current_index && current_index > 0
  @next_item_id = @sibling_items[current_index + 1] if current_index && current_index < @sibling_items.length - 1
end

#slot_assignment_dialogObject

GET /crm/image_profile_manager/:id/slot_assignment_dialog
Dialog to assign a single image to one or more slots across all marketplaces at once.



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 333

def slot_assignment_dialog
  @image = Image.find(params.expect(:image_id))
  @locale = params[:content_locale].presence || 'en'

  # All currently assigned types for this image on this item
  @assigned_types = @item.image_profiles
                         .where(image_id: @image.id, locale: @locale)
                         .pluck(:image_type)
                         .to_set

  # All occupied slots (any image) so we can show which slots are taken by someone else
  @occupied_types = @item.image_profiles
                         .where(locale: @locale)
                         .where.not(image_id: @image.id)
                         .pluck(:image_type)
                         .to_set

  @marketplace_configs = [
    { code: 'WYS', name: 'Website',  color: 'success', icon: 'globe',  icon_type: 'solid' },
    { code: 'AMZ', name: 'Amazon',   color: 'warning', icon: 'amazon', icon_type: 'brands' },
    { code: 'WAL', name: 'Walmart',  color: 'primary', icon: 'store',  icon_type: 'solid' }
  ]

  render layout: false
end

#swap_profilesObject

POST /crm/image_profile_manager/:id/swap_profiles
Swaps images between two profile slots.
When replace_only=true, moves the source image to the target slot (source becomes empty,
any existing target image is discarded). When false (default), swaps both images.
Uses a three-step TEMPORARY placeholder to avoid uniqueness constraint violations.



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 154

def swap_profiles
  source_type = params[:source_image_type]
  target_type = params[:target_image_type]
  replace_only = params[:replace_only] == 'true'
  locale = params[:content_locale].presence || 'en'

  source_profile = @item.image_profiles.find_by(image_type: source_type, locale: locale)
  target_profile = @item.image_profiles.find_by(image_type: target_type, locale: locale)

  return render_error('Source slot is empty') unless source_profile

  ActiveRecord::Base.transaction do
    if replace_only
      # Move source to target, discarding whatever was in target
      target_profile&.destroy!
      source_profile.skip_uniqueness_validation = true
      source_profile.update!(image_type: target_type)
      render_success("Moved image from #{source_type} to #{target_type}")
    elsif target_profile
      # Both slots have images - swap using a per-record ID-based temp type to avoid
      # hitting the unique index on (item_id, image_type, locale). update_all bypasses
      # Rails validations so the temp value never races with a stale 'TEMPORARY' row.
      temp_type = "__SWAP_#{source_profile.id}__"
      ImageProfile.where(id: source_profile.id).update_all(image_type: temp_type)
      ImageProfile.where(id: target_profile.id).update_all(image_type: source_type)
      ImageProfile.where(id: source_profile.id).update_all(image_type: target_type)
      render_success("Swapped images between #{source_type} and #{target_type}")
    else
      # Target is empty - just move the source image to target
      source_profile.skip_uniqueness_validation = true
      source_profile.update!(image_type: target_type)
      render_success("Moved image from #{source_type} to #{target_type}")
    end
  end
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique => e
  render_error(e.message)
end

#unassign_profileObject

DELETE /crm/image_profile_manager/:id/unassign_profile
Removes an image from a profile slot



136
137
138
139
140
141
142
143
144
145
146
147
# File 'app/controllers/crm/image_profile_manager_controller.rb', line 136

def unassign_profile
  image_type = params[:image_type]
  locale = params[:content_locale].presence || 'en'

  profile = @item.image_profiles.find_by(image_type: image_type, locale: locale)

  if profile&.destroy
    render_success("Image removed from #{image_type}")
  else
    render_error('Profile not found or could not be deleted')
  end
end