Class: Spree::ProductMetricsSubscriber

Inherits:
Subscriber
  • Object
show all
Defined in:
app/subscribers/spree/product_metrics_subscriber.rb

Overview

Handles order completion events to update product metrics.

When an order is completed, this subscriber enqueues background jobs to refresh the metrics (units_sold_count, revenue) for each product in the order.

Instance Method Summary collapse

Methods inherited from Subscriber

#call, call, event_handlers, #handle, on, subscribes_to, subscription_options, subscription_patterns

Instance Method Details

#refresh_product_metrics(event) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'app/subscribers/spree/product_metrics_subscriber.rb', line 14

def refresh_product_metrics(event)
  order_id = event.payload['id']
  store_id = event.payload['store_id']
  return unless order_id && store_id

  order = Spree::Order.find_by(id: order_id)
  return unless order

  product_ids = order.line_items.includes(:variant).map { |li| li.variant.product_id }.uniq
  return if product_ids.empty?

  jobs = product_ids.map { |product_id| Spree::Products::RefreshMetricsJob.new(product_id, store_id) }
  ActiveJob.perform_all_later(jobs)
end