Class: Image::ImageShiftingService

Inherits:
Object
  • Object
show all
Defined in:
app/services/image/image_shifting_service.rb

Overview

Service class for handling image shifting operations

Class Method Summary collapse

Class Method Details

.analyze_missing_sequences(locale: 'en', prefix: nil) ⇒ Hash

Analyzes missing sequences in image profiles

Parameters:

  • locale (String) (defaults to: 'en')

    The locale for the images (default: 'en')

  • prefix (String, nil) (defaults to: nil)

    Optional prefix to limit analysis to a specific group (e.g., 'AMZ', 'WAL')

Returns:

  • (Hash)

    Analysis results including items with gaps and gap details



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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'app/services/image/image_shifting_service.rb', line 104

def self.analyze_missing_sequences(locale: 'en', prefix: nil)
  results = {
    total_items: 0,
    items_with_gaps: 0,
    total_gaps: 0,
    items_with_complete_sequences: 0,
    gap_details: [],
    prefix_groups: {}
  }

  # Find all items that have image profiles
  items_with_profiles = Item.joins(:image_profiles)
                            .where(image_profiles: { locale: locale })
                            .distinct

  # Apply prefix filter if specified
  if prefix.present?
    prefix = prefix.upcase
    items_with_profiles = items_with_profiles.where('image_profiles.image_type LIKE ?', "#{prefix}%")
  end

  results[:total_items] = items_with_profiles.count

  # Group by prefix for analysis
  prefix_groups = {}

  if prefix.present?
    prefix_groups[prefix] = items_with_profiles
  else
    # Group by prefix
    %w[AMZ WAL].each do |group_prefix|
      group_items = items_with_profiles.where('image_profiles.image_type LIKE ?', "#{group_prefix}%")
      prefix_groups[group_prefix] = group_items if group_items.any?
    end
  end

  prefix_groups.each do |group_prefix, items|
    group_results = analyze_prefix_group(items, group_prefix, locale)
    results[:prefix_groups][group_prefix] = group_results
    results[:items_with_gaps] += group_results[:items_with_gaps]
    results[:total_gaps] += group_results[:total_gaps]
    results[:gap_details].concat(group_results[:gap_details])
  end

  results[:items_with_complete_sequences] = results[:total_items] - results[:items_with_gaps]
  results
end

.analyze_prefix_group(items, group_prefix, locale) ⇒ Object

Analyzes a specific prefix group for gaps



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'app/services/image/image_shifting_service.rb', line 218

def self.analyze_prefix_group(items, group_prefix, locale)
  results = {
    prefix: group_prefix,
    items_with_gaps: 0,
    total_gaps: 0,
    gap_details: []
  }

  # Get ordered types for this group
  ordered_types = ImageProfile.ordered_image_types_for_group(group_prefix)

  items.find_each do |item|
    current_profiles = get_item_image_profiles(item, locale, group_prefix)

    # Calculate gaps
    gaps = calculate_gaps(current_profiles, ordered_types)

    if gaps.any?
      results[:items_with_gaps] += 1
      results[:total_gaps] += gaps.count

      results[:gap_details] << {
        item: item,
        current_profiles: current_profiles,
        gaps: gaps,
        gap_count: gaps.count
      }
    end
  end

  results
end

.calculate_gaps(current_profiles, ordered_types) ⇒ Object

Calculates gaps in image sequence



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'app/services/image/image_shifting_service.rb', line 252

def self.calculate_gaps(current_profiles, ordered_types)
  gaps = []
  found_types = []

  ordered_types.each do |type|
    if current_profiles.include?(type)
      found_types << type
    elsif found_types.any?
      # This is a gap - a missing type that comes after at least one existing type
      # but only if there are more existing types after this position
      remaining_types = ordered_types[ordered_types.index(type)..-1]
      remaining_found = remaining_types & current_profiles

      gaps << type if remaining_found.any?
    end
  end

  gaps
end

.find_missing_image_type(image_type, locale: 'en', prefix: nil, limit: 50) ⇒ Hash

Finds items missing a specific image type

Parameters:

  • image_type (String)

    The image type to search for

  • locale (String) (defaults to: 'en')

    The locale for the images (default: 'en')

  • prefix (String, nil) (defaults to: nil)

    Optional prefix to limit search to a specific group (e.g., 'AMZ', 'WAL')

  • limit (Integer) (defaults to: 50)

    Maximum number of items to return (default: 50)

Returns:

  • (Hash)

    Results including missing items and their current images



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
191
192
193
194
195
# File 'app/services/image/image_shifting_service.rb', line 158

def self.find_missing_image_type(image_type, locale: 'en', prefix: nil, limit: 50)
  results = {
    image_type: image_type,
    total_missing: 0,
    missing_items: [],
    limit: limit
  }

  # Find items that have image profiles but are missing the specific type
  items_with_profiles = Item.joins(:image_profiles)
                            .where(image_profiles: { locale: locale })
                            .distinct

  # Apply prefix filter if specified
  if prefix.present?
    prefix = prefix.upcase
    items_with_profiles = items_with_profiles.where('image_profiles.image_type LIKE ?', "#{prefix}%")
  end

  # Find items missing the specific image type
  items_missing_type = items_with_profiles.where.not(
    id: ImageProfile.where(locale: locale, image_type: image_type).select(:item_id)
  )

  results[:total_missing] = items_missing_type.count

  # Get details for limited number of items
  items_missing_type.limit(limit).each do |item|
    current_images = get_item_image_profiles(item, locale, prefix)

    results[:missing_items] << {
      item: item,
      current_images: current_images
    }
  end

  results
