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
Ability to configure which models should emit events
Damian Legawiece7822b1d95bf
diff --git a/core/app/models/concerns/spree/publishable.rb b/core/app/models/concerns/spree/publishable.rbindex c9ec44191a..fdef886e62 100644--- a/core/app/models/concerns/spree/publishable.rb+++ b/core/app/models/concerns/spree/publishable.rb@@ -3,35 +3,24 @@module Spree# Concern for models that publish events.#- # Include this concern in models that need to publish events- # to the Spree event system. It provides helper methods for- # publishing events with the model's serialized data.+ # This concern is included in Spree::Base, so all Spree models+ # automatically emit lifecycle events (create, update, destroy).#- # @example Basic usage- # class Spree::Order < Spree.base_class- # include Spree::Publishable+ # @example Disabling events for a specific model+ # class Spree::LogEntry < Spree.base_class+ # self.publish_events = false+ # end#+ # @example Publishing custom events+ # class Spree::Order < Spree.base_class# def complete!# # ... completion logic ...# publish_event('order.complete')# end# end#- # @example With automatic lifecycle events- # class Spree::Product < Spree.base_class- # include Spree::Publishable- #- # publishes_lifecycle_events- # end- # # This will automatically publish:- # # - 'product.create' after create- # # - 'product.update' after update- # # - 'product.destroy' after destroy- ## @example With custom serialization# class Spree::Order < Spree.base_class- # include Spree::Publishable- ## def event_payload# serializable_hash(# only: [:id, :number, :state, :total],@@ -44,6 +33,7 @@ module Spreeextend ActiveSupport::Concernincluded do+ class_attribute :publish_events, default: trueclass_attribute :lifecycle_events_enabled, default: falseclass_attribute :event_serialization_options, default: {}end@@ -72,18 +62,30 @@ module Spreeevents -= Array(options[:except]) if options[:except]if events.include?(:create)- after_commit :publish_create_event, on: :create+ after_commit :publish_create_event, on: :create, if: :should_publish_events?endif events.include?(:update)- after_commit :publish_update_event, on: :update+ after_commit :publish_update_event, on: :update, if: :should_publish_events?endif events.include?(:destroy)- after_commit :publish_destroy_event, on: :destroy+ before_destroy :capture_pre_destroy_payload, if: :should_publish_events?+ after_commit :publish_destroy_event, on: :destroy, if: :should_publish_events?endend+ # Disable lifecycle events for this model+ #+ # @example+ # class Spree::LogEntry < Spree.base_class+ # skip_lifecycle_events+ # end+ #+ def skip_lifecycle_events+ self.publish_events = false+ end+# Get the event name prefix for this model## @return [String] e.g., 'order' for Spree::Order@@ -138,6 +140,10 @@ module Spreeprivate+ def should_publish_events?+ self.class.publish_events && Spree::Events.enabled?+ end+def default_serialization_options{}end@@ -164,7 +170,6 @@ module Spreepublish_event("#{event_prefix}.destroy", @_pre_destroy_payload || event_payload)end- # Capture payload before destroy for the after_commit callbackdef capture_pre_destroy_payload@_pre_destroy_payload = event_payloadenddiff --git a/core/app/models/concerns/spree/user_methods.rb b/core/app/models/concerns/spree/user_methods.rbindex e1ec42c964..bf712b1d0d 100644--- a/core/app/models/concerns/spree/user_methods.rb+++ b/core/app/models/concerns/spree/user_methods.rb@@ -9,7 +9,12 @@ module Spreeinclude Spree::AdminUserMethodsinclude Spree::RansackableAttributesinclude Spree::MultiSearchable+ include Spree::Publishable+included do+ # Enable lifecycle events for user models+ publishes_lifecycle_events+# we need to have this callback before any dependent: :destroy associations# https://github.com/rails/rails/issues/3458before_validation :clone_billing_address, if: :use_billing?diff --git a/core/app/models/spree/base.rb b/core/app/models/spree/base.rbindex 0102cea743..a897b87111 100644--- a/core/app/models/spree/base.rb+++ b/core/app/models/spree/base.rb@@ -3,6 +3,7 @@ class Spree::Base < ApplicationRecordinclude Spree::RansackableAttributesinclude Spree::TranslatableResourceScopesinclude Spree::IntegrationsConcern+ include Spree::Publishableafter_initialize doif has_attribute?(:preferences) && !preferences.nil?diff --git a/core/app/models/spree/events.rb b/core/app/models/spree/events.rbindex 7864d3f763..668d4c0f04 100644--- a/core/app/models/spree/events.rb+++ b/core/app/models/spree/events.rb@@ -23,68 +23,6 @@ module Spree# Spree::Events.subscribe('*', GlobalEventLogger) # All events#module Events- # Standard Spree event names- #- # This provides a reference for the standard events that Spree publishes.- # Developers can use these constants or the string versions.- #- # @return [Hash<Symbol, String>]- STANDARD_EVENTS = {- # Product events- product_create: 'product.create',- product_update: 'product.update',- product_destroy: 'product.destroy',-- # Variant events- variant_create: 'variant.create',- variant_update: 'variant.update',- variant_destroy: 'variant.destroy',-- # Order lifecycle events- order_create: 'order.create',- order_update: 'order.update',- order_destroy: 'order.destroy',- order_complete: 'order.complete',- order_cancel: 'order.cancel',- order_resume: 'order.resume',- order_approve: 'order.approve',-- # Payment events- payment_create: 'payment.create',- payment_complete: 'payment.complete',- payment_void: 'payment.void',- payment_refund: 'payment.refund',-- # Shipment events- shipment_create: 'shipment.create',- shipment_ship: 'shipment.ship',- shipment_deliver: 'shipment.deliver',- shipment_cancel: 'shipment.cancel',-- # Inventory events- stock_item_update: 'stock_item.update',- stock_item_low_stock: 'stock_item.low_stock',- stock_item_out_of_stock: 'stock_item.out_of_stock',-- # User events- user_create: 'user.create',- user_update: 'user.update',- user_password_reset: 'user.password_reset',- user_signup: 'user.signup',-- # Checkout events- checkout_progress: 'checkout.progress',- checkout_complete: 'checkout.complete',-- # Refund events- refund_create: 'refund.create',-- # Return events- return_create: 'return.create',- return_approve: 'return.approve',- return_cancel: 'return.cancel'- }.freeze-class << self# Publish an event to all matching subscribers#@@ -206,14 +144,6 @@ module SpreeensureRequestStore.store[:spree_events_disabled] = previousend-- # Get standard event name by key- #- # @param key [Symbol] The event key- # @return [String, nil] The event name- def event_name(key)- STANDARD_EVENTS[key]- endendendenddiff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rbindex d55daa7229..b3b5222986 100644--- a/core/lib/spree/core.rb+++ b/core/lib/spree/core.rb@@ -289,6 +289,17 @@ module SpreeRails.application.config.spree.integrations = valueend+ # Models that automatically emit lifecycle events (create, update, destroy)+ # @example Adding a custom model to emit events+ # Spree.eventable_models << MyCustomModel+ def self.eventable_models+ Rails.application.config.spree.eventable_models+ end++ def self.eventable_models=(value)+ Rails.application.config.spree.eventable_models = value+ end+def self.analytics@analytics ||= AnalyticsConfig.newenddiff --git a/core/lib/spree/core/engine.rb b/core/lib/spree/core/engine.rbindex 53f58a5867..d764607261 100644--- a/core/lib/spree/core/engine.rb+++ b/core/lib/spree/core/engine.rb@@ -27,7 +27,8 @@ module Spree:metafields,:analytics_events,:analytics_event_handlers,- :integrations)+ :integrations,+ :eventable_models)SpreeCalculators = Struct.new(:shipping_methods, :tax_rates, :promotion_actions_create_adjustments, :promotion_actions_create_item_adjustments)PromoEnvironment = Struct.new(:rules, :actions)SpreeValidators = Struct.new(:addresses)@@ -268,6 +269,42 @@ module SpreeRails.application.config.spree.validators.addresses = [Spree::Addresses::PhoneValidator]++ # Models that automatically emit lifecycle events (create, update, destroy)+ # Developers can add/remove models from this list in their initializers+ Rails.application.config.spree.eventable_models = [+ Spree::Asset,+ Spree::CustomerReturn,+ Spree::Digital,+ Spree::DigitalLink,+ Spree::Export,+ Spree::GiftCard,+ Spree::GiftCardBatch,+ Spree::Import,+ Spree::Invitation,+ Spree::LineItem,+ Spree::NewsletterSubscriber,+ Spree::Order,+ Spree::Payment,+ Spree::Post,+ Spree::PostCategory,+ Spree::Promotion,+ Spree::Refund,+ Spree::ReturnAuthorization,+ Spree::Shipment,+ Spree::StockItem,+ Spree::StockMovement,+ Spree::StockTransfer,+ Spree::StoreCredit,+ Spree::Variant,+ Spree::WishedItem,+ Spree::Wishlist+ ]++ # Enable lifecycle events for configured models+ Rails.application.config.spree.eventable_models.each do |model|+ model.publishes_lifecycle_events if model.respond_to?(:publishes_lifecycle_events)+ endendinitializer 'spree.promo.register.promotions.actions' do |app|diff --git a/core/spec/models/concerns/spree/publishable_spec.rb b/core/spec/models/concerns/spree/publishable_spec.rbindex b8cf61cddf..cad1248deb 100644--- a/core/spec/models/concerns/spree/publishable_spec.rb+++ b/core/spec/models/concerns/spree/publishable_spec.rb@@ -141,9 +141,11 @@ RSpec.describe Spree::Publishable doexpect(received_event.name).to eq('test_product.create')end+ # Note: These specs use ApplicationRecord directly to test Publishable in isolation+ # since Spree::Base now has lifecycle events enabled by defaultcontext 'with only option' dolet(:limited_class) do- Class.new(Spree::Base) do+ Class.new(ApplicationRecord) doself.table_name = 'spree_products'include Spree::Publishable@@ -152,7 +154,6 @@ RSpec.describe Spree::Publishable doendit 'only registers specified callbacks' do- # Verify that only create callback is registeredexpect(limited_class._commit_callbacks.map(&:filter)).to include(:publish_create_event)expect(limited_class._commit_callbacks.map(&:filter)).not_to include(:publish_update_event)expect(limited_class._commit_callbacks.map(&:filter)).not_to include(:publish_destroy_event)@@ -161,7 +162,7 @@ RSpec.describe Spree::Publishable docontext 'with except option' dolet(:except_class) do- Class.new(Spree::Base) do+ Class.new(ApplicationRecord) doself.table_name = 'spree_products'include Spree::Publishable@@ -178,7 +179,7 @@ RSpec.describe Spree::Publishable docontext 'with serialize option' dolet(:serialize_class) do- Class.new(Spree::Base) do+ Class.new(ApplicationRecord) doself.table_name = 'spree_products'include Spree::Publishable@@ -194,6 +195,19 @@ RSpec.describe Spree::Publishable doexpect(serialize_class.event_serialization_options).to eq({ only: [:id] })endend++ context 'with skip_lifecycle_events' do+ let(:skipped_class) do+ Class.new(Spree::Base) do+ self.table_name = 'spree_products'+ skip_lifecycle_events+ end+ end++ it 'disables event publishing for the model' do+ expect(skipped_class.publish_events).to be false+ end+ endenddescribe '.event_prefix' dodiff --git a/core/spec/models/spree/events_spec.rb b/core/spec/models/spree/events_spec.rbindex 2f01dac59a..6a0314b4fa 100644--- a/core/spec/models/spree/events_spec.rb+++ b/core/spec/models/spree/events_spec.rb@@ -195,34 +195,6 @@ RSpec.describe Spree::Events doendend- describe '.event_name' do- it 'returns standard event names' do- expect(described_class.event_name(:order_complete)).to eq('order.complete')- expect(described_class.event_name(:product_create)).to eq('product.create')- end-- it 'returns nil for unknown keys' do- expect(described_class.event_name(:unknown_event)).to be_nil- end- end-- describe 'STANDARD_EVENTS' do- it 'defines order events' do- expect(described_class::STANDARD_EVENTS[:order_complete]).to eq('order.complete')- expect(described_class::STANDARD_EVENTS[:order_cancel]).to eq('order.cancel')- end-- it 'defines product events' do- expect(described_class::STANDARD_EVENTS[:product_create]).to eq('product.create')- expect(described_class::STANDARD_EVENTS[:product_update]).to eq('product.update')- end-- it 'defines payment events' do- expect(described_class::STANDARD_EVENTS[:payment_complete]).to eq('payment.complete')- expect(described_class::STANDARD_EVENTS[:payment_refund]).to eq('payment.refund')- end- end-describe 'multiple subscribers' doit 'notifies all matching subscribers' doreceived1 = []