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
Spree Event Subscribers
Damian Legawiec583b12e3691f
diff --git a/core/app/jobs/spree/events/subscriber_job.rb b/core/app/jobs/spree/events/subscriber_job.rbnew file mode 100644index 0000000000..415a1e58ef--- /dev/null+++ b/core/app/jobs/spree/events/subscriber_job.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++module Spree+ module Events+ # Job for executing subscribers asynchronously.+ #+ # When subscribers are configured to run async (the default),+ # this job is enqueued to handle the event processing in the background.+ #+ # @example Direct usage (typically called by the adapter)+ # Spree::Events::SubscriberJob.perform_later(+ # 'MySubscriber',+ # { name: 'order.complete', payload: {...}, ... }+ # )+ #+ class SubscriberJob < Spree::BaseJob+ queue_as Spree.queues.events++ # Retry configuration+ retry_on StandardError, wait: :polynomially_longer, attempts: 3++ discard_on ActiveJob::DeserializationError do |job, error|+ Rails.error.report(error, context: {+ subscriber: job.arguments.first,+ event: job.arguments.second+ })+ end++ # @param subscriber_class_name [String] The subscriber class name+ # @param event_hash [Hash] The event data as a hash+ def perform(subscriber_class_name, event_hash)+ subscriber_class = subscriber_class_name.constantize+ event = reconstruct_event(event_hash)++ if subscriber_class < Spree::Subscriber+ subscriber_class.new.call(event)+ elsif subscriber_class.respond_to?(:call)+ subscriber_class.call(event)+ else+ raise ArgumentError, "#{subscriber_class_name} is not a valid subscriber"+ end+ rescue NameError => e+ Rails.error.report(e, context: {+ subscriber: subscriber_class_name,+ event_name: event_hash[:name] || event_hash['name']+ })+ raise+ end++ private++ def reconstruct_event(event_hash)+ event_hash = event_hash.deep_symbolize_keys+ Spree::Event.new(+ name: event_hash[:name],+ payload: event_hash[:payload],+ metadata: event_hash[:metadata]+ )+ end+ end+ end+enddiff --git a/core/app/models/concerns/spree/publishable.rb b/core/app/models/concerns/spree/publishable.rbnew file mode 100644index 0000000000..c9ec44191a--- /dev/null+++ b/core/app/models/concerns/spree/publishable.rb@@ -0,0 +1,172 @@+# frozen_string_literal: true++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.+ #+ # @example Basic usage+ # class Spree::Order < Spree.base_class+ # include Spree::Publishable+ #+ # 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],+ # include: { line_items: { only: [:id, :quantity] } }+ # )+ # end+ # end+ #+ module Publishable+ extend ActiveSupport::Concern++ included do+ class_attribute :lifecycle_events_enabled, default: false+ class_attribute :event_serialization_options, default: {}+ end++ class_methods do+ # Enable automatic lifecycle event publishing+ #+ # @param options [Hash] Options for lifecycle events+ # @option options [Array<Symbol>] :only Limit to specific events (:create, :update, :destroy)+ # @option options [Array<Symbol>] :except Exclude specific events+ # @option options [Hash] :serialize Options passed to serializable_hash+ # @return [void]+ #+ # @example+ # publishes_lifecycle_events+ # publishes_lifecycle_events only: [:create, :destroy]+ # publishes_lifecycle_events except: [:update]+ # publishes_lifecycle_events serialize: { only: [:id, :name] }+ #+ def publishes_lifecycle_events(options = {})+ self.lifecycle_events_enabled = true+ self.event_serialization_options = options.fetch(:serialize, {})++ events = [:create, :update, :destroy]+ events &= Array(options[:only]) if options[:only]+ events -= Array(options[:except]) if options[:except]++ if events.include?(:create)+ after_commit :publish_create_event, on: :create+ end++ if events.include?(:update)+ after_commit :publish_update_event, on: :update+ end++ if events.include?(:destroy)+ after_commit :publish_destroy_event, on: :destroy+ end+ end++ # Get the event name prefix for this model+ #+ # @return [String] e.g., 'order' for Spree::Order+ def event_prefix+ @event_prefix ||= model_name.element+ end++ # Set a custom event prefix+ #+ # @param prefix [String]+ def event_prefix=(prefix)+ @event_prefix = prefix+ end+ end++ # Publish an event with this model's data+ #+ # @param event_name [String] The event name (e.g., 'order.complete')+ # @param payload [Hash, nil] Custom payload (defaults to event_payload)+ # @param metadata [Hash] Additional metadata+ # @return [Spree::Event] The published event+ #+ # @example+ # order.publish_event('order.complete')+ # order.publish_event('order.complete', { custom: 'data' })+ # order.publish_event('order.complete', metadata: { user_id: 1 })+ #+ def publish_event(event_name, payload = nil, metadata = {})+ return unless Spree::Events.enabled?++ payload ||= event_payload+ Spree::Events.publish(event_name, payload, metadata.merge(default_event_metadata))+ end++ # Get the payload for events+ #+ # Override this method to customize the data sent with events.+ # By default, uses ActiveModel::Serialization#serializable_hash.+ #+ # @return [Hash]+ def event_payload+ options = self.class.event_serialization_options.presence || default_serialization_options+ serializable_hash(options)+ end++ # Get the event prefix for this instance+ #+ # @return [String]+ def event_prefix+ self.class.event_prefix+ end++ private++ def default_serialization_options+ {}+ end++ def default_event_metadata+ {+ model_class: self.class.name,+ model_id: try(:id)+ }+ end++ def publish_create_event+ publish_event("#{event_prefix}.create")+ end++ def publish_update_event+ publish_event("#{event_prefix}.update")+ end++ def publish_destroy_event+ # For destroy, we need to capture the data before it's gone+ # The after_commit runs after the record is deleted, so we use+ # the previously captured payload+ publish_event("#{event_prefix}.destroy", @_pre_destroy_payload || event_payload)+ end++ # Capture payload before destroy for the after_commit callback+ def capture_pre_destroy_payload+ @_pre_destroy_payload = event_payload+ end+ end+enddiff --git a/core/app/models/spree/event.rb b/core/app/models/spree/event.rbnew file mode 100644index 0000000000..5655eeb21b--- /dev/null+++ b/core/app/models/spree/event.rb@@ -0,0 +1,126 @@+# frozen_string_literal: true++module Spree+ # Represents an event in the Spree event system.+ #+ # Events are immutable objects that carry information about something+ # that happened in the system. They contain:+ # - A name (e.g., 'order.complete', 'product.create')+ # - A payload (serialized data about the event)+ # - Metadata (contextual information like store_id, timestamps)+ #+ # @example Creating an event+ # event = Spree::Event.new(+ # name: 'order.complete',+ # payload: order.serializable_hash+ # )+ #+ # @example Accessing event data+ # event.name # => 'order.complete'+ # event.payload # => { 'id' => 1, 'number' => 'R123456' }+ # event.timestamp # => 2024-01-15 10:30:00 UTC+ #+ class Event+ attr_reader :name, :payload, :metadata, :timestamp++ # @param name [String] The event name (e.g., 'order.complete')+ # @param payload [Hash] The serialized event data+ # @param metadata [Hash] Additional contextual information+ def initialize(name:, payload:, metadata: {})+ @name = name.to_s.freeze+ @payload = (payload || {}).deep_stringify_keys.freeze+ @timestamp = Time.current.freeze+ @metadata = build_metadata(metadata).freeze+ end++ # Returns the resource type from the event name+ # @return [String] The resource type (e.g., 'order' from 'order.complete')+ def resource_type+ @resource_type ||= name.split('.').first+ end++ # Returns the action from the event name+ # @return [String] The action (e.g., 'complete' from 'order.complete')+ def action+ @action ||= name.split('.').drop(1).join('.')+ end++ # Checks if the event matches a pattern+ # Supports wildcards: 'order.*' matches 'order.complete', 'order.cancel'+ # @param pattern [String] The pattern to match against+ # @return [Boolean]+ def matches?(pattern)+ self.class.matches?(name, pattern)+ end++ # Class method to check if an event name matches a pattern+ # @param event_name [String] The event name+ # @param pattern [String] The pattern (supports * wildcard)+ # @return [Boolean]+ def self.matches?(event_name, pattern)+ return true if pattern == '*'++ if pattern.include?('*')+ regex = Regexp.new("^#{Regexp.escape(pattern).gsub('\*', '.*')}$")+ event_name.match?(regex)+ else+ event_name == pattern+ end+ end++ # Convert to hash representation+ # @return [Hash]+ def to_h+ {+ name: name,+ payload: payload,+ metadata: metadata,+ timestamp: timestamp+ }+ end++ def inspect+ "#<Spree::Event name=#{name.inspect} timestamp=#{timestamp.iso8601}>"+ end++ private++ def build_metadata(custom_metadata)+ base_metadata = {+ 'event_id' => SecureRandom.uuid,+ 'timestamp' => @timestamp.iso8601,+ 'spree_version' => Spree.version+ }++ # Add store context if available+ if defined?(Spree::Store) && Spree::Store.respond_to?(:current)+ current_store = Spree::Store.current+ base_metadata['store_id'] = current_store&.id&.to_s+ end++ # Add request context if available (via CurrentAttributes or similar)+ if defined?(Current) && Current.respond_to?(:request_id)+ base_metadata['request_id'] = Current.request_id+ end++ # Merge custom metadata and ensure IDs are strings for JSON consistency+ merged = base_metadata.merge(stringify_metadata(custom_metadata))+ merged+ end++ def stringify_metadata(hash)+ hash.deep_stringify_keys.transform_values do |value|+ case value+ when Integer, BigDecimal+ value.to_s+ when Hash+ stringify_metadata(value)+ when Array+ value.map { |v| v.is_a?(Hash) ? stringify_metadata(v) : v }+ else+ value+ end+ end+ end+ end+enddiff --git a/core/app/models/spree/events.rb b/core/app/models/spree/events.rbnew file mode 100644index 0000000000..7864d3f763--- /dev/null+++ b/core/app/models/spree/events.rb@@ -0,0 +1,219 @@+# frozen_string_literal: true++module Spree+ # Main entry point for the Spree event system.+ #+ # This module provides a clean API for publishing events and subscribing+ # to them. It abstracts the underlying implementation (ActiveSupport::Notifications)+ # allowing for future changes without affecting subscriber code.+ #+ # @example Publishing an event+ # Spree::Events.publish('order.complete', order.serializable_hash)+ #+ # @example Subscribing with a class+ # Spree::Events.subscribe('order.complete', OrderCompleteHandler)+ #+ # @example Subscribing with a block+ # Spree::Events.subscribe('order.complete') do |event|+ # puts "Order completed: #{event.payload['number']}"+ # end+ #+ # @example Pattern matching+ # Spree::Events.subscribe('order.*', OrderAuditLogger) # All order events+ # 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+ #+ # @param name [String] The event name (e.g., 'order.complete')+ # @param payload [Hash] The event payload (should be serializable)+ # @param metadata [Hash] Additional metadata for the event+ # @return [Spree::Event] The published event+ #+ # @example+ # Spree::Events.publish('product.create', product.serializable_hash)+ # Spree::Events.publish('order.complete', order.serializable_hash, { user_id: current_user.id })+ #+ def publish(name, payload = {}, metadata = {})+ adapter.publish(name, payload, metadata)+ end++ # Subscribe to an event pattern+ #+ # @param pattern [String] Event pattern (supports wildcards like 'order.*' or '*')+ # @param subscriber [Class, Proc, nil] The subscriber class or callable+ # @param options [Hash] Subscription options+ # @option options [Boolean] :async (true) Whether to run async via ActiveJob+ # @yield [event] Block to execute when event occurs (alternative to subscriber param)+ # @yieldparam event [Spree::Event] The event object+ # @return [void]+ #+ # @example With a subscriber class+ # Spree::Events.subscribe('order.complete', SendConfirmationEmail)+ #+ # @example With a block+ # Spree::Events.subscribe('order.complete') { |event| puts event.name }+ #+ # @example With pattern matching+ # Spree::Events.subscribe('order.*', OrderAuditLogger)+ #+ # @example Synchronous execution+ # Spree::Events.subscribe('order.complete', MyHandler, async: false)+ #+ def subscribe(pattern, subscriber = nil, options = {}, &block)+ subscriber = block if block_given?+ raise ArgumentError, 'Must provide a subscriber class, callable, or block' unless subscriber++ adapter.subscribe(pattern, subscriber, options)+ end++ # Unsubscribe from an event pattern+ #+ # @param pattern [String] Event pattern+ # @param subscriber [Class, Proc] The subscriber to remove+ # @return [Boolean] true if removed, false if not found+ def unsubscribe(pattern, subscriber)+ adapter.unsubscribe(pattern, subscriber)+ end++ # Get the event registry+ #+ # @return [Spree::Events::Registry]+ def registry+ @registry ||= Registry.new+ end++ # Get the adapter instance+ #+ # @return [Spree::Events::Adapters::ActiveSupportNotifications]+ def adapter+ @adapter ||= Adapters::ActiveSupportNotifications.new(registry)+ end++ # Activate the event system (called during Rails initialization)+ def activate!+ adapter.activate!+ end++ # Reset the event system (useful for testing)+ def reset!+ adapter.deactivate! if @adapter+ @registry = nil+ @adapter = nil+ end++ # List all registered subscriber patterns+ #+ # @return [Array<String>]+ def patterns+ registry.patterns+ end++ # List all subscriptions+ #+ # @return [Array<Spree::Events::Registry::Subscription>]+ def subscriptions+ registry.all_subscriptions+ end++ # Check if events are enabled+ #+ # Events can be temporarily disabled using Spree::Events.disable { ... }+ #+ # @return [Boolean]+ def enabled?+ !RequestStore.store[:spree_events_disabled]+ end++ # Temporarily disable events within a block+ #+ # @yield Block during which events are disabled+ # @return [Object] Return value of the block+ #+ # @example+ # Spree::Events.disable do+ # # Events published here won't trigger subscribers+ # order.complete!+ # end+ #+ def disable+ previous = RequestStore.store[:spree_events_disabled]+ RequestStore.store[:spree_events_disabled] = true+ yield+ ensure+ RequestStore.store[:spree_events_disabled] = previous+ end++ # 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]+ end+ end+ end+enddiff --git a/core/app/models/spree/events/adapters/active_support_notifications.rb b/core/app/models/spree/events/adapters/active_support_notifications.rbnew file mode 100644index 0000000000..f5afbc9581--- /dev/null+++ b/core/app/models/spree/events/adapters/active_support_notifications.rb@@ -0,0 +1,167 @@+# frozen_string_literal: true++module Spree+ module Events+ module Adapters+ # Adapter for ActiveSupport::Notifications backend.+ #+ # This adapter wraps Rails' built-in notification system to provide+ # the Spree event infrastructure. It can be swapped out for other+ # implementations (e.g., Redis pub/sub, Kafka) without changing+ # the subscriber API.+ #+ # @example Publishing an event+ # adapter = ActiveSupportNotifications.new(registry)+ # adapter.publish('order.complete', { id: 1 })+ #+ class ActiveSupportNotifications+ NAMESPACE = 'spree'++ attr_reader :registry++ def initialize(registry)+ @registry = registry+ @as_subscription = nil+ @mutex = Mutex.new+ end++ # Publish an event to all matching subscribers+ #+ # @param event_name [String] The event name+ # @param payload [Hash] The event payload+ # @param metadata [Hash] Additional metadata+ # @return [Spree::Event] The published event+ def publish(event_name, payload, metadata = {})+ event = Spree::Event.new(+ name: event_name,+ payload: payload,+ metadata: metadata+ )++ instrument_name = namespaced_event(event_name)++ ::ActiveSupport::Notifications.instrument(instrument_name, event: event) do+ # The block is intentionally empty - we use the instrument+ # to trigger subscribers, not to wrap code execution+ end++ event+ end++ # Subscribe to an event pattern+ #+ # This method registers a subscriber in the registry.+ # The actual AS::N subscription is created once via activate!+ #+ # @param pattern [String] Event pattern (supports wildcards)+ # @param subscriber [Class, Proc] The subscriber+ # @param options [Hash] Subscription options+ def subscribe(pattern, subscriber, options = {})+ # Register in our registry+ registry.register(pattern, subscriber, options)++ # Ensure the global AS::N subscription exists+ ensure_as_subscription+ end++ # Unsubscribe from an event pattern+ #+ # @param pattern [String] Event pattern+ # @param subscriber [Class, Proc] The subscriber to remove+ def unsubscribe(pattern, subscriber)+ registry.unregister(pattern, subscriber)+ end++ # Activate all registered subscriptions+ #+ # This is called during Rails initialization to set up+ # the single AS::N subscription that catches all Spree events.+ def activate!+ ensure_as_subscription+ end++ # Deactivate all AS::N subscriptions+ def deactivate!+ @mutex.synchronize do+ if @as_subscription+ ::ActiveSupport::Notifications.unsubscribe(@as_subscription)+ @as_subscription = nil+ end+ end+ end++ private++ def namespaced_event(event_name)+ "#{event_name}.#{NAMESPACE}"+ end++ # Create a single AS::N subscription that catches all Spree events+ def ensure_as_subscription+ @mutex.synchronize do+ return if @as_subscription++ # Match all events ending with .spree+ @as_subscription = ::ActiveSupport::Notifications.subscribe(/\.#{NAMESPACE}$/) do |_name, _start, _finish, _id, as_payload|+ # Extract our event from the AS::N payload+ event = as_payload[:event]+ next unless event++ # Find and invoke all matching subscribers+ invoke_subscribers(event)+ end+ end+ end++ def invoke_subscribers(event)+ # Check if events are enabled (can be disabled via Spree::Events.disable)+ return unless Spree::Events.enabled?++ subscriptions = registry.subscriptions_for(event.name)++ subscriptions.each do |subscription|+ invoke_subscriber(subscription.subscriber, event, subscription.options)+ rescue StandardError => e+ handle_subscriber_error(e, event, subscription)+ end+ end++ def invoke_subscriber(subscriber, event, options)+ async = options.fetch(:async, true)++ if subscriber.is_a?(Proc)+ # Block subscribers run synchronously+ subscriber.call(event)+ elsif subscriber.respond_to?(:call)+ # Callable objects (including subscriber instances)+ if async && defined?(Spree::Events::SubscriberJob)+ Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)+ else+ subscriber.call(event)+ end+ elsif subscriber.is_a?(Class) && subscriber < Spree::Subscriber+ # Subscriber classes+ if async && defined?(Spree::Events::SubscriberJob)+ Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)+ else+ subscriber.new.call(event)+ end+ else+ raise ArgumentError, "Invalid subscriber: #{subscriber.inspect}. Must be a Proc, callable, or Spree::Subscriber subclass."+ end+ end++ def handle_subscriber_error(error, event, subscription)+ Rails.error.report(error, context: {+ event_name: event.name,+ subscriber: subscription.subscriber.to_s,+ event_id: event.metadata['event_id']+ })++ # Re-raise in development/test for visibility+ raise if Rails.env.development? || Rails.env.test?+ end+ end+ end+ end+enddiff --git a/core/app/models/spree/events/registry.rb b/core/app/models/spree/events/registry.rbnew file mode 100644index 0000000000..1bab04fbba--- /dev/null+++ b/core/app/models/spree/events/registry.rb@@ -0,0 +1,110 @@+# frozen_string_literal: true++module Spree+ module Events+ # Registry for managing event subscribers.+ #+ # The registry keeps track of all registered subscribers and their+ # event subscriptions. It supports pattern matching for event names.+ #+ # @example Registering a subscriber+ # registry = Spree::Events::Registry.new+ # registry.register('order.complete', MySubscriber)+ #+ # @example Finding subscribers for an event+ # registry.subscribers_for('order.complete')+ # # => [MySubscriber, AnotherSubscriber]+ #+ class Registry+ Subscription = Struct.new(:pattern, :subscriber, :options, keyword_init: true)++ def initialize+ @subscriptions = []+ @mutex = Mutex.new+ end++ # Register a subscriber for an event pattern+ #+ # @param pattern [String] Event pattern (supports wildcards like 'order.*')+ # @param subscriber [Class, Proc] The subscriber class or callable+ # @param options [Hash] Additional options for the subscription+ # @return [Subscription] The created subscription+ def register(pattern, subscriber, options = {})+ subscription = Subscription.new(+ pattern: pattern.to_s,+ subscriber: subscriber,+ options: options+ )++ @mutex.synchronize do+ @subscriptions << subscription+ end++ subscription+ end++ # Unregister a subscriber+ #+ # @param pattern [String] Event pattern+ # @param subscriber [Class, Proc] The subscriber to remove+ # @return [Boolean] true if removed, false if not found+ def unregister(pattern, subscriber)+ @mutex.synchronize do+ original_size = @subscriptions.size+ @subscriptions.reject! do |sub|+ sub.pattern == pattern.to_s && sub.subscriber == subscriber+ end+ @subscriptions.size < original_size+ end+ end++ # Find all subscribers that match an event name+ #+ # @param event_name [String] The event name to match+ # @return [Array<Subscription>] Matching subscriptions+ def subscriptions_for(event_name)+ @mutex.synchronize do+ @subscriptions.select do |subscription|+ Spree::Event.matches?(event_name, subscription.pattern)+ end+ end+ end++ # Get all registered subscriptions+ #+ # @return [Array<Subscription>]+ def all_subscriptions+ @mutex.synchronize { @subscriptions.dup }+ end++ # Get all unique patterns+ #+ # @return [Array<String>]+ def patterns+ @mutex.synchronize { @subscriptions.map(&:pattern).uniq }+ end++ # Clear all subscriptions+ def clear!+ @mutex.synchronize { @subscriptions.clear }+ end++ # Number of subscriptions+ #+ # @return [Integer]+ def size+ @mutex.synchronize { @subscriptions.size }+ end++ # Check if a pattern is registered+ #+ # @param pattern [String]+ # @return [Boolean]+ def registered?(pattern)+ @mutex.synchronize do+ @subscriptions.any? { |sub| sub.pattern == pattern.to_s }+ end+ end+ end+ end+enddiff --git a/core/app/models/spree/subscriber.rb b/core/app/models/spree/subscriber.rbnew file mode 100644index 0000000000..6ca9a9087d--- /dev/null+++ b/core/app/models/spree/subscriber.rb@@ -0,0 +1,209 @@+# frozen_string_literal: true++module Spree+ # Base class for event subscribers.+ #+ # Subscribers handle events published through the Spree event system.+ # They provide a clean DSL for declaring which events to subscribe to+ # and are automatically registered during Rails initialization.+ #+ # @example Basic subscriber+ # class OrderCompletedNotifier < Spree::Subscriber+ # subscribes_to 'order.complete'+ #+ # def call(event)+ # order_id = event.payload['id']+ # Spree::OrderMailer.confirm_email(order_id).deliver_later+ # end+ # end+ #+ # @example Multi-event subscriber+ # class OrderAuditLogger < Spree::Subscriber+ # subscribes_to 'order.complete', 'order.cancel', 'order.resume'+ #+ # def call(event)+ # AuditLog.create!(+ # event_name: event.name,+ # payload: event.payload,+ # occurred_at: event.timestamp+ # )+ # end+ # end+ #+ # @example Pattern matching subscriber+ # class OrderEventLogger < Spree::Subscriber+ # subscribes_to 'order.*'+ #+ # def call(event)+ # Rails.logger.info("Order event: #{event.name}")+ # end+ # end+ #+ # @example Subscriber with method routing+ # class PaymentSubscriber < Spree::Subscriber+ # subscribes_to 'payment.complete', 'payment.void', 'payment.refund'+ #+ # on 'payment.complete', :handle_complete+ # on 'payment.void', :handle_void+ # on 'payment.refund', :handle_refund+ #+ # private+ #+ # def handle_complete(event)+ # # Handle payment completion+ # end+ #+ # def handle_void(event)+ # # Handle payment void+ # end+ #+ # def handle_refund(event)+ # # Handle payment refund+ # end+ # end+ #+ # @example Synchronous subscriber (runs immediately, not via ActiveJob)+ # class CriticalOrderHandler < Spree::Subscriber+ # subscribes_to 'order.complete', async: false+ #+ # def call(event)+ # # This runs synchronously+ # end+ # end+ #+ class Subscriber+ class << self+ # DSL method to declare which events this subscriber handles+ #+ # @param patterns [Array<String>] Event patterns to subscribe to+ # @param options [Hash] Subscription options+ # @option options [Boolean] :async (true) Whether to run async via ActiveJob+ # @return [void]+ #+ # @example+ # subscribes_to 'order.complete'+ # subscribes_to 'order.complete', 'order.cancel'+ # subscribes_to 'order.*'+ # subscribes_to 'order.complete', async: false+ #+ def subscribes_to(*patterns, **options)+ @subscription_patterns ||= []+ @subscription_options = options++ patterns.flatten.each do |pattern|+ @subscription_patterns << pattern.to_s+ end+ end++ # DSL method to route specific events to specific methods+ #+ # @param pattern [String] Event pattern+ # @param method_name [Symbol] Method to call for this event+ # @return [void]+ #+ # @example+ # on 'payment.complete', :handle_complete+ # on 'payment.void', :handle_void+ #+ def on(pattern, method_name)+ @event_handlers ||= {}+ @event_handlers[pattern.to_s] = method_name+ end++ # Get all subscription patterns for this subscriber+ #+ # @return [Array<String>]+ def subscription_patterns+ @subscription_patterns ||= []+ end++ # Get subscription options+ #+ # @return [Hash]+ def subscription_options+ @subscription_options ||= {}+ end++ # Get event handlers mapping+ #+ # @return [Hash<String, Symbol>]+ def event_handlers+ @event_handlers ||= {}+ end++ # Register this subscriber with the event system+ #+ # Called automatically during Rails initialization for subscribers+ # in the app/subscribers directory.+ #+ # @return [void]+ def register!+ return if subscription_patterns.empty?++ subscription_patterns.each do |pattern|+ Spree::Events.subscribe(pattern, self, subscription_options)+ end+ end++ # Unregister this subscriber from the event system+ #+ # @return [void]+ def unregister!+ subscription_patterns.each do |pattern|+ Spree::Events.unsubscribe(pattern, self)+ end+ end++ # Class-level call method for when the class itself is used as subscriber+ #+ # @param event [Spree::Event]+ def call(event)+ new.call(event)+ end+ end++ # Handle an event+ #+ # Override this method in subclasses to handle events.+ # If you've defined event handlers with `on`, this method+ # will route to the appropriate handler automatically.+ #+ # @param event [Spree::Event] The event to handle+ # @return [void]+ def call(event)+ handler = find_handler(event)++ if handler+ send(handler, event)+ else+ # Default behavior - subclasses should override+ handle(event)+ end+ end++ # Default event handler+ #+ # Override this in subclasses if not using the `on` DSL+ #+ # @param event [Spree::Event]+ def handle(event)+ # Override in subclass+ end++ private++ def find_handler(event)+ handlers = self.class.event_handlers++ # Try exact match first+ return handlers[event.name] if handlers.key?(event.name)++ # Try pattern matching+ handlers.each do |pattern, method_name|+ return method_name if event.matches?(pattern)+ end++ nil+ end+ end+enddiff --git a/core/lib/generators/spree/install/templates/config/initializers/spree.rb b/core/lib/generators/spree/install/templates/config/initializers/spree.rbindex 36a08f6959..728c9ca9b2 100644--- a/core/lib/generators/spree/install/templates/config/initializers/spree.rb+++ b/core/lib/generators/spree/install/templates/config/initializers/spree.rb@@ -20,6 +20,7 @@ end# Background job queue names# Spree.queues.default = :default+# Spree.queues.events = :default # Event subscribers (Spree::Events::SubscriberJob)# Spree.queues.variants = :default# Spree.queues.stock_location_stock_items = :default# Spree.queues.coupon_codes = :defaultdiff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rbindex 0bb8ac12e7..d55daa7229 100644--- a/core/lib/spree/core.rb+++ b/core/lib/spree/core.rb@@ -97,6 +97,7 @@ module Spreedef self.queues@@queues ||= OpenStruct.new(default: :default,+ events: :default,exports: :default,images: :default,imports: :default,diff --git a/core/lib/spree/core/engine.rb b/core/lib/spree/core/engine.rbindex 560001da9c..53f58a5867 100644--- a/core/lib/spree/core/engine.rb+++ b/core/lib/spree/core/engine.rb@@ -35,6 +35,9 @@ module Spreeisolate_namespace Spreeengine_name 'spree'+ # Add app/subscribers to autoload paths+ config.paths.add 'app/subscribers', eager_load: true+rake_tasks doload File.join(root, 'lib', 'tasks', 'exchanges.rake')end@@ -315,6 +318,16 @@ module SpreeDir.glob(File.join(File.dirname(__FILE__), '../../../app/**/*_decorator*.rb')) do |c|Rails.configuration.cache_classes ? require(c) : load(c)end++ # Reset and re-register event subscribers on code reload+ Spree::Events.reset!++ # Auto-register all Spree::Subscriber subclasses+ # Subscribers are auto-loaded from app/subscribers directories+ Spree::Subscriber.descendants.each(&:register!)++ # Activate the event system+ Spree::Events.activate!endendenddiff --git a/core/spec/models/concerns/spree/publishable_spec.rb b/core/spec/models/concerns/spree/publishable_spec.rbnew file mode 100644index 0000000000..b8cf61cddf--- /dev/null+++ b/core/spec/models/concerns/spree/publishable_spec.rb@@ -0,0 +1,211 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Publishable do+ before do+ Spree::Events.reset!+ end++ after do+ Spree::Events.reset!+ end++ let(:publishable_class) do+ Class.new(Spree::Base) do+ self.table_name = 'spree_products'++ include Spree::Publishable++ # Simulate ActiveModel::Serialization+ def serializable_hash(options = {})+ { 'id' => id, 'name' => name }.merge(options[:extra] || {})+ end+ end+ end++ let(:instance) { publishable_class.new(id: 1, name: 'Test Product') }++ describe '#publish_event' do+ it 'publishes an event with the model payload' do+ received_event = nil+ Spree::Events.subscribe('product.custom', async: false) { |e| received_event = e }+ Spree::Events.activate!++ instance.publish_event('product.custom')++ expect(received_event).to be_present+ expect(received_event.name).to eq('product.custom')+ expect(received_event.payload['id']).to eq(1)+ expect(received_event.payload['name']).to eq('Test Product')+ end++ it 'allows custom payload' do+ received_event = nil+ Spree::Events.subscribe('product.custom', async: false) { |e| received_event = e }+ Spree::Events.activate!++ instance.publish_event('product.custom', { custom: 'data' })++ expect(received_event.payload).to eq({ 'custom' => 'data' })+ end++ it 'includes model metadata with IDs as strings' do+ received_event = nil+ Spree::Events.subscribe('product.custom', async: false) { |e| received_event = e }+ Spree::Events.activate!++ instance.publish_event('product.custom')++ expect(received_event.metadata['model_id']).to eq('1')+ end++ it 'does not publish when events are disabled' do+ received = false+ Spree::Events.subscribe('product.custom', async: false) { received = true }+ Spree::Events.activate!++ Spree::Events.disable do+ instance.publish_event('product.custom')+ end++ expect(received).to be false+ end+ end++ describe '#event_payload' do+ it 'returns serializable_hash by default' do+ expect(instance.event_payload).to eq({ 'id' => 1, 'name' => 'Test Product' })+ end++ context 'with custom serialization options' do+ let(:custom_class) do+ Class.new(Spree::Base) do+ self.table_name = 'spree_products'++ include Spree::Publishable+ self.event_serialization_options = { extra: { 'custom' => 'field' } }++ def serializable_hash(options = {})+ { 'id' => id }.merge(options[:extra] || {})+ end+ end+ end++ it 'uses the custom serialization options' do+ instance = custom_class.new(id: 1)+ expect(instance.event_payload).to eq({ 'id' => 1, 'custom' => 'field' })+ end+ end+ end++ describe '#event_prefix' do+ it 'returns the model name element' do+ stub_const('Spree::Product', publishable_class)+ instance = Spree::Product.new++ expect(instance.event_prefix).to eq('product')+ end+ end++ describe '.publishes_lifecycle_events' do+ let(:lifecycle_class) do+ Class.new(Spree::Base) do+ self.table_name = 'spree_products'++ include Spree::Publishable+ publishes_lifecycle_events++ def serializable_hash(_options = {})+ { 'id' => id, 'name' => name }+ end+ end+ end++ before do+ stub_const('Spree::TestProduct', lifecycle_class)+ end++ it 'enables lifecycle events' do+ expect(lifecycle_class.lifecycle_events_enabled).to be true+ end++ it 'publishes create event after commit', skip: 'Requires database transaction' do+ received_event = nil+ Spree::Events.subscribe('test_product.create', async: false) { |e| received_event = e }+ Spree::Events.activate!++ product = lifecycle_class.create!(name: 'New Product')++ expect(received_event).to be_present+ expect(received_event.name).to eq('test_product.create')+ end++ context 'with only option' do+ let(:limited_class) do+ Class.new(Spree::Base) do+ self.table_name = 'spree_products'++ include Spree::Publishable+ publishes_lifecycle_events only: [:create]+ end+ end++ it 'only registers specified callbacks' do+ # Verify that only create callback is registered+ expect(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)+ end+ end++ context 'with except option' do+ let(:except_class) do+ Class.new(Spree::Base) do+ self.table_name = 'spree_products'++ include Spree::Publishable+ publishes_lifecycle_events except: [:update]+ end+ end++ it 'excludes specified callbacks' do+ expect(except_class._commit_callbacks.map(&:filter)).to include(:publish_create_event)+ expect(except_class._commit_callbacks.map(&:filter)).not_to include(:publish_update_event)+ expect(except_class._commit_callbacks.map(&:filter)).to include(:publish_destroy_event)+ end+ end++ context 'with serialize option' do+ let(:serialize_class) do+ Class.new(Spree::Base) do+ self.table_name = 'spree_products'++ include Spree::Publishable+ publishes_lifecycle_events serialize: { only: [:id] }++ def serializable_hash(options = {})+ options[:only] ? { 'id' => id } : { 'id' => id, 'name' => name }+ end+ end+ end++ it 'uses custom serialization options' do+ expect(serialize_class.event_serialization_options).to eq({ only: [:id] })+ end+ end+ end++ describe '.event_prefix' do+ it 'derives from model name' do+ stub_const('Spree::OrderLineItem', publishable_class)+ expect(Spree::OrderLineItem.event_prefix).to eq('order_line_item')+ end++ it 'can be customized' do+ stub_const('Spree::CustomModel', publishable_class)+ Spree::CustomModel.event_prefix = 'custom'+ expect(Spree::CustomModel.event_prefix).to eq('custom')+ end+ end+enddiff --git a/core/spec/models/spree/event_spec.rb b/core/spec/models/spree/event_spec.rbnew file mode 100644index 0000000000..b0e5aac99c--- /dev/null+++ b/core/spec/models/spree/event_spec.rb@@ -0,0 +1,152 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Event do+ describe '#initialize' do+ it 'creates an event with name and payload' do+ event = described_class.new(+ name: 'order.complete',+ payload: { id: 1, number: 'R123' }+ )++ expect(event.name).to eq('order.complete')+ expect(event.payload).to eq({ 'id' => 1, 'number' => 'R123' })+ end++ it 'freezes the name, payload, and metadata' do+ event = described_class.new(+ name: 'order.complete',+ payload: { id: 1 }+ )++ expect(event.name).to be_frozen+ expect(event.payload).to be_frozen+ expect(event.metadata).to be_frozen+ end++ it 'sets a timestamp' do+ event = described_class.new(name: 'test', payload: {})+ expect(event.timestamp).to be_within(1.second).of(Time.current)+ end++ it 'generates an event_id in metadata' do+ event = described_class.new(name: 'test', payload: {})+ expect(event.metadata['event_id']).to be_present+ expect(event.metadata['event_id']).to match(/\A[0-9a-f-]{36}\z/)+ end++ it 'includes spree_version in metadata' do+ event = described_class.new(name: 'test', payload: {})+ expect(event.metadata['spree_version']).to eq(Spree.version)+ end++ it 'accepts custom metadata' do+ event = described_class.new(+ name: 'test',+ payload: {},+ metadata: { custom_key: 'custom_value' }+ )++ expect(event.metadata['custom_key']).to eq('custom_value')+ end++ it 'deep stringifies payload keys' do+ event = described_class.new(+ name: 'test',+ payload: { nested: { deep_key: 'value' } }+ )++ expect(event.payload).to eq({ 'nested' => { 'deep_key' => 'value' } })+ end+ end++ describe '#resource_type' do+ it 'extracts the resource type from the event name' do+ event = described_class.new(name: 'order.complete', payload: {})+ expect(event.resource_type).to eq('order')+ end++ it 'handles nested event names' do+ event = described_class.new(name: 'stock_item.low_stock', payload: {})+ expect(event.resource_type).to eq('stock_item')+ end+ end++ describe '#action' do+ it 'extracts the action from the event name' do+ event = described_class.new(name: 'order.complete', payload: {})+ expect(event.action).to eq('complete')+ end++ it 'handles multi-part actions' do+ event = described_class.new(name: 'stock_item.low_stock', payload: {})+ expect(event.action).to eq('low_stock')+ end+ end++ describe '#matches?' do+ let(:event) { described_class.new(name: 'order.complete', payload: {}) }++ it 'matches exact event names' do+ expect(event.matches?('order.complete')).to be true+ expect(event.matches?('order.cancel')).to be false+ end++ it 'matches wildcard patterns' do+ expect(event.matches?('order.*')).to be true+ expect(event.matches?('product.*')).to be false+ end++ it 'matches global wildcard' do+ expect(event.matches?('*')).to be true+ end+ end++ describe '.matches?' do+ it 'matches exact names' do+ expect(described_class.matches?('order.complete', 'order.complete')).to be true+ expect(described_class.matches?('order.complete', 'order.cancel')).to be false+ end++ it 'matches wildcard patterns' do+ expect(described_class.matches?('order.complete', 'order.*')).to be true+ expect(described_class.matches?('order.cancel', 'order.*')).to be true+ expect(described_class.matches?('product.create', 'order.*')).to be false+ end++ it 'matches global wildcard' do+ expect(described_class.matches?('order.complete', '*')).to be true+ expect(described_class.matches?('anything.here', '*')).to be true+ end++ it 'handles complex patterns' do+ expect(described_class.matches?('order.line_item.update', 'order.line_item.*')).to be true+ expect(described_class.matches?('order.line_item.update', 'order.*')).to be true+ end+ end++ describe '#to_h' do+ it 'returns a hash representation with IDs as strings' do+ event = described_class.new(+ name: 'order.complete',+ payload: { id: 1 },+ metadata: { user_id: 5 }+ )++ hash = event.to_h++ expect(hash[:name]).to eq('order.complete')+ expect(hash[:payload]).to eq({ 'id' => 1 })+ expect(hash[:metadata]['user_id']).to eq('5')+ expect(hash[:timestamp]).to eq(event.timestamp)+ end+ end++ describe '#inspect' do+ it 'returns a readable string representation' do+ event = described_class.new(name: 'order.complete', payload: {})+ expect(event.inspect).to match(/Spree::Event name="order.complete"/)+ end+ end+enddiff --git a/core/spec/models/spree/events/registry_spec.rb b/core/spec/models/spree/events/registry_spec.rbnew file mode 100644index 0000000000..7258369b1f--- /dev/null+++ b/core/spec/models/spree/events/registry_spec.rb@@ -0,0 +1,169 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Events::Registry do+ let(:registry) { described_class.new }+ let(:subscriber_class) { Class.new }+ let(:another_subscriber) { Class.new }++ describe '#register' do+ it 'registers a subscriber for a pattern' do+ registry.register('order.complete', subscriber_class)++ expect(registry.size).to eq(1)+ expect(registry.registered?('order.complete')).to be true+ end++ it 'allows multiple subscribers for the same pattern' do+ registry.register('order.complete', subscriber_class)+ registry.register('order.complete', another_subscriber)++ expect(registry.size).to eq(2)+ end++ it 'stores subscription options' do+ registry.register('order.complete', subscriber_class, async: false)++ subscription = registry.subscriptions_for('order.complete').first+ expect(subscription.options[:async]).to be false+ end++ it 'returns the subscription' do+ subscription = registry.register('order.complete', subscriber_class)++ expect(subscription).to be_a(Spree::Events::Registry::Subscription)+ expect(subscription.pattern).to eq('order.complete')+ expect(subscription.subscriber).to eq(subscriber_class)+ end+ end++ describe '#unregister' do+ before do+ registry.register('order.complete', subscriber_class)+ registry.register('order.complete', another_subscriber)+ end++ it 'removes a specific subscriber' do+ result = registry.unregister('order.complete', subscriber_class)++ expect(result).to be true+ expect(registry.size).to eq(1)+ expect(registry.subscriptions_for('order.complete').map(&:subscriber)).not_to include(subscriber_class)+ end++ it 'returns false when subscriber not found' do+ result = registry.unregister('order.cancel', subscriber_class)++ expect(result).to be false+ end++ it 'keeps other subscribers intact' do+ registry.unregister('order.complete', subscriber_class)++ expect(registry.subscriptions_for('order.complete').map(&:subscriber)).to include(another_subscriber)+ end+ end++ describe '#subscriptions_for' do+ before do+ registry.register('order.complete', subscriber_class)+ registry.register('order.*', another_subscriber)+ end++ it 'returns subscriptions for exact match' do+ subscriptions = registry.subscriptions_for('order.complete')++ expect(subscriptions.size).to eq(2)+ end++ it 'returns subscriptions matching wildcard patterns' do+ subscriptions = registry.subscriptions_for('order.cancel')++ expect(subscriptions.size).to eq(1)+ expect(subscriptions.first.subscriber).to eq(another_subscriber)+ end++ it 'returns empty array when no matches' do+ subscriptions = registry.subscriptions_for('product.create')++ expect(subscriptions).to be_empty+ end++ context 'with global wildcard' do+ before { registry.register('*', Class.new) }++ it 'matches all events' do+ expect(registry.subscriptions_for('order.complete').size).to eq(3)+ expect(registry.subscriptions_for('product.create').size).to eq(1)+ end+ end+ end++ describe '#all_subscriptions' do+ it 'returns all registered subscriptions' do+ registry.register('order.complete', subscriber_class)+ registry.register('order.*', another_subscriber)++ subscriptions = registry.all_subscriptions++ expect(subscriptions.size).to eq(2)+ end++ it 'returns a copy of the subscriptions' do+ registry.register('order.complete', subscriber_class)++ subscriptions = registry.all_subscriptions+ subscriptions.clear++ expect(registry.size).to eq(1)+ end+ end++ describe '#patterns' do+ it 'returns unique patterns' do+ registry.register('order.complete', subscriber_class)+ registry.register('order.complete', another_subscriber)+ registry.register('order.*', subscriber_class)++ expect(registry.patterns).to contain_exactly('order.complete', 'order.*')+ end+ end++ describe '#clear!' do+ it 'removes all subscriptions' do+ registry.register('order.complete', subscriber_class)+ registry.register('order.*', another_subscriber)++ registry.clear!++ expect(registry.size).to eq(0)+ end+ end++ describe '#registered?' do+ it 'returns true for registered patterns' do+ registry.register('order.complete', subscriber_class)++ expect(registry.registered?('order.complete')).to be true+ end++ it 'returns false for unregistered patterns' do+ expect(registry.registered?('order.complete')).to be false+ end+ end++ describe 'thread safety' do+ it 'handles concurrent registrations' do+ threads = 10.times.map do |i|+ Thread.new do+ registry.register("event.#{i}", subscriber_class)+ end+ end++ threads.each(&:join)++ expect(registry.size).to eq(10)+ end+ end+enddiff --git a/core/spec/models/spree/events_spec.rb b/core/spec/models/spree/events_spec.rbnew file mode 100644index 0000000000..2f01dac59a--- /dev/null+++ b/core/spec/models/spree/events_spec.rb@@ -0,0 +1,256 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Events do+ before do+ described_class.reset!+ end++ after do+ described_class.reset!+ end++ describe '.publish' do+ it 'publishes an event' do+ event = described_class.publish('order.complete', { id: 1 })++ expect(event).to be_a(Spree::Event)+ expect(event.name).to eq('order.complete')+ expect(event.payload).to eq({ 'id' => 1 })+ end++ it 'includes metadata with IDs as strings' do+ event = described_class.publish('order.complete', { id: 1 }, { user_id: 5 })++ expect(event.metadata['user_id']).to eq('5')+ end++ it 'notifies subscribers synchronously when async: false' do+ received_events = []++ described_class.subscribe('order.complete', async: false) do |event|+ received_events << event+ end++ described_class.activate!+ described_class.publish('order.complete', { id: 1 })++ expect(received_events.size).to eq(1)+ end+ end++ describe '.subscribe' do+ it 'subscribes with a block' do+ called = false++ described_class.subscribe('order.complete', async: false) do |_event|+ called = true+ end++ described_class.activate!+ described_class.publish('order.complete', {})++ expect(called).to be true+ end++ it 'subscribes with a class' do+ received = []+ handler_class = Class.new do+ define_singleton_method(:call) do |event|+ received << event+ end+ end++ described_class.subscribe('order.complete', handler_class, async: false)+ described_class.activate!+ described_class.publish('order.complete', {})++ expect(received.size).to eq(1)+ end++ it 'supports pattern matching with wildcards' do+ received_events = []++ described_class.subscribe('order.*', async: false) do |event|+ received_events << event+ end++ described_class.activate!+ described_class.publish('order.complete', {})+ described_class.publish('order.cancel', {})+ described_class.publish('product.create', {})++ expect(received_events.size).to eq(2)+ expect(received_events.map(&:name)).to contain_exactly('order.complete', 'order.cancel')+ end++ it 'supports global wildcard' do+ received_events = []++ described_class.subscribe('*', async: false) do |event|+ received_events << event+ end++ described_class.activate!+ described_class.publish('order.complete', {})+ described_class.publish('product.create', {})++ expect(received_events.size).to eq(2)+ end++ it 'raises error when no subscriber provided' do+ expect { described_class.subscribe('order.complete') }.to raise_error(ArgumentError)+ end+ end++ describe '.unsubscribe' do+ it 'removes a subscriber' do+ received_events = []+ handler = ->(event) { received_events << event }++ described_class.subscribe('order.complete', handler, async: false)+ described_class.unsubscribe('order.complete', handler)+ described_class.activate!+ described_class.publish('order.complete', {})++ expect(received_events).to be_empty+ end+ end++ describe '.patterns' do+ it 'returns all registered patterns' do+ described_class.subscribe('order.complete', async: false) { }+ described_class.subscribe('order.*', async: false) { }++ expect(described_class.patterns).to contain_exactly('order.complete', 'order.*')+ end+ end++ describe '.subscriptions' do+ it 'returns all subscriptions' do+ described_class.subscribe('order.complete', async: false) { }+ described_class.subscribe('order.cancel', async: false) { }++ expect(described_class.subscriptions.size).to eq(2)+ end+ end++ describe '.disable' do+ it 'disables events within the block' do+ received = false++ described_class.subscribe('order.complete', async: false) do+ received = true+ end++ described_class.activate!++ described_class.disable do+ described_class.publish('order.complete', {})+ end++ expect(received).to be false+ end++ it 'restores enabled state after the block' do+ described_class.disable do+ expect(described_class.enabled?).to be false+ end++ expect(described_class.enabled?).to be true+ end++ it 'handles nested disable blocks' do+ described_class.disable do+ described_class.disable do+ expect(described_class.enabled?).to be false+ end+ expect(described_class.enabled?).to be false+ end++ expect(described_class.enabled?).to be true+ end+ end++ describe '.enabled?' do+ it 'returns true by default' do+ expect(described_class.enabled?).to be true+ end++ it 'returns false when disabled' do+ described_class.disable do+ expect(described_class.enabled?).to be false+ end+ end+ end++ describe '.reset!' do+ it 'clears all subscriptions' do+ described_class.subscribe('order.complete', async: false) { }++ described_class.reset!++ expect(described_class.subscriptions).to be_empty+ end+ end++ 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' do+ it 'notifies all matching subscribers' do+ received1 = []+ received2 = []++ described_class.subscribe('order.complete', async: false) { |e| received1 << e }+ described_class.subscribe('order.complete', async: false) { |e| received2 << e }++ described_class.activate!+ described_class.publish('order.complete', {})++ expect(received1.size).to eq(1)+ expect(received2.size).to eq(1)+ end++ it 'handles mixed pattern and exact subscribers' do+ exact_received = []+ pattern_received = []++ described_class.subscribe('order.complete', async: false) { |e| exact_received << e }+ described_class.subscribe('order.*', async: false) { |e| pattern_received << e }++ described_class.activate!+ described_class.publish('order.complete', {})+ described_class.publish('order.cancel', {})++ expect(exact_received.size).to eq(1)+ expect(pattern_received.size).to eq(2)+ end+ end+enddiff --git a/core/spec/models/spree/subscriber_spec.rb b/core/spec/models/spree/subscriber_spec.rbnew file mode 100644index 0000000000..8db0dc6b1c--- /dev/null+++ b/core/spec/models/spree/subscriber_spec.rb@@ -0,0 +1,206 @@+# frozen_string_literal: true++require 'spec_helper'++RSpec.describe Spree::Subscriber do+ before do+ Spree::Events.reset!+ end++ after do+ Spree::Events.reset!+ end++ describe '.subscribes_to' do+ it 'registers subscription patterns' do+ subscriber_class = Class.new(described_class) do+ subscribes_to 'order.complete'+ end++ expect(subscriber_class.subscription_patterns).to eq(['order.complete'])+ end++ it 'accepts multiple patterns' do+ subscriber_class = Class.new(described_class) do+ subscribes_to 'order.complete', 'order.cancel'+ end++ expect(subscriber_class.subscription_patterns).to contain_exactly('order.complete', 'order.cancel')+ end++ it 'stores subscription options' do+ subscriber_class = Class.new(described_class) do+ subscribes_to 'order.complete', async: false+ end++ expect(subscriber_class.subscription_options).to eq({ async: false })+ end++ it 'accumulates patterns from multiple calls' do+ subscriber_class = Class.new(described_class) do+ subscribes_to 'order.complete'+ subscribes_to 'order.cancel'+ end++ expect(subscriber_class.subscription_patterns).to contain_exactly('order.complete', 'order.cancel')+ end+ end++ describe '.on' do+ it 'maps events to methods' do+ subscriber_class = Class.new(described_class) do+ subscribes_to 'payment.complete', 'payment.void'+ on 'payment.complete', :handle_complete+ on 'payment.void', :handle_void+ end++ expect(subscriber_class.event_handlers).to eq({+ 'payment.complete' => :handle_complete,+ 'payment.void' => :handle_void+ })+ end+ end++ describe '.register!' do+ it 'registers the subscriber with the event system' do+ subscriber_class = Class.new(described_class) do+ subscribes_to 'order.complete'+ end++ subscriber_class.register!++ expect(Spree::Events.patterns).to include('order.complete')+ end++ it 'does nothing when no patterns defined' do+ subscriber_class = Class.new(described_class)++ expect { subscriber_class.register! }.not_to change { Spree::Events.patterns.size }+ end+ end++ describe '.unregister!' do+ it 'removes the subscriber from the event system' do+ subscriber_class = Class.new(described_class) do+ subscribes_to 'order.complete'+ end++ subscriber_class.register!+ subscriber_class.unregister!++ expect(Spree::Events.subscriptions).to be_empty+ end+ end++ describe '#call' do+ context 'without event handlers' do+ it 'calls the handle method' do+ handled_events = []++ subscriber_class = Class.new(described_class) do+ define_method(:handle) do |event|+ handled_events << event+ end+ end++ event = Spree::Event.new(name: 'order.complete', payload: {})+ subscriber_class.new.call(event)++ expect(handled_events).to eq([event])+ end+ end++ context 'with event handlers' do+ it 'routes to the correct handler' do+ called_handlers = []++ subscriber_class = Class.new(described_class) do+ subscribes_to 'payment.complete', 'payment.void'+ on 'payment.complete', :handle_complete+ on 'payment.void', :handle_void++ define_method(:handle_complete) do |event|+ called_handlers << [:complete, event]+ end++ define_method(:handle_void) do |event|+ called_handlers << [:void, event]+ end+ end++ complete_event = Spree::Event.new(name: 'payment.complete', payload: {})+ void_event = Spree::Event.new(name: 'payment.void', payload: {})++ subscriber_class.new.call(complete_event)+ subscriber_class.new.call(void_event)++ expect(called_handlers).to eq([+ [:complete, complete_event],+ [:void, void_event]+ ])+ end++ it 'falls back to handle when no matching handler' do+ handled_events = []++ subscriber_class = Class.new(described_class) do+ subscribes_to 'payment.*'+ on 'payment.complete', :handle_complete++ define_method(:handle_complete) do |_event|+ # Should not be called for refund events+ end++ define_method(:handle) do |event|+ handled_events << event+ end+ end++ event = Spree::Event.new(name: 'payment.refund', payload: {})+ subscriber_class.new.call(event)++ expect(handled_events).to eq([event])+ end+ end+ end++ describe '.call' do+ it 'creates an instance and calls it' do+ called = false++ subscriber_class = Class.new(described_class) do+ define_method(:handle) do |_event|+ called = true+ end+ end++ event = Spree::Event.new(name: 'test', payload: {})+ subscriber_class.call(event)++ expect(called).to be true+ end+ end++ describe 'integration' do+ it 'receives events when registered' do+ received_events = []++ subscriber_class = Class.new(described_class) do+ subscribes_to 'test.event', async: false++ define_method(:handle) do |event|+ received_events << event+ end+ end++ subscriber_class.register!+ Spree::Events.activate!++ Spree::Events.publish('test.event', { key: 'value' })++ expect(received_events.size).to eq(1)+ expect(received_events.first.name).to eq('test.event')+ expect(received_events.first.payload).to eq({ 'key' => 'value' })+ end+ end+end