Commit 2f3c0762 by Tran Hoang Viet

VietTH: Add rake update price for products amazon

parent 92e948d5
......@@ -12,7 +12,7 @@ class Product < ActiveRecord::Base
# validates
validates :title, presence: true, length: {maximum: 255}
validates :category, presence: true
validates :stock, presence: true, numericality: {greater_than: 0}
validates :stock, presence: true, numericality: {greater_than_or_equal_to: 0}
enum product_type: %i(system amazon)
......
namespace :aws do
desc "Get data and update to database"
task load_data: :environment do
request = Vacuum.new('GB')
@request = Vacuum.new('GB')
request.configure(
@request.configure(
aws_access_key_id: ENV['AWS_ACCESS'],
aws_secret_access_key: ENV['AWS_SECRET'],
associate_tag: ENV['AWS_TAG']
)
desc "Get data and update to database"
task load_data: :environment do
params = {
SearchIndex: 'All',
Keywords: '*',
......@@ -17,12 +17,36 @@ namespace :aws do
}
until params[:ItemPage] > 5
raw_products = request.item_search(query: params).to_h
raw_products = @request.item_search(query: params).to_h
set_data(raw_products['ItemSearchResponse']['Items'])
params[:ItemPage] += 1
end
end
desc 'Update price data every one hour'
task update_price: :environment do
Product.amazon.find_each(batch_size: 100) do |product|
response = find_product(product.asin)
if response.present?
price = response['LowestNewPrice'].try(:[], 'Amount').to_i
product.update(price: price) if product.price != price
end
end
end
def find_product(asin)
response = @request.item_lookup(
query: {
ItemId: asin,
ResponseGroup: 'OfferSummary'
}
).to_h
if response['ItemLookupResponse']['Items']['Request']['Errors'].blank?
response['ItemLookupResponse']['Items']['Item']['OfferSummary']
end
end
def set_data(data)
return unless data['Request']['IsValid'].downcase == 'true'
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment