Class: ExportedCatalogItemPacket

Inherits:
ApplicationRecord show all
Includes:
Models::Auditable, SearchesHelper
Defined in:
app/models/exported_catalog_item_packet.rb

Overview

== Schema Information

Table name: exported_catalog_item_packets
Database name: primary

id :integer not null, primary key
background_color :string default("FFFFFF")
image_format :string
image_height_gteq :integer
image_height_lteq :integer
image_width_gteq :integer
image_width_lteq :integer
inactive :boolean default(FALSE)
name :string
named_transformation :string
transformation_position :string default("path")
created_at :datetime not null
updated_at :datetime not null
customer_id :integer

Indexes

customer_id_inactive (customer_id,inactive)

Constant Summary collapse

RETAILER_IMAGE_PRESETS =
{
  "amazon"  => { named_transformation: "amazon_api", image_width_lteq: 2000, image_height_lteq: 2000, image_format: "jpeg", background_color: "FFFFFF" },
  "walmart" => { named_transformation: "walmart_marketplace_api", image_width_lteq: 2200, image_height_lteq: 2200, image_format: "jpeg", background_color: "FFFFFF" },
  "website" => { image_width_lteq: 1500, image_height_lteq: 1500, image_format: "jpeg", background_color: "FFFFFF" }
}.freeze

Constants included from Models::Auditable

Models::Auditable::ALWAYS_IGNORED

Instance Attribute Summary collapse

Belongs to collapse

Methods included from Models::Auditable

#creator, #updater

Has many collapse

Has and belongs to many collapse

Instance Method Summary collapse

Methods included from SearchesHelper

#adv_sortable, #cross_reference_customer_search_collection, #current_user_recent_searches, #field_wrap, #get_num_records, #hash_to_form_params, #header_search_selector, #line_items_search_fields, #permitted_search_types, #permitted_search_types_classes, #query_template_link, #result_search_selector, #rma_items_search_fields, #sales_rep_fields, #search_breadcrumb, #search_range_text_field, #search_select_field, #search_text_field, #simple_search_link, #yes_no_boolean_field

Methods included from Models::Auditable

#all_skipped_columns, #audit_reference_data, #should_not_save_version, #stamp_record

Methods inherited from ApplicationRecord

ransackable_associations, ransackable_attributes, ransackable_scopes, ransortable_attributes, #to_relation

Methods included from Models::EventPublishable

#publish_event

Instance Attribute Details

#image_height_gteqObject (readonly)



56
57
58
# File 'app/models/exported_catalog_item_packet.rb', line 56

validates :image_width_lteq, :image_width_gteq,
:image_height_lteq, :image_height_gteq,
numericality: { greater_than: 0, allow_nil: true }

#image_height_lteqObject (readonly)



56
57
58
# File 'app/models/exported_catalog_item_packet.rb', line 56

validates :image_width_lteq, :image_width_gteq,
:image_height_lteq, :image_height_gteq,
numericality: { greater_than: 0, allow_nil: true }

#image_width_gteqObject (readonly)



56
57
58
# File 'app/models/exported_catalog_item_packet.rb', line 56

validates :image_width_lteq, :image_width_gteq,
:image_height_lteq, :image_height_gteq,
numericality: { greater_than: 0, allow_nil: true }

#image_width_lteqObject (readonly)



56
57
58
# File 'app/models/exported_catalog_item_packet.rb', line 56

validates :image_width_lteq, :image_width_gteq,
:image_height_lteq, :image_height_gteq,
numericality: { greater_than: 0, allow_nil: true }

#selected_literaturesObject

Returns the value of attribute selected_literatures.



51
52
53
# File 'app/models/exported_catalog_item_packet.rb', line 51

def selected_literatures
  @selected_literatures
end

Instance Method Details

#apply_retailer_preset!(retailer_key) ⇒ Object



66
67
68
69
70
71
# File 'app/models/exported_catalog_item_packet.rb', line 66

def apply_retailer_preset!(retailer_key)
  preset = RETAILER_IMAGE_PRESETS[retailer_key.to_s]
  return unless preset

  update!(preset)
end

#catalog_items_statesObject



73
74
75
76
77
78
79
# File 'app/models/exported_catalog_item_packet.rb', line 73

def catalog_items_states
  exported_catalog_items.collect do |eci|
    eci.catalog_item.state
  rescue StandardError
    'unassigned'
  end.uniq.sort
