From 7bd84590e5bd111ea598c6142513ee0ddb0474c6 Mon Sep 17 00:00:00 2001 From: lukaszreszke Date: Thu, 14 Nov 2024 14:26:08 +0100 Subject: [PATCH] Process manager --- rails_application/app/services/send_email.rb | 37 ++++++++++++++++++++ rails_application/lib/configuration.rb | 5 +++ 2 files changed, 42 insertions(+) create mode 100644 rails_application/app/services/send_email.rb diff --git a/rails_application/app/services/send_email.rb b/rails_application/app/services/send_email.rb new file mode 100644 index 00000000..b6564a0b --- /dev/null +++ b/rails_application/app/services/send_email.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +class SendEmail + def call(event) + event_store.link(event.event_id, stream_name: "Sales$#{order_id(event)}") + + state = {} + + event_store.read.stream("Sales$#{order_id(event)}").each do |event_in_stream| + case event_in_stream + when Ordering::OrderPaid + state[:order_paid] = true + when Invoicing::InvoiceGenerated + state[:invoice_generated] = true + end + end + + if state[:order_paid] && state[:invoice_generated] + Rails.configuration.email_client.send_email(order_id(event)) + end + end + + private + + def order_id(event) + case event + when Ordering::OrderPaid + event.data[:id] + when Invoicing::InvoiceGenerated + event.data[:order_id] + end + end + + def event_store + Rails.configuration.event_store + end +end diff --git a/rails_application/lib/configuration.rb b/rails_application/lib/configuration.rb index 07946910..ece0a1cd 100644 --- a/rails_application/lib/configuration.rb +++ b/rails_application/lib/configuration.rb @@ -21,6 +21,11 @@ def call(event_store, command_bus) Inventory::UpdateProductCatalog, to: [Inventory::StockLevelIncreased, Inventory::StockLevelDecreased] ) + + event_store.subscribe( + SendEmail, + to: [Ordering::OrderPaid, Invoicing::InvoiceGenerated] + ) end def self.available_vat_rates