From 4eb5464a843ece68f01973107e62791e80cd6d23 Mon Sep 17 00:00:00 2001 From: Stephen Paul Weber Date: Wed, 30 Nov 2022 12:37:44 -0500 Subject: [PATCH] Create new whiplash item when asked for a sku that does not exist --- app/controllers/fulfillment_controller.rb | 4 +- app/jobs/create_whiplash_item_job.rb | 49 ++++++++++++++++++++++ test/jobs/create_whiplash_item_job_test.rb | 9 ++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 app/jobs/create_whiplash_item_job.rb create mode 100644 test/jobs/create_whiplash_item_job_test.rb diff --git a/app/controllers/fulfillment_controller.rb b/app/controllers/fulfillment_controller.rb index 9c9554f..98afd2c 100644 --- a/app/controllers/fulfillment_controller.rb +++ b/app/controllers/fulfillment_controller.rb @@ -23,7 +23,9 @@ class FulfillmentController < ApplicationController "items/sku/#{params[:sku]}", nil, "X-API-KEY" => @shop.whiplash_api_key - ).body.each_with_object({}) { |item, h| h[params[:sku]] = item["id"] } + ).body.each_with_object({}) { |item, h| h[params[:sku]] = item["id"] }.tap do |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"] } diff --git a/app/jobs/create_whiplash_item_job.rb b/app/jobs/create_whiplash_item_job.rb new file mode 100644 index 0000000..ac71758 --- /dev/null +++ b/app/jobs/create_whiplash_item_job.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +class CreateWhiplashItemJob < ApplicationJob + queue_as :default + + def perform(shop, sku) + shop.with_shopify_session do + response = ShopifyAPI::Clients::Graphql::Admin.new( + session: ShopifyAPI::Context.active_session + ).query(query: <<~GRAPHQL, variables: { q: "sku:#{sku}" }) + query fetch($q: String) { + productVariants(first: 1, query: $q) { + edges { + node { + sku + legacyResourceId + displayName + price + image { + url + } + } + } + } + } + GRAPHQL + + variant = response.body&.dig("data", "productVariants", "edges", 0, "node") + return if !variant || variant["sku"] != sku + + response = WHIPLASH_HTTP.post( + "items", + { + sku: variant["sku"], + originator_id: variant["legacyResourceId"], + title: variant["displayName"], + price: variant["price"], + image_originator_url: variant.dig("image", "url") + }, + "X-API-KEY" => shop.whiplash_api_key + ) + + Rails.logger.error response.to_s if response.status != 201 + rescue StandardError + Sentry.capture_exception($!) + Rails.logger.error $!.to_s + end + end +end diff --git a/test/jobs/create_whiplash_item_job_test.rb b/test/jobs/create_whiplash_item_job_test.rb new file mode 100644 index 0000000..8df5e4e --- /dev/null +++ b/test/jobs/create_whiplash_item_job_test.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +require "test_helper" + +class CreateWhiplashItemJobTest < ActiveJob::TestCase + # test "the truth" do + # assert true + # end +end -- 2.45.2