Class: ItemSearch

Inherits:
Search show all
Defined in:
app/models/item_search.rb

Overview

== Schema Information

Table name: searches
Database name: primary

id :integer not null, primary key
name :string(255)
persist :boolean default(FALSE)
pinned :boolean default(FALSE), not null
query_params :jsonb
result_set_size :integer default(0)
selected_columns :string is an Array
set_limit :integer default(25)
sort_column :string(255)
sort_columns :string default([]), not null, is an Array
sort_direction :string(255) default("ASC")
type :string(255) not null
created_at :datetime
updated_at :datetime
employee_id :integer

Indexes

employee_id_pinned (employee_id,pinned)
employee_id_type (employee_id,type)

Constant Summary

Constants inherited from Search

Search::DISTANCE_SEARCH_KEYS

Instance Attribute Summary

Attributes inherited from Search

#composite_columns, #pagy_count, #pagy_limit, #pagy_page, #sort_column1, #sort_column2, #sort_column3, #sql_select_columns

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Search

#all_composite_columns, allowed_role_ids, #append_custom_column, #append_ouput_column, #append_to_sql_select_columns, #applicable_sort_terms, #apply_array_match, #apply_criteria, #apply_customer_cross_reference, #apply_distance_search, #apply_select, #apply_sort, #available_events, available_output_columns, #available_output_columns, base_search_class_name, #cleanup_search_results, composite_column, #composite_column, custom_criteria_keys, database_columns, default_columns, default_sort, #discard_excess, #effective_name, #effective_short_name, #employee, #enqueue_navbar_pinned_refresh, #fast_count, favorites, friendly_column_name, #get_pinned_results, #get_sort_term, global_favorite, has_role_for_search?, #human_query_params, instantiate_query_template, #instantiate_resource_updater, #limit_options, main_resource_class, main_resource_table, mass_actions_for_select, #mass_export, maximum_unpersisted_queries, #normalize_for_mass_update, options, options_classes, #output_columns_for_select, #pagy_from_search, #perform, #perform_selected, #pinned_query, #prepend_custom_column, #prepend_output_column, query_favorites_templates, recent_searches_for_employee_id, #record_list, #refresh_pinned_results, #remove_other_pins, search_name, #search_name, #search_results, search_type, search_type_humanized, select_sort_columns, #select_sort_columns, #select_statement, #set_defaults, #set_sort_term, #sort_columns_for_select, #sort_columns_to_hash, #target_geocoding, unpersisted_queries_quote_reached?, #unrecord_list, #validated_selected_columns, view_resource_class, view_resource_klass, #view_resource_klass, view_resource_table, visible?, with_search_results

Methods inherited from ApplicationRecord

ransackable_associations, ransackable_attributes, ransackable_scopes, ransortable_attributes, #to_relation

Methods included from Models::EventPublishable

#publish_event

Class Method Details

.discounts_collection_for_selectObject



74
75
76
# File 'app/models/item_search.rb', line 74

def self.discounts_collection_for_select
  [['Inherit catalog settings if any', nil]] + (0..100).to_a.map { |e| ["#{e} %", (e.to_f / 100).round(2)] }
end

Instance Method Details

#apply_custom_criteria(results) ⇒ Object



39
40
41
42
43
44
# File 'app/models/item_search.rb', line 39

def apply_custom_criteria(results)
  query_params.select { |k, _v| k.to_s.index('spec_field_')&.zero? }.map { |k, v| [k.to_s.split(/^spec_field_/).join, v] }.each do |spec_field, spec_value|
    results = results.with_product_specification(spec_field, spec_value)
  end
  results
end

#mass_add_to_next_cycle_count(params, cur_user = nil) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
# File 'app/models/item_search.rb', line 118

def mass_add_to_next_cycle_count(params, cur_user = nil)
  return { status: :error, message: 'Target Store must be specified' } unless params[:target_store_id].present?

  jid = MassSearch::ItemAddToNextCycleCountWorker.perform_async(
    'search_id'     => id,
    'action_params' => { 'target_store_id' => params[:target_store_id] },
    'user_id'       => cur_user&.id,
    'locale'        => I18n.locale.to_s
  )
  { status: :ok, job_id: jid }
end

#mass_assign_to_catalog(params, cur_user = nil) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'app/models/item_search.rb', line 101

