Class: PartyProductInterestSync

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

Overview

Synchronizes a Party's product interests (catalog product lines) and broadcasts
Events::ProductInterestChanged for any added/removed product line IDs.

Two entry points:

  • call(party, product_line_ids): full reconcile (computes added/removed, persists,
    broadcasts). Returns the cleaned id list, or nil when the party has no customer.
  • broadcast(party, added:, removed:): publish-only path used when ids were already
    persisted by another writer (Customer::NewCustomer initial save).

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(party) ⇒ PartyProductInterestSync

Returns a new instance of PartyProductInterestSync.



23
24
25
# File 'app/services/party_product_interest_sync.rb', line 23

def initialize(party)
  @party = party
end

Class Method Details

.broadcast(party, added: [], removed: []) ⇒ Object



19
20
21
# File 'app/services/party_product_interest_sync.rb', line 19

def self.broadcast(party, added: [], removed: [])
  new(party).broadcast(added: added, removed: removed)
end

.call(party, product_line_ids) ⇒ Object



15
16
17
# File 'app/services/party_product_interest_sync.rb', line 15

def self.call(party, product_line_ids)
  new(party).process(product_line_ids)
end

Instance Method Details

#broadcast(added:, removed:) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/services/party_product_interest_sync.rb', line 38

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

  AfterCommitEverywhere.after_commit do
    Rails.configuration.event_store.publish(
      Events::ProductInterestChanged.new(data: {
        party_id: @party.id,
        product_line_ids_added: added,
        product_line_ids_removed: removed
      }),
      stream_name: "Party-#{@party.id}"
    )
  end
end

#process(product_line_ids) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'app/services/party_product_interest_sync.rb', line 27

def process(product_line_ids)
  return unless customer_present?

  clean_ids = compact_sorted_ids(product_line_ids)
  added = clean_ids - @party.customer.product_line_ids
  removed = @party.customer.product_line_ids - clean_ids
  @party.product_line_ids = clean_ids
  broadcast(added: added, removed: removed)
  clean_ids
end