end

#communicationsActiveRecord::Relation<Communication>

Returns:

See Also:



35
# File 'app/models/exported_catalog_item_packet.rb', line 35

has_many :communications, -> { order(:id).reverse_order }, as: :resource, dependent: :nullify

#create_default_packet_attributesObject



146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'app/models/exported_catalog_item_packet.rb', line 146

def create_default_packet_attributes
  %w[name description catalog_price parent_catalog_price discount].each do |attr_name|
    exported_catalog_item_packet_attributes.where(attr_name: attr_name).first_or_initialize(attr_type: 'catalog').save!
  end
  %w[shipping_height shipping_width shipping_length shipping_weight feature_1 feature_2 feature_3 feature_4 feature_5].each do |attr_name|
    exported_catalog_item_packet_attributes.where(attr_name: attr_name).first_or_initialize(attr_type: 'dynamic').save!
  end
  (1..15).each do |n|
    exported_catalog_item_packet_attributes.where(attr_name: "image_url_#{n}").first_or_initialize(attr_type: 'image').save!
    exported_catalog_item_packet_attributes.where(attr_name: "image_name_#{n}").first_or_initialize(attr_type: 'image').save!
  end

end

#create_zip(preserve_assets_directory: false, export_csv: true, export_xlsx: false, export_images: true, export_literatures: true) ⇒ Object



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
# File 'app/models/exported_catalog_item_packet.rb', line 204

def create_zip(preserve_assets_directory: false, export_csv: true, export_xlsx: false, export_images: true, export_literatures: true)
  unless export_csv || export_xlsx || export_images || export_literatures
    raise 'No output (csv, xlsx, image, or literature) specified'
  end

  require 'zip'
  require 'open-uri'
  packet_system_name = name.parameterize.tableize.singularize
  directory_path = Rails.root.join(Rails.application.config.x.temp_storage_path.to_s, "#{packet_system_name}_#{SecureRandom.hex(3)}")
  assets_directory_path = "#{directory_path}/assets"
  FileUtils.mkdir_p(assets_directory_path)

  if export_images
    images_path = "#{assets_directory_path}/images"
    export_images(images_path)
  end

  if export_csv
    file_name = "#{packet_system_name}.csv"
    file_path = "#{assets_directory_path}/#{file_name}"
    export_csv(file_path)
  end

  if export_xlsx
    file_name = "#{packet_system_name}.xlsx"
    file_path = "#{assets_directory_path}/#{file_name}"
    export_xlsx(file_path)
  end

  if export_literatures
    literature_path = "#{assets_directory_path}/literature"
    export_literatures(literature_path)
  end

  # Now zip it all up
  zip_file_name = "#{packet_system_name}.zip"
  zip_file_path = "#{directory_path}/#{zip_file_name}"
  zf = ZipFileGenerator.new(assets_directory_path, zip_file_path)
  zf.write

  # Cleanup
  FileUtils.rm_rf(assets_directory_path) unless preserve_assets_directory

  zip_file_path
end

#customerCustomer

Returns:

See Also:



30
# File 'app/models/exported_catalog_item_packet.rb', line 30

belongs_to :customer, optional: true

#export_csv(file_path) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'app/models/exported_catalog_item_packet.rb', line 108

def export_csv(file_path)
  CSV.open(file_path, 'w', force_quotes: true) do |csv|
    csv << selected_attributes.collect { |a| a.attr_rename.nil? ? a.attr_name : a.attr_rename}
    exported_catalog_items.each do |ec_item|
      row = selected_attributes.map do |attribute|
        attribute.render_value(ec_item)
      end
      csv << row
    end
  end
  File.chmod(0o444, file_path.to_s)
  file_path
end

#export_images(images_path) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'app/models/exported_catalog_item_packet.rb', line 160

def export_images(images_path)
  FileUtils.mkdir_p(images_path)
  counter = 0
  exported_catalog_items.each do |ci|
    ci.exported_catalog_item_images.where(excluded: false).each do |im|
      im.download(images_path)
      counter += 1
    rescue Dragonfly::Job::Fetch::NotFound, Down::NotFound => e
      # Down::NotFound covers HTTP 404s from the CDN-backed image URL; we don't
      # want one missing source image to abort the entire packet export.
      logger.error "Image #{im.image_id} not found. #{e}"
    end
  end
  counter
