~singpolyma/whiplash-mboa

02529a5dd65a1fbaefb75fbff24cb293140eb2b9 — Stephen Paul Weber 1 year, 3 months ago 4151477
Cache full stock pull data
1 files changed, 17 insertions(+), 11 deletions(-)

M app/controllers/fulfillment_controller.rb
M app/controllers/fulfillment_controller.rb => app/controllers/fulfillment_controller.rb +17 -11
@@ 19,31 19,37 @@ class FulfillmentController < ApplicationController
	end

	def fetch_stock
		item_ids = if params[:sku]
			WHIPLASH_HTTP.get(
		items = if params[:sku]
			fetch_items(WHIPLASH_HTTP.get(
				"items/sku/#{params[:sku]}",
				nil,
				"X-API-KEY" => @shop.whiplash_api_key
			).body.each_with_object({}) { |item, h| h[params[:sku]] = item["id"] }.tap do |ids|
			).body.each_with_object({}) { |item, h| h[params[:sku]] = item["id"] }.tap { |ids|
				CreateWhiplashItemJob.perform_later(@shop, params[:sku]) if ids.empty?
			end
			})
		else
			Rails.cache.fetch("all_whiplash_items-#{@shop.id}", expires_in: 4.hours) do
				fetch_all_items.each_with_object({}) { |item, h| h[item["sku"]] = item["id"] }
			Rails.cache.fetch("whiplash_stock-#{@shop.id}", expires_in: 50.minutes) do
				fetch_items(Rails.cache.fetch("all_whiplash_items-#{@shop.id}", expires_in: 4.hours) {
					fetch_all_items.each_with_object({}) { |item, h| h[item["sku"]] = item["id"] }
				})
			end
		end

		results = items.transform_values { |item|
			item.find { |warehouse| warehouse["id"].to_s == @service.whiplash_id }&.dig("sellable_quantity") || 0
		}

		render json: results
	end

	def fetch_items(item_ids)
		WHIPLASH_HTTP.in_parallel do
			@requests = item_ids.transform_values { |item_id|
				WHIPLASH_HTTP.get("items/#{item_id}/warehouse_quantities", nil, "X-API-KEY" => @shop.whiplash_api_key)
			}
		end

		results = @requests.transform_values { |req|
			req.body.find { |warehouse| warehouse["id"].to_s == @service.whiplash_id }&.dig("sellable_quantity") || 0
		}

		render json: results
		@requests.transform_values(&:body)
	end

	def order_notification