Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
SD-1511 System should emit `variant.out_of_stock` if Variant is sold out (#11464)
Aleksandar Petrushevad1f829c6c5c
diff --git a/api/app/models/spree/api/webhooks/stock_movement_decorator.rb b/api/app/models/spree/api/webhooks/stock_movement_decorator.rbnew file mode 100644index 0000000000..f27ac58eac--- /dev/null+++ b/api/app/models/spree/api/webhooks/stock_movement_decorator.rb@@ -0,0 +1,22 @@+module Spree+ module Api+ module Webhooks+ module StockMovementDecorator+ def update_stock_item_quantity+ variant_in_stock_before_update = variant_in_stock?+ super+ variant = stock_item.variant+ variant.queue_webhooks_requests!('variant.out_of_stock') if variant_in_stock_before_update && !variant_in_stock?+ end++ private++ def variant_in_stock?+ stock_item.variant.in_stock?+ end+ end+ end+ end+end++Spree::StockMovement.prepend(Spree::Api::Webhooks::StockMovementDecorator)diff --git a/api/spec/models/spree/api/webhooks/stock_movement_decorator_spec.rb b/api/spec/models/spree/api/webhooks/stock_movement_decorator_spec.rbnew file mode 100644index 0000000000..e8f16f9a05--- /dev/null+++ b/api/spec/models/spree/api/webhooks/stock_movement_decorator_spec.rb@@ -0,0 +1,40 @@+require 'spec_helper'++describe Spree::StockMovement do+ let(:stock_item) { create(:stock_item) }+ let(:variant) { stock_item.variant }+ let(:stock_movement) { create(:stock_movement, stock_item: stock_item, quantity: movement_quantity) }+ let(:body) { Spree::Api::V2::Platform::VariantSerializer.new(variant).serializable_hash.to_json }++ describe '#update_stock_item_quantity' do+ subject { stock_movement }++ describe 'when the variant goes out of stock' do+ let(:movement_quantity) { -stock_item.count_on_hand }++ it 'emits the variant.out_of_stock event' do+ expect { subject }.to emit_webhook_event('variant.out_of_stock')+ end+ end++ describe 'when the variant does not go out of stock' do+ let(:movement_quantity) { -stock_item.count_on_hand + 1 }++ it 'does not emit the variant.out_of_stock event' do+ expect { subject }.not_to emit_webhook_event('variant.out_of_stock')+ end+ end++ describe 'when the variant was out of stock before the update and after the update' do+ before do+ stock_item.set_count_on_hand(0)+ end++ let(:movement_quantity) { 0 }++ it 'does not emit the variant.out_of_stock event' do+ expect { subject }.not_to emit_webhook_event('variant.out_of_stock')+ end+ end+ end+end