Class: Activity::EmailNotificationHandler

Inherits:
Object
  • Object
show all
Defined in:
app/subscribers/activity/email_notification_handler.rb

Overview

Creates outbound Communications triggered by an activity's activity_type email
template, after the activity has been persisted and the transaction commits.

Subscribes to: Events::ActivityCreated

WHY after-commit: CommunicationBuilder persists a Communication record.
Running after commit prevents orphaned communications if the parent activity
save is rolled back for any reason.

Behavioural invariant: does NOT fire when the activity_type is configured with
skip_email_template_with_result AND the activity already has a result type at
creation time (e.g. chain-created completed activities).

Instance Method Summary collapse

Instance Method Details

#call(event) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/subscribers/activity/email_notification_handler.rb', line 16

def call(event)
  activity = Activity.find_by(id: event.data[:activity_id])
  return unless activity
  return unless activity.activity_type

  template = activity.activity_type.email_template
  return unless template
  return if activity.activity_type.skip_email_template_with_result && activity.activity_result_type.present?

  appointment = nil
  appointment = activity.resource.generate_service_calendar_event if activity.resource && activity.is_onsite_service? && activity.open?

  comm = CommunicationBuilder.new(
    sender_party:              activity.sender_party,
    resource:                  activity.resource,
    recipient_party:           activity.party,
    template:,
    current_user:              (activity.creator if activity.creator.is_a?(Employee)),
    use_best_email:            true,
    appointment:,
    transmit_at:               activity.activity_type.email_transmit_at_time,
    triggered_by_activity_id:  activity.id
  ).create
  Rails.logger.info "Activity #{activity.id} created communication #{comm.id}"
rescue StandardError => e
  ErrorReporting.error(e, activity_id: event.data[:activity_id])
  raise
end