def mass_assign_to_catalog(params, cur_user = nil)
  return { status: :error, message: 'Access Denied' } unless cur_user..can?(:update, Item)
  return { status: :error, message: 'Target Catalog must be specified' } unless params[:target_catalog_id].present?

  jid = MassSearch::ItemAssignToCatalogWorker.perform_async(
    'search_id'     => id,
    'action_params' => {
      'target_catalog_id'             => params[:target_catalog_id],
      'discount_to_apply'             => params[:discount_to_apply],
      'add_kit_components_to_catalog' => params[:add_kit_components_to_catalog]
    },
    'user_id'       => cur_user&.id,
    'locale'        => I18n.locale.to_s
  )
  { status: :ok, job_id: jid }
end

#mass_compare_specs(context) ⇒ Object



170
171
172
173
174
175
# File 'app/models/item_search.rb', line 170

def mass_compare_specs(context)
  item_ids = search_results.pluck(:resource_id)
  return { status: :error, message: 'No items selected' } unless item_ids.present?

  context.redirect_to context.reports_items_spec_matrix_path(command: { item_ids: })
end

#mass_create_specs(context) ⇒ Object



177
178
179
180
181
182
# File 'app/models/item_search.rb', line 177

def mass_create_specs(context)
  item_ids = search_results.pluck(:resource_id)
  return { status: :error, message: 'No items selected' } unless item_ids.present?

  context.redirect_to context.new_product_specification_path(product_specification: { item_ids: })
end

#mass_export_amazon_multibox_csv(params = {}, cur_user = nil, path = nil) ⇒ Object



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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'app/models/item_search.rb', line 197

def mass_export_amazon_multibox_csv(params = {}, cur_user = nil, path = nil)
  item_ids = search_results.pluck(:resource_id)
  return { status: :error, message: 'No items selected' } unless item_ids.present?

  file_name = "export_amazon_multibox_#{id}.csv"
  warehouse_code = params[:warehouse_code].presence || 'DFEE'
  warehouse_name_by_warehouse_code = {
    DFEE: 'WarmlyYours Radiant Inc.',
    AMDR: 'WY-RICHMOND HILL'
  }.with_indifferent_access
  units_by_warehouse_code = {
    DFEE: { length: 'in', weight: 'lbs' },
    AMDR: { length: 'cm', weight: 'kg' }
  }.with_indifferent_access
  part_1_column_names_to_item_methods_hash = {
    SKU: :sku, UPC: :upc, ASIN: :amazon_asin, Title: :title_for_amazon, Warehouse: warehouse_code, 'Warehouse name': warehouse_name_by_warehouse_code[warehouse_code]
  }.with_indifferent_access
  part_2_column_names_by_warehouse_code = {
    DFEE: ['Package number', 'Dimension lock', 'Length (in)', 'Height (in)', 'Width (in)', 'Weight (lb)'],
    AMDR: ['Package number', 'Length (cm)', 'Height (cm)', 'Width (cm)', 'Weight (kg)']
  }.with_indifferent_access
  directory_path = path || Rails.root.join(Rails.application.config.x.temp_storage_path.to_s, 'users', cur_user ? cur_user.id.to_s : '')
  FileUtils.mkdir_p(directory_path)
  file_path = Rails.root.join(directory_path, file_name)
  encoding = params[:encoding].presence || 'UTF-8'
  CSV.open(file_path, 'w', force_quotes: true, encoding: encoding) do |csv|
    csv << (part_1_column_names_to_item_methods_hash.keys + part_2_column_names_by_warehouse_code[warehouse_code])
    items = Item.where(id: item_ids)
    items.each do |item|
      item.boxes_shipping_dimensions_and_weights_converted(units: units_by_warehouse_code[warehouse_code], precision: 2).each_with_index do |box, i|
        row = []
        part_1_column_names_to_item_methods_hash.values.each do |value_or_symbol|
          value = value_or_symbol.is_a?(Symbol) ? item.send(value_or_symbol) : value_or_symbol
          if params[:transliterate].to_b
            value = value.delete('') # Remove trademark symbol otherwise you'd end up with a ?
            value = value.delete('©') # Remove copyright symbol otherwise you'd end up with a ?
            value = value.gsub('', ' ft.') # Expand prime symbol to its unit definition
            value = value.gsub('', ' ft.') # Expand prime symbol to its unit definition
            value = value.gsub('ʺ', ' in.') # Expand double-prime symbol to its unit definition
            value = value.gsub('', ' in.') # Expand double-prime symbol to its unit definition
          end
          value = I18n.transliterate(value) if params[:encoding].to_s == 'ASCII' # Anything else that is unsavory for ASCII can be transliterated, unless our encoding is UTF-8
          row << value
        end
        row << (i + 1) # Package number
        if warehouse_code == 'DFEE'
          row << 'FALSE' # Dimension lock, which is apparently only for DFEE (not AMDR), is always FALSE as far as I can see
        end
        row << box[0] # Length
        row << box[1] # Width
        row << box[2] # Height
        row << box[3] # Weight
        csv << row
      end
    end
  end
  { status: :ok, result_file: file_name, result_file_path: file_path }
