Skip to content

Commit 339852b

Browse files
authored
Merge pull request #51 from CruGlobal/delete_old_products
Delete products that are no longer in Woo
2 parents f5eb841 + 4a491c2 commit 339852b

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

app/services/woo_refresh.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ def handle_job job
103103

104104
def save_products_to_db job, products
105105
log job, "Found #{products.count} products. Saving to database."
106+
existing_products = WooProduct.all.to_a
107+
106108
products.each do |product|
107109
woo_product = WooProduct.find_or_create_by(product_id: product["id"])
108110
woo_product.sku = product["sku"]
@@ -116,8 +118,14 @@ def save_products_to_db job, products
116118
wbi.save!
117119
end
118120
end
121+
existing_products.delete(woo_product)
119122
log job, "Saved product #{woo_product.product_id} with sku #{woo_product.sku}. Bundle count: #{product["bundled_items"].count}"
120123
end
124+
125+
existing_products.each do |product|
126+
product.destroy
127+
log job, "Deleted product #{product.product_id}"
128+
end
121129
rescue => e
122130
log job, "Error saving products to database: #{e.message}"
123131
job.status_error!

spec/services/woo_refresh_spec.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,25 @@
3838
end
3939

4040
it("it should save products to the db") do
41-
allow(woo).to receive(:get_page).and_return([{"id" => 1, "name" => "Test Product", "price" => "10.00", "sku" => "12345", "description" => "Test Description", "categories" => [{"id" => 1, "name" => "Test Category"}]}])
41+
allow(woo).to receive(:get_page).and_return([{"id" => 1, "name" => "Test Product", "price" => "10.00", "sku" => "12345", "description" => "Test Description", "bundled_items" => [], "categories" => [{"id" => 1, "name" => "Test Category"}]}])
4242

4343
job = woo.create_job
4444
products = woo.get_page job, 1, {status: "publish", per_page: 1, page: 1}
4545
woo.save_products_to_db job, products
4646
expect(WooProduct.count).to be > 0
4747
end
4848

49+
it "should delete products that are no longer in woo" do
50+
allow(woo).to receive(:get_page).and_return([{"id" => 1, "name" => "Test Product", "price" => "10.00", "sku" => "12345", "description" => "Test Description", "bundled_items" => [], "categories" => [{"id" => 1, "name" => "Test Category"}]}])
51+
create(:woo_product, product_id: 30)
52+
53+
job = woo.create_job
54+
products = woo.get_page job, 1, {status: "publish", per_page: 1, page: 1}
55+
woo.save_products_to_db job, products
56+
expect(WooProduct.count).to eq(1)
57+
expect(WooProduct.find_by(product_id: 30)).to be_nil
58+
end
59+
4960
it("it should handle a job") do
5061
job = woo.create_job
5162
woo.handle_job job

0 commit comments

Comments
 (0)