Skip to content

Commit

Permalink
Import on-demand stock setting in DFC import
Browse files Browse the repository at this point in the history
  • Loading branch information
mkllnk committed Sep 19, 2024
1 parent ededa91 commit 585bd88
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions app/models/spree/variant.rb
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,8 @@ def set_cost_currency
end

def create_stock_items
return unless stock_items.empty?

StockLocation.find_each do |stock_location|
stock_location.propagate_variant(self)
end
Expand Down
22 changes: 22 additions & 0 deletions engines/dfc_provider/app/services/catalog_item_builder.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# frozen_string_literal: true

class CatalogItemBuilder < DfcBuilder
def self.apply_stock(item, variant)
limit = item&.stockLimitation

return if limit.blank?

# Negative stock means "on demand".
# And we are only interested in that for now.
return unless limit.to_i.negative?

if variant.stock_items.empty?
variant.stock_items << Spree::StockItem.new(
stock_location: DefaultStockLocation.find_or_create,
variant:,
)
end

variant.stock_items[0].backorderable = true
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def self.import_variant(supplied_product, supplier)
end.tap do |variant|
link = supplied_product.semanticId
variant.semantic_links.new(semantic_id: link) if link.present?
CatalogItemBuilder.apply_stock(supplied_product&.catalogItems&.first, variant)
end
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,23 @@
value: 2,
),
productType: product_type,
catalogItems: [catalog_item],
)
end
let(:product_type) { DfcLoader.connector.PRODUCT_TYPES.VEGETABLE.NON_LOCAL_VEGETABLE }
let(:catalog_item) {
DataFoodConsortium::Connector::CatalogItem.new(
nil,
# On-demand is expressed as negative stock.
# And some APIs send strings instead of numbers...
stockLimitation: "-1",
)
}

it "creates a new Spree::Product and variant" do
# We need this to save stock:
DefaultStockLocation.find_or_create

create(:taxon)

expect(imported_variant).to be_a(Spree::Variant)
Expand All @@ -169,6 +181,11 @@
expect(imported_product.name).to eq("Tomato")
expect(imported_product.description).to eq("Awesome tomato")
expect(imported_product.variant_unit).to eq("weight")

# Stock can only be checked when persisted:
imported_product.save!
expect(imported_variant.on_demand).to eq true
expect(imported_variant.on_hand).to eq 0
end

context "with spree_product_id supplied" do
Expand Down

0 comments on commit 585bd88

Please sign in to comment.