end

#mass_print_item_identifier_labels(params, cur_user = nil) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'app/models/item_search.rb', line 130

def mass_print_item_identifier_labels(params, cur_user = nil)
  print_profile = PrintProfile.where(id: params[:print_profile_id]).first
  quantity = params[:quantity]&.to_i || 1
  size = params[:size] || 'regular'
  target_market = params[:target_market]
  # return { status: :error, message: 'Print Profile must be selected' } unless print_profile
  ru = instantiate_resource_updater(params[:resource])
  result = { status: :ok }
  # If we are not to send to a printer but instead generate a pdf, we need to store this pdf somewhere
  if print_profile.nil?
    combined_pdf = PdfCombinator.new
    file_name = "export_labels_#{id}.pdf"
    directory_path = Rails.root.join(Rails.application.config.x.temp_storage_path.to_s, 'users', "#{cur_user&.id || 0}")
    FileUtils.mkdir_p(directory_path)
    file_path = Rails.root.join(directory_path, file_name)
    result[:result_file] = file_name
    result[:result_file_path] = file_path
  end

  ru.perform do |item|
    upc_result = Pdf::Label::ItemIdentifier.call(item, size:, target_market:)
    if print_profile
      base64_output = Base64.encode64(upc_result.pdf)
      print_profile.print(base64_output, quantity:)
    else # Download, so let's combine our pdf
      combined_pdf << upc_result.pdf
    end
    { ok: true }
  end
  if print_profile.nil?
    File.open(result[:result_file_path], 'wb') do |file|
      file.write combined_pdf.to_pdf
      file.flush
      file.fsync
    end
  end

  result
end

#mass_refresh_item_specs(context) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
# File 'app/models/item_search.rb', line 184

def mass_refresh_item_specs(context)
  return { status: :error, message: 'Access Denied' } unless context..can?(:update, Item)

  item_ids = perform_selected(selected_columns: %i[id]).pluck(:id)
  if item_ids.present?
    item_ids.each { |iid| ItemAttributeWorker.perform_async(iid) }
    context.flash[:info] = "#{item_ids.size} queued for spec refresh"
  else
    context.flash[:warning] = 'No item(s) selected'
  end
  context.redirect_to(context.search_path(self))
end

#mass_update(params, cur_user) ⇒ Object

Mass actions section #



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'app/models/item_search.rb', line 81

def mass_update(params, cur_user)
  return { status: :error, message: 'Access Denied' } unless cur_user..can?(:update, Item)

  resource_params      = (params[:resource] || {}).to_h
  add_product_line_ids    = resource_params.delete('add_product_line_ids') || resource_params.delete(:add_product_line_ids) || []
  remove_product_line_ids = resource_params.delete('remove_product_line_ids') || resource_params.delete(:remove_product_line_ids) || []

  jid = MassSearch::ItemUpdateWorker.perform_async(
    'search_id'     => id,
    'action_params' => {
      'resource_params'           => resource_params,
      'add_product_line_ids'      => add_product_line_ids,
      'remove_product_line_ids'   => remove_product_line_ids
    },
    'user_id'       => cur_user&.id,
    'locale'        => I18n.locale.to_s
  )
  { status: :ok, job_id: jid }
end

#ransack_probe_paramsObject



35
36
37
# File 'app/models/item_search.rb', line 35

def ransack_probe_params
  super.reject { |k, _| k.to_s.start_with?('spec_field_') }
end