end

#export_literatures(literature_path) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'app/models/exported_catalog_item_packet.rb', line 176

def export_literatures(literature_path)
  FileUtils.mkdir_p(literature_path)
  counter = 0
  exported_catalog_items.each do |ci|
    ci.publications.joins(:literature).includes(:literature).find_each do |pub|
      literature = pub.literature
      lit_name = "#{ci.catalog_item.item.sku}_literature_#{literature.attachment_name}"
      literature.attachment.to_file("#{literature_path}/#{lit_name}") # rescue nil
      counter += 1
    rescue Dragonfly::Job::Fetch::NotFound => e
      logger.error "Literature #{literature.id} not found. #{e}"
    end
  end
  counter
end

#export_xlsx(file_path) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'app/models/exported_catalog_item_packet.rb', line 122

def export_xlsx(file_path)
  require "rubyXL"

  workbook = RubyXL::Workbook.new
  ws = workbook[0]
  ws.sheet_name = "Attributes"

  selected_attributes.each_with_index do |a, i|
    ws.add_cell(0, i, a.attr_rename.presence || a.attr_name)
  end

  exported_catalog_items.includes(
    catalog_item: [:item, :catalog],
    exported_catalog_item_images: :image
  ).each_with_index do |ec_item, row|
    selected_attributes.each_with_index do |att, col|
      ws.add_cell(row + 1, col, att.render_value(ec_item).to_s)
    end
  end

  workbook.write(file_path)
  file_path
end

#exported_catalog_item_packet_attributesActiveRecord::Relation<ExportedCatalogItemPacketAttribute>

Returns:

See Also:



33
# File 'app/models/exported_catalog_item_packet.rb', line 33

has_many :exported_catalog_item_packet_attributes, -> { order(attr_position: :asc) }, dependent: :destroy

#exported_catalog_item_packet_image_attributesActiveRecord::Relation<ExportedCatalogItemPacketImageAttribute>

Returns:

See Also:



34
# File 'app/models/exported_catalog_item_packet.rb', line 34

has_many :exported_catalog_item_packet_image_attributes, inverse_of: :exported_catalog_item_packet, dependent: :destroy

#exported_catalog_itemsActiveRecord::Relation<ExportedCatalogItem>

Returns:

See Also:



32
# File 'app/models/exported_catalog_item_packet.rb', line 32

has_many :exported_catalog_items, dependent: :destroy

#generate_packet(export_csv: true, export_xlsx: false, export_images: true, export_literatures: true) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
# File 'app/models/exported_catalog_item_packet.rb', line 192

def generate_packet(export_csv: true, export_xlsx: false, export_images: true, export_literatures: true)
  zip_file_path = create_zip(export_csv:, export_xlsx:, export_images:, export_literatures:)
  # Store this zip in our upload
  upload = Upload.uploadify(zip_file_path, 'exported_packet', self, name)
  if upload.persisted?
    # generate a download token publically accessible
    upload.create_new_download_token
    uploads << upload
  end
  upload
end


85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'app/models/exported_catalog_item_packet.rb', line 85

def link_images
  unlink_images

  image_attributes = exported_catalog_item_packet_image_attributes.where(selected: true)

  exported_catalog_items.each do |ci|
    image_attributes.each do |image_attribute|
      images = image_attribute.retrieve_images(ci.item).all_images
      images.each do |image|
        ci.exported_catalog_item_images.create!(
          image_id: image.id,
          tag: image_attribute.tag,
          excluded: false
        )
      end
    end
  end
end

#selected_attributesObject



104
105
106
# File 'app/models/exported_catalog_item_packet.rb', line 104

def selected_attributes
  @selected_attributes ||= exported_catalog_item_packet_attributes.where(selected: true).order(:attr_position)
end


81
82
83
# File 'app/models/exported_catalog_item_packet.rb', line 81

def unlink_images
  ExportedCatalogItemImage.joins(:exported_catalog_item).merge(exported_catalog_items).delete_all
end

#uploadsActiveRecord::Relation<Upload>

Returns:

  • (ActiveRecord::Relation<Upload>)

See Also:



37
# File 'app/models/exported_catalog_item_packet.rb', line 37

has_and_belongs_to_many :uploads, inverse_of: :exported_catalog_item_packets