end

.get_item_image_profiles(item, locale, prefix) ⇒ Object

Gets image profiles for an item in proper order



200
201
202
203
204
205
206
207
208
# File 'app/services/image/image_shifting_service.rb', line 200

def self.get_item_image_profiles(item, locale, prefix)
  profiles = item.image_profiles.where(locale: locale)
  profiles = profiles.where('image_type LIKE ?', "#{prefix}%") if prefix.present?
  profile_types = profiles.pluck(:image_type)

  # Sort by proper image type order
  ordered_types = prefix.present? ? ImageProfile.ordered_image_types_for_group(prefix) : ImageProfile::IMAGE_TYPES.keys.map(&:to_s)
  profile_types.sort_by { |type| ordered_types.index(type) || 999 }
end

.shift_images_for_all_items(locale: 'en', prefix: nil, batch_size: 100, dry_run: false) ⇒ Hash

Shifts images for all items that have image profiles

Parameters:

  • locale (String) (defaults to: 'en')

    The locale for the images (default: 'en')

  • prefix (String, nil) (defaults to: nil)

    Optional prefix to limit shifting to a specific group (e.g., 'AMZ', 'WAL')

  • batch_size (Integer) (defaults to: 100)

    Number of items to process in each batch (default: 100)

  • dry_run (Boolean) (defaults to: false)

    If true, only shows what would be done without making changes (default: false)

Returns:

  • (Hash)

    Summary of the operation including processed items and any errors



42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
98
# File 'app/services/image/image_shifting_service.rb', line 42

def self.shift_images_for_all_items(locale: 'en', prefix: nil, batch_size: 100, dry_run: false)
  results = {
    processed_items: 0,
    skipped_items: 0,
    errors: [],
    dry_run: dry_run,
    items_with_changes: 0,
    total_changes: 0
  }

  # Find all items that have image profiles
  items_with_profiles = Item.joins(:image_profiles)
                            .where(image_profiles: { locale: locale })
                            .distinct

  # Apply prefix filter if specified
  if prefix.present?
    prefix = prefix.upcase
    items_with_profiles = items_with_profiles.where('image_profiles.image_type LIKE ?', "#{prefix}%")
  end

  total_items = items_with_profiles.count
  results[:total_items] = total_items

  items_with_profiles.find_in_batches(batch_size: batch_size) do |batch|
    batch.each do |item|
      # Get before state
      before_profiles = get_item_image_profiles(item, locale, prefix)

      if dry_run
        # For dry run, just check if changes would be needed
        after_profiles = simulate_shift(before_profiles, prefix)
        changes_needed = before_profiles != after_profiles
        results[:items_with_changes] += 1 if changes_needed
      else
        # Perform the actual shift
        shift_result = shift_images_for_item(item.id, locale: locale, prefix: prefix)

        if shift_result[:success]
          if shift_result[:changes_made]
            results[:items_with_changes] += 1
            results[:total_changes] += 1
          end
        else
          results[:errors] << shift_result[:errors].first
        end
      end

      results[:processed_items] += 1
    rescue StandardError => e
      error_msg = "Error processing item #{item.id} (#{item.sku}): #{e.message}"
      results[:errors] << error_msg
    end
  end

  results
end

.shift_images_for_item(item_id, locale: 'en', prefix: nil) ⇒ Hash

Shifts images for a specific item to fill empty slots in image type order

Parameters:

  • item_id (Integer)

    The ID of the item to shift images for

  • locale (String) (defaults to: 'en')

    The locale for the images (default: 'en')

  • prefix (String, nil) (defaults to: nil)

    Optional prefix to limit shifting to a specific group (e.g., 'AMZ', 'WAL')

Returns:

  • (Hash)

    Result of the operation including success status and any errors



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
# File 'app/services/image/image_shifting_service.rb', line 8

def self.shift_images_for_item(item_id, locale: 'en', prefix: nil)
  result = { success: true, errors: [], changes_made: false }

  begin
    item = Item.find(item_id)

    # Get before state
    before_profiles = get_item_image_profiles(item, locale, prefix)

    # Perform the shift
    ImageProfile.shift_images_for_item(item_id, locale: locale, prefix: prefix)

    # Get after state
    after_profiles = get_item_image_profiles(item, locale, prefix)

    # Check if changes were made
    result[:changes_made] = before_profiles != after_profiles
    result[:before_profiles] = before_profiles
    result[:after_profiles] = after_profiles
    result[:item] = item
  rescue StandardError => e
    result[:success] = false
    result[:errors] << "Error shifting images for item #{item_id}: #{e.message}"
  end

  result
end

.simulate_shift(current_profiles, prefix) ⇒ Object

Simulates a shift operation for dry run



211
212
213
214
215
# File 'app/services/image/image_shifting_service.rb', line 211

def self.simulate_shift(current_profiles, prefix)
  # This is a simplified simulation - in practice, you might want to duplicate the actual shift logic
  # For now, we'll just return the current profiles as-is
  current_profiles
end