diff --git a/engines/dfc_provider/app/controllers/dfc_provider/catalog_items_controller.rb b/engines/dfc_provider/app/controllers/dfc_provider/catalog_items_controller.rb index 378e904d2f..b668cfbe63 100644 --- a/engines/dfc_provider/app/controllers/dfc_provider/catalog_items_controller.rb +++ b/engines/dfc_provider/app/controllers/dfc_provider/catalog_items_controller.rb @@ -15,7 +15,8 @@ module DfcProvider end def show - render json: variant, serializer: DfcProvider::CatalogItemSerializer + dfc_object = DfcBuilder.catalog_item(variant) + render json: DfcLoader.connector.export(dfc_object) end private diff --git a/engines/dfc_provider/app/services/dfc_builder.rb b/engines/dfc_provider/app/services/dfc_builder.rb new file mode 100644 index 0000000000..4a56319589 --- /dev/null +++ b/engines/dfc_provider/app/services/dfc_builder.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +class DfcBuilder + def self.catalog_item(variant) + id = urls.enterprise_catalog_item_url( + enterprise_id: variant.product.supplier_id, + id: variant.id, + ) + product = supplied_product(variant) + + DataFoodConsortium::Connector::CatalogItem.new( + id, product: product, + sku: variant.sku, + offers: [offer(variant)], + ) + end + + def self.supplied_product(variant) + id = urls.enterprise_supplied_product_url( + enterprise_id: variant.product.supplier_id, + id: variant.id, + ) + + DataFoodConsortium::Connector::SuppliedProduct.new( + id, name: variant.name, description: variant.description + ) + end + + def self.offer(variant) + id = "/offers/#{variant.id}" + offered_to = [] + + # The DFC sees "empty" stock as unlimited. + # http://static.datafoodconsortium.org/conception/DFC%20-%20Business%20rules.pdf + stock = variant.on_demand ? nil : variant.total_on_hand + + DataFoodConsortium::Connector::Offer.new( + id, offeredTo: offered_to, + price: variant.price.to_f, + stockLimitation: stock, + ) + end + + def self.urls + DfcProvider::Engine.routes.url_helpers + end +end diff --git a/engines/dfc_provider/spec/services/offer_builder_spec.rb b/engines/dfc_provider/spec/services/offer_builder_spec.rb new file mode 100644 index 0000000000..468e5ec052 --- /dev/null +++ b/engines/dfc_provider/spec/services/offer_builder_spec.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +require DfcProvider::Engine.root.join("spec/spec_helper") + +describe DfcBuilder do + let(:variant) { build(:variant) } + + describe ".offer" do + it "assigns a stock level" do + # Assigning stock only works with persisted records: + variant.save! + variant.on_hand = 5 + + offer = DfcBuilder.offer(variant) + + expect(offer.stockLimitation).to eq 5 + end + + it "has no stock limitation when on demand" do + # Assigning stock only works with persisted records: + variant.save! + variant.on_hand = 5 + variant.on_demand = true + + offer = DfcBuilder.offer(variant) + + expect(offer.stockLimitation).to eq nil + end + end +end