Sha256: 45cae8c1ae4b0c659b1a679eb0fcf8b1c0c2b4ae03bbeafcf2880ef8711a0223

Contents?: true

Size: 1.9 KB

Versions: 1

Compression:

Stored size: 1.9 KB

Contents

module Gemgento
  class InventoryImportValidator < ActiveModel::Validator

    def validate(record)
      @record = record

      begin
        @record.spreadsheet
      rescue Exception => e
        Rails.logger.error e.message
        @record.errors[:file] = 'Invalid Spreadsheet'
        return
      end

      validate_required_attributes
      validate_sku
      validate_attributes
    end

    def validate_required_attributes
      errors = []
      %w[sku quantity manage_stock is_in_stock].each do |attribute|
        errors << attribute unless @record.header_row.include? attribute
      end

      unless errors.empty?
        error = '<b>The following required attributes could not be found:</b><br /><ul><li>'
        error += errors.join('</li><li>')
        error += '</li></ul>'

        @record.errors[:file]= "<div>#{error}</div>"
      end
    end

    def validate_sku
      errors = []

      @record.content_index_range.each do |index|
        row = @record.spreadsheet.row(index)
        sku = row[@record.header_row.index('sku').to_i].to_s.strip
        next if sku.blank?

        errors << sku unless product = Gemgento::Product.not_deleted.find_by(sku: sku)
      end

      unless errors.empty?
        error = '<b>The following SKU(s) could not be found:</b><br /><ul><li>'
        error += errors.join('</li><li>')
        error += '</li></ul>'

        @record.errors[:file]= "<div>#{error}</div>"
      end
    end

    def validate_attributes
      errors = []

      @record.header_row.each do |attribute|
        next if attribute == 'sku'
        errors << attribute unless Gemgento::Inventory.column_names.include? attribute
      end

      unless errors.empty?
        error = '<b>The following inventory attributes could not be found:</b><br /><ul><li>'
        error += errors.join('</li><li>')
        error += '</li></ul>'

        @record.errors[:file]= "<div>#{error}</div>"
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gemgento-2.8.0 app/validators/gemgento/inventory_import_validator.rb