Class: CustomerBuyingGroupUpdater

Inherits:
Object
  • Object
show all
Defined in:
app/services/customer_buying_group_updater.rb

Overview

Updates a Customer's buying group and broadcasts Events::BuyingGroupChanged
when the value actually changes. Two entry points:

  • call(customer, buying_group_id): full reconcile (no-op when unchanged)
  • broadcast(customer, added:, removed:): publish-only path used when ids
    were already persisted by another writer (Customer::NewCustomer initial save).

Flat name (not Customer::BuyingGroupUpdater) because Customer is an AR model
and Zeitwerk would otherwise create a top-level Customer module.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(customer) ⇒ CustomerBuyingGroupUpdater

Returns a new instance of CustomerBuyingGroupUpdater.



20
21
22
# File 'app/services/customer_buying_group_updater.rb', line 20

def initialize(customer)
  @customer = customer
end

Class Method Details

.broadcast(customer, added: nil, removed: nil) ⇒ Object



16
17
18
# File 'app/services/customer_buying_group_updater.rb', line 16

def self.broadcast(customer, added: nil, removed: nil)
  new(customer).broadcast(added: added, removed: removed)
end

.call(customer, buying_group_id) ⇒ Object



12
13
14
# File 'app/services/customer_buying_group_updater.rb', line 12

def self.call(customer, buying_group_id)
  new(customer).process(buying_group_id)
end

Instance Method Details

#broadcast(added:, removed:) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'app/services/customer_buying_group_updater.rb', line 34

def broadcast(added:, removed:)
  return if added.nil? && removed.nil?

  AfterCommitEverywhere.after_commit do
    Rails.configuration.event_store.publish(
      Events::BuyingGroupChanged.new(data: {
        party_id: @customer.id,
        buying_group_id_added: added,
        buying_group_id_removed: removed
      }),
      stream_name: "Party-#{@customer.id}"
    )
  end
end

#process(buying_group_id) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'app/services/customer_buying_group_updater.rb', line 24

def process(buying_group_id)
  new_id = buying_group_id.to_i
  return if @customer.buying_group_id == new_id

  previous_id = @customer.buying_group_id
  broadcast(added: buying_group_id, removed: previous_id)
  @customer.buying_group_id = buying_group_id
  buying_group_id
end