Sha256: 92d74cdc25d76afab7aa0bb5e2393002bec622868661a962b196e7ca68df6cdc

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

module SolidusBling
  class Product < ApplicationRecord
    belongs_to :account

    def self.update bling_account
      bling_api = SolidusBling::Api.new(bling_account)
      skus = Spree::Variant.pluck(:sku)
      hash_products = {}
      products = skus.map do |sku|
        begin 
          attempts ||= 1
          req = Typhoeus.get("#{bling_api.account.api_base_url}/produtos?codigo=#{sku}", headers: bling_api.headers)
          res_json = JSON.parse(req.body)
          p "#{sku} => #{res_json}"
          next if res_json["data"] == []
          product = res_json["data"].first
          hash_products[sku] = product["id"]
          { 
            account_id: bling_api.account.id,
            sku: sku,
            external_id: product["id"].to_s,
            name: product["nome"]
          }
        rescue => e
          hash_products[sku] = res_json
          p "#{sku} => #{res_json} => #{e}"
          sleep 1
          retry if (attempts += 1) < 5
        end
      end.compact.uniq
      SolidusBling::Product.upsert_all(products, unique_by: :sku)
      Spree::Bus.publish :bling_products_updated, products: hash_products
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
solidus_bling-2.0.1 app/models/solidus_bling/product.rb
solidus_bling-2.0.0 app/models/solidus_bling/product.rb