Class: Communication

Inherits:
ApplicationRecord show all
Includes:
Models::Auditable, Models::Embeddable, Models::Lineage
Defined in:
app/models/communication.rb

Overview

== Schema Information

Table name: communications
Database name: primary

id :integer not null, primary key
archived :boolean default(FALSE), not null
body :text
body_email :text
category :string
direction :integer default("outbound")
redactor_version :string
reply_to :string
reply_to_full_name :string
resource_type :string(25)
sender :string(254)
state :string(25)
status_message :text
subject :string(255)
template_merge_options :jsonb
transmit_at :datetime
triggered_by_mailbox :boolean default(FALSE), not null
created_at :datetime not null
updated_at :datetime not null
creator_id :integer
email_template_id :integer
mailbox_inbound_email_id :integer
parent_id :integer
recipient_party_id :integer
reply_to_parent_id :integer
resource_id :integer
sender_party_id :integer
source_id :integer
triggered_by_activity_id :integer
unique_id :uuid
updater_id :integer

Indexes

communications_email_template_id_idx (email_template_id) WHERE (NOT (email_template_id IS NULL))
communications_resource (resource_type,resource_id) WHERE (NOT ((resource_type IS NULL) AND (resource_id IS NULL)))
index_communications_on_direction (direction)
index_communications_on_parent_id (parent_id) WHERE (parent_id IS NOT NULL) USING hash
index_communications_on_sender_party_id (sender_party_id) WHERE (NOT (sender_party_id IS NULL))
index_communications_on_state (state) USING hash
index_communications_on_transmit_at (transmit_at) USING brin
index_communications_on_unique_id (unique_id) USING hash
index_communications_recipient_party_id (recipient_party_id) WHERE (NOT (recipient_party_id IS NULL))

Foreign Keys

communications_email_template_id_fk (email_template_id => email_templates.id) ON DELETE => nullify
communications_recipient_party_id_fk (recipient_party_id => parties.id)
communications_sender_party_id_fk (sender_party_id => parties.id)

Defined Under Namespace

Classes: EventParser

Constant Summary collapse

VALID_TRANSMIT_METHODS =
[ContactPoint::EMAIL, ContactPoint::FAX].freeze
DEFAULT_SENDER =
'info@warmlyyours.com'
MIN_EMBEDDABLE_BODY_LENGTH =

Minimum stripped-text length for a communication to be worth embedding.

80

Constants included from Models::Embeddable

Models::Embeddable::DEFAULT_MODEL, Models::Embeddable::MAX_CONTENT_LENGTH

Constants included from Models::Auditable

Models::Auditable::ALWAYS_IGNORED

Instance Attribute Summary collapse

Belongs to collapse

Methods included from Models::Auditable

#creator, #updater

Has many collapse

Methods included from Models::Embeddable

#content_embeddings

Has and belongs to many collapse

Delegated Instance Attributes collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Models::Embeddable

embeddable_content_types, #embeddable_locales, #embedding_content_hash, embedding_partition_class, #embedding_stale?, #embedding_type_name, #embedding_vector, #find_content_embedding, #find_similar, #generate_all_embeddings!, #generate_chunked_embeddings!, #generate_embedding!, #has_embedding?, #locale_for_embedding, #needs_chunking?, regenerate_all_embeddings, semantic_search

Methods included from Models::Auditable

#all_skipped_columns, #audit_reference_data, #should_not_save_version, #stamp_record

Methods included from Models::Lineage

#ancestors, #ancestors_ids, #children_and_roots, #descendants, #descendants_ids, #ensure_non_recursive_lineage, #family_members, #generate_full_name, #generate_full_name_array, #lineage, #lineage_array, #lineage_simple, #root, #root_id, #self_ancestors_and_descendants, #self_ancestors_and_descendants_ids, #self_and_ancestors, #self_and_ancestors_ids, #self_and_children, #self_and_descendants, #self_and_descendants_ids, #self_and_siblings, #self_and_siblings_ids, #siblings, #siblings_ids

Methods inherited from ApplicationRecord

ransackable_associations, ransackable_attributes, ransackable_scopes, ransortable_attributes, #to_relation

Methods included from Models::EventPublishable

#publish_event

Instance Attribute Details

#appointmentObject

Returns the value of attribute appointment.



91
92
93
# File 'app/models/communication.rb', line 91

def appointment
  @appointment
end

#bodyObject (readonly)



110
# File 'app/models/communication.rb', line 110

validates :body, :subject, presence: { unless: proc { archived && is_triggered_by_mailbox? } }

#check_subscription_preferencesObject

Returns the value of attribute check_subscription_preferences.



91
92
93
# File 'app/models/communication.rb', line 91

def check_subscription_preferences
  @check_subscription_preferences
end

#existing_upload_idsObject

Returns the value of attribute existing_upload_ids.



91
92
93
# File 'app/models/communication.rb', line 91

def existing_upload_ids
  @existing_upload_ids
end

#multi_emailsObject

Returns the value of attribute multi_emails.



91
92
93
# File 'app/models/communication.rb', line 91

def multi_emails
  @multi_emails
end

#skip_suppression_checkObject

Returns the value of attribute skip_suppression_check.



91
92
93
# File 'app/models/communication.rb', line 91

def skip_suppression_check
  @skip_suppression_check
end

#subjectObject (readonly)



110
# File 'app/models/communication.rb', line 110

validates :body, :subject, presence: { unless: proc { archived && is_triggered_by_mailbox? } }

Class Method Details



729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
# File 'app/models/communication.rb', line 729

def self.append_source_to_links(cbody, referral_code)
  html_doc = Nokogiri::HTML(cbody)
  html_doc.xpath('//a').select { |node| node['href'].present? && node['href'] =~ /^http/ }.each do |node|
    base_href = node['href']
    uri = Addressable::URI.parse(base_href.to_s.squish)
    uri.host ||= WEB_HOSTNAME
    uri.scheme ||= 'https'
    uri.path = uri.path&.chomp('/')
    # We only care to add ref code to us
    next unless /^www\.warmlyyours/.match?(uri.host)

    merged_params = Rack::Utils.parse_nested_query uri.query
    merged_params = (merged_params || {}).with_indifferent_access
    merged_params.merge!({ referral_code: }) if referral_code.present?
    uri.query = merged_params.present? ? merged_params.to_query : nil
    # base_href = base_href.gsub(/\/$/, '') # remove any trailing forward slash
    # operator = base_href.include?('?') ? '&' : '?'
    # utm_sources = ["utm_source=#{Addressable::URI.escape(campaign_email_name)}", "utm_medium=email", "utm_campaign=#{URI.escape(campaign_name)}"]
    # node['href'] = base_href+operator+"referral_code="+referral_code+"&"+utm_sources.join("&")
    node['href'] = uri.to_s # base_href + operator + 'referral_code=' + referral_code
  end
  html_doc.to_html.gsub('&', '&')
end

.campaign_onlyActiveRecord::Relation<Communication>

A relation of Communications that are campaign only. Active Record Scope

Returns:

See Also:



89
# File 'app/models/communication.rb', line 89

scope :campaign_only, -> { where(resource_type: 'CampaignDelivery') }

.default_signature(employee = nil) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'app/models/communication.rb', line 229

def self.default_signature(employee = nil)
  parts = ['WarmlyYours Radiant Inc']
  store = signature_store_for(employee)
  append_signature_employee_line(parts, employee)
  email, phone, fax = signature_contact_fields(employee, store)
  append_signature_address_line(parts, store)
  parts << "E. #{email}" if email
  parts << signature_phone_fax_line(phone, fax)
  parts << 'Visit us online at https://www.warmlyyours.com'

  # e.g.
  # WarmlyYours Radiant Inc
  # Ramie Blatt | Senior Software Developer
  # 2 Corporate Drive | Long Grove, IL 60047
  # T. (800) 875-5285 ext. 848 | F. (800) 408-1100
  # Visit us online at www.WarmlyYours.com
  parts.join("\n")
end

.documents_html(publications = []) ⇒ Object



337
338
339
340
341
342
343
344
345
346
347
# File 'app/models/communication.rb', line 337

def self.documents_html(publications = [])
  if publications.empty?
    ''
  else
    text = "<p>The following additional documents are available for your review:<ul style='padding-left: 0; margin-left: 40px; list-style: none;'>"
    publications.each do |d|
      text += "<li style='clear: both; text-decoration: none; padding: 4px 0 15px 0; height: 10px;'><img style='float: left;' src='https://ik.warmlyyours.com/img/pdf-54057a.jpeg'><a style='float: left; padding-left: 10px; padding-top: 4px; color: #333; text-decoration: none;' href='https://www.warmlyyours.com/publications/#{d.sku}'>#{d.public_name}</a></li>"
    end
    text += '</ul></p>'
  end
end

.documents_plain(publications = []) ⇒ Object



327
328
329
330
331
332
333
334
335
# File 'app/models/communication.rb', line 327

def self.documents_plain(publications = [])
  if publications.empty?
    ''
  else
    text = "The following additional documents are available for your review:\r\n"
    text += publications.map { |p| "https://www.warmlyyours.com/publications/#{p.sku}" }.join("\r\n")
    text
  end
end

.embeddableActiveRecord::Relation<Communication>

A relation of Communications that are embeddable. Active Record Scope

Returns:

See Also:



861
# File 'app/models/communication.rb', line 861

scope :embeddable, -> { where(category: nil) }

.most_recent_firstActiveRecord::Relation<Communication>

A relation of Communications that are most recent first. Active Record Scope

Returns:

See Also:



84
# File 'app/models/communication.rb', line 84

scope :most_recent_first, -> { order('COALESCE(communications.transmit_at, communications.created_at) DESC') }

.non_campaignActiveRecord::Relation<Communication>

A relation of Communications that are non campaign. Active Record Scope

Returns:

See Also:



88
# File 'app/models/communication.rb', line 88

scope :non_campaign, -> { where("resource_type is null or resource_type <> 'CampaignDelivery'") }

.parse_valid_email_address(email) ⇒ Object



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'app/models/communication.rb', line 503

def self.parse_valid_email_address(email)
  return nil unless email.is_a?(String) && email.include?('@')

  # Step 1: Parse with Mail::Address
  begin
    parsed_email = Mail::Address.new(email)
    return nil unless parsed_email.address == email && parsed_email.local && parsed_email.domain
  rescue Mail::Field::ParseError
    return nil
  end
  # Step 2: Validate with TrueMail (Optional, for deeper validation)
  truemail_result = Truemail.validate(email)
  return email if truemail_result # TrueMail returns true/false

  nil
end

.problem_stateActiveRecord::Relation<Communication>

A relation of Communications that are problem state. Active Record Scope

Returns:

See Also:



87
# File 'app/models/communication.rb', line 87

scope :problem_state, -> { with_a_recipient_in_state(CommunicationRecipient::UNDELIVERED + CommunicationRecipient::UNWANTED) }

.process_recipients(rel_cr) ⇒ Object



421
422
423
424
425
426
427
428
429
# File 'app/models/communication.rb', line 421

def self.process_recipients(rel_cr)
  to_array = []
  rel_cr.each do |cr|
    address = Mail::Address.new cr.formatted_email_string # ex: "john@example.com"
    address.display_name = cr.name if cr.name.present? # ex: "John Doe"
    to_array << address.format # returns "John Doe <john@example.com>"
  end
  to_array.empty? ? nil : to_array.uniq.compact.join(',')
end

.sent_todayActiveRecord::Relation<Communication>

A relation of Communications that are sent today. Active Record Scope

Returns:

See Also:



86
# File 'app/models/communication.rb', line 86

scope :sent_today, -> { where(state: 'sent').where(transmit_at: Date.current.beginning_of_day...) }

.signature_to_html(text = '') ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'app/models/communication.rb', line 300

def self.signature_to_html(text = '')
  return '' if text.blank?

  text = text.gsub("\r\n\r\n", '</p><p>')
  text = text.gsub("\r\n", '<br>')
  text = text.gsub("\n", '<br>')
  text = text.gsub("\r", '<br>')

  "<table>
    <tr>
      <td style='width:80px;padding:0 10px 0 0'>
        <p style='line-height: 3em;white-space:nowrap'>
          <img src='https://ik.warmlyyours.com/img/warmlyyours-ee8a63.jpeg' alt='WarmlyYours Logo'><br>
          <a href='https://www.facebook.com/WarmlyYours' target='_blank'><img  style='border:none' src='https://ik.warmlyyours.com/img/warmlyyoursfb-86a1b8.png' alt='WarmlyYours Facebook'></a>
		      <a href='https://twitter.com/warmlyyours' target='_blank'><img style='border:none' src='https://ik.warmlyyours.com/img/warmlyyourstw-e403fd.png' alt='WarmlyYours Twitter'></a>
		      <a href='https://www.linkedin.com/company/warmlyyours/' target='_blank'><img style='border:none' src='https://ik.warmlyyours.com/img/warmlyyoursli-c746a7.png' alt='WarmlyYours Linked In'></a>
		    </p>
	    </td>
	    <td style='width:500px;padding: 0 10px 0 0; vertical-align: top;'>
		    <p style='line-height:1.4em;font-size:12px'>
		      #{text}
		    </p>
	    </td>
	  </tr>
	</table>"
end

.state_for_selectObject



225
226
227
# File 'app/models/communication.rb', line 225

def self.state_for_select
  Communication.state_machines[:state].states.map { |s| [s.name.to_s.titleize, s.name.to_s] }
end

.text_to_html(text = '') ⇒ Object



290
291
292
293
294
295
296
297
298
# File 'app/models/communication.rb', line 290

def self.text_to_html(text = '')
  return '' if text.blank?

  text = text.gsub("\r\n\r\n", '</p><p>')
  text = text.gsub("\r\n", '<br>')
  text = text.gsub("\n", '<br>')
  text = text.gsub("\r", '<br>')
  %(<p>#{text}</p>)
end

.with_a_recipient_in_stateActiveRecord::Relation<Communication>

A relation of Communications that are with a recipient in state. Active Record Scope

Returns:

See Also:



85
# File 'app/models/communication.rb', line 85

scope :with_a_recipient_in_state, ->(recipient_state) { where('EXISTS(select 1 from communication_recipients cr where cr.state IN (?) and cr.communication_id = communications.id)', recipient_state) }

Instance Method Details

#activitiesActiveRecord::Relation<Activity>

Returns:

See Also:



79
# File 'app/models/communication.rb', line 79

has_many :activities, dependent: :nullify

#attachments_too_large?Boolean

Returns:

  • (Boolean)


815
816
817
# File 'app/models/communication.rb', line 815

def attachments_too_large?
  total_attachment_size > provider_limit
end

#bccObject



453
454
455
# File 'app/models/communication.rb', line 453

def bcc
  self.class.process_recipients(communication_recipients.where(email_method: 'bcc'))
end

#body_for_emailObject

Body used for sending: full email document (body_email) when present, else editor content (body).



699
700
701
# File 'app/models/communication.rb', line 699

def body_for_email
  body_email.presence || body
end

#build_recipients(email, email_method = nil) ⇒ Object



485
486
487
488
489
490
491
492
# File 'app/models/communication.rb', line 485

def build_recipients(email, email_method = nil)
  return unless email.present?

  email.split(',').each do |email|
    email = email.strip.downcase
    communication_recipients.build(detail: email, category: ContactPoint::EMAIL, email_method:) unless communication_recipients.detect { |cr| cr.detail == email }
  end
end

#can_be_edited?Boolean

Communications can only be edited while in draft state

Returns:

  • (Boolean)


190
191
192
# File 'app/models/communication.rb', line 190

def can_be_edited?
  draft?
end

#can_release?Boolean

Returns:

  • (Boolean)


349
350
351
352
353
# File 'app/models/communication.rb', line 349

def can_release?
  has_recipients? &&
    (transmit_at.nil? || (Time.current > transmit_at)) &&
    valid?
end

#ccObject



449
450
451
# File 'app/models/communication.rb', line 449

def cc
  self.class.process_recipients(communication_recipients.where(email_method: 'cc'))
end

#clear_bounce_listObject



494
495
496
497
498
499
500
501
# File 'app/models/communication.rb', line 494

def clear_bounce_list
  emails = communication_recipients.emails.joins(:contact_point).pluck(:detail)
  if emails.present?
    Sendgrid::Toolkit.delete_bounces(emails:)
  else
    []
  end
end

#close_reply_activityObject



766
767
768
769
770
771
772
773
774
# File 'app/models/communication.rb', line 766

def close_reply_activity
  # Find if there is any activity attached to the parent communication. If so, mark the activity as completed.
  # Use the reply communication's created_at so the parent activity sorts chronologically
  # before the outgoing reply in the activity timeline (which sorts by completion_datetime DESC).
  return unless reply_to_parent_id.present?

  parent_act = Activity.where(communication_id: reply_to_parent_id)&.first
  parent_act.complete(completion_datetime: created_at) if parent_act.present? && parent_act.open?
end

#communication_recipientsActiveRecord::Relation<CommunicationRecipient>

Returns:

See Also:

Validations (unless => proc { is_triggered_by_mailbox? } ):

  • Nested_attributes_uniqueness ({ field: :detail })


80
# File 'app/models/communication.rb', line 80

has_many :communication_recipients, inverse_of: :communication

#communication_resourceObject



673
674
675
# File 'app/models/communication.rb', line 673

def communication_resource
  resource.present? && resource.respond_to?(:communication_resource) ? resource.communication_resource : resource
end

#compliant_bodyObject



703
704
705
706
707
# File 'app/models/communication.rb', line 703

def compliant_body
  cbody = "#{preview_text}#{body_for_email}"
  cbody = self.class.append_source_to_links(cbody, source.referral_code) if source.present?
  cbody.presence
end

#content_for_embedding(_content_type = :primary) ⇒ Object



863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
# File 'app/models/communication.rb', line 863

def content_for_embedding(_content_type = :primary)
  return nil if category.present?

  text = stripped_body_for_embedding
  return nil if text.blank? || text.length < MIN_EMBEDDABLE_BODY_LENGTH

  parts = []
  parts << "Direction: #{direction_inbound? ? 'Inbound from customer' : 'Outbound from staff'}"
  parts << "Subject: #{subject.strip}" if subject.present?
  parts << "From: #{sender_party&.full_name || sender}" if sender.present?
  parts << "To: #{recipient_party&.full_name}" if recipient_party
  parts << "Relates to: #{resource_type} ##{resource_id}" if resource_type.present?
  parts << text.first(2000)
  parts.compact.join("\n")
end

#create_email_activitiesObject



776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# File 'app/models/communication.rb', line 776

def create_email_activities
  # recipients = communication_recipients.with_party
  # recipients = communication_recipients if resource&.respond_to?(:tracking_email)

  communication_recipients.each do |cr|
    next if (cr.contact_point.present? && activities.detect { |a| a.party_id == cr.contact_point.party_id }) || (cr.contact_point&.party&.class == Employee)

    activity_type_id = (cr.category == ContactPoint::FAX ? ActivityTypeConstants::FAXOUT : ActivityTypeConstants::EMAILOUT)
    activities.create(party: cr.contact_point&.party,
                      activity_type_id:,
                      target_datetime: Time.current,
                      assigned_resource: sender_party,
                      resource:,
                      description: "Email: #{subject}",
                      activity_result_type: ActivityResultType.find_by(result_code: 'QUEUED'))
  end
  true
end

#custom_resource_exception_actionsObject



805
806
807
808
# File 'app/models/communication.rb', line 805

def custom_resource_exception_actions
  resource.post_communication_exception_hook if resource&.respond_to?(:post_communication_exception_hook)
  true
end

#custom_resource_queued_actionsObject



795
796
797
798
# File 'app/models/communication.rb', line 795

def custom_resource_queued_actions
  resource.post_communication_queued_hook if resource&.respond_to?(:post_communication_queued_hook)
  true
end

#custom_resource_sent_actionsObject



800
801
802
803
# File 'app/models/communication.rb', line 800

def custom_resource_sent_actions
  resource.post_communication_sent_hook if resource&.respond_to?(:post_communication_sent_hook)
  true
end

#custom_resource_suppressed_actionsObject



810
811
812
813
# File 'app/models/communication.rb', line 810

def custom_resource_suppressed_actions
  resource.post_communication_suppressed_hook if resource&.respond_to?(:post_communication_suppressed_hook)
  true
end

#deep_dupObject



117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'app/models/communication.rb', line 117

def deep_dup
  associations = [:uploads]
  associations << :communication_recipients if is_not_campaign_delivery?
  deep_clone(
    include: associations,
    except: %i[unique_id transmit_at]
  ) do |original, copy|
    if copy.is_a?(Communication)
      copy.state = 'draft'
      copy.parent_id = original.id
    end
  end
end

#default_recipient_listObject



413
414
415
416
417
418
419
# File 'app/models/communication.rb', line 413

def default_recipient_list
  return nil unless resource || recipient_party

  # Use flat results because TomSelectInput (CollectionSelectInput) doesn't support
  # grouped hash collections. Hash format is only for Rails' grouped_select input.
  ContactPoint::AddressBookBuilder.options_for_select(resource:, party: recipient_party, group_results: false)
end

#default_resource_for_selectObject



677
678
679
680
681
682
# File 'app/models/communication.rb', line 677

def default_resource_for_select
  return [] unless communication_resource

  formatter = Activity::ResourceList.build_formatter(communication_resource)
  [[formatter.display, formatter.identifier]]
end

#email_templateEmailTemplate



74
# File 'app/models/communication.rb', line 74

belongs_to :email_template, optional: true

#embedding_content_changed?Boolean

Returns:

  • (Boolean)


879
880
881
# File 'app/models/communication.rb', line 879

def embedding_content_changed?
  saved_change_to_body? || saved_change_to_subject?
end

#enqueue_release_workerObject



435
436
437
438
439
440
441
442
443
# File 'app/models/communication.rb', line 435

def enqueue_release_worker
  CommunicationWorker.perform_async(id)
rescue RedisClient::CannotConnectError => e
  Rails.logger.warn(
    "Communication #{id} queued but failed to enqueue CommunicationWorker: #{e.message}. " \
    'The scheduled CommunicationWorker will retry queued records once Redis recovers.'
  )
  nil
end

#external_stylesheet_for_emailObject



638
639
640
641
642
# File 'app/models/communication.rb', line 638

def external_stylesheet_for_email
  return unless email_template.present?

  email_template.stylesheet # EmailTemplate::DEFAULT_STYLESHEET we're trying without this
end

#feed_historiesActiveRecord::Relation<FeedHistory>

Returns:

See Also:



81
# File 'app/models/communication.rb', line 81

has_many :feed_histories, dependent: :destroy

#fill_suppressed_reasonObject



400
401
402
403
404
405
406
407
408
409
410
411
# File 'app/models/communication.rb', line 400

def fill_suppressed_reason
  reason = if has_unsubscribed?
             'Recipient has unsubscribed to this type of email'
           elsif has_failed_contact_point?
             'Delivery has failed to this recipient previously'
           elsif has_inactive_contact?
             'Contact is marked as inactive'
           elsif has_closed_customer?
             'Customer is marked as closed or bankrupt'
           end
  self.status_message = reason
end

#has_closed_customer?Boolean

Returns:

  • (Boolean)


379
380
381
382
383
384
385
386
387
388
# File 'app/models/communication.rb', line 379

def has_closed_customer?
  return false if recipient_party.nil?

  customer = if recipient_party.class == Contact
               recipient_party.customer
             elsif recipient_party.class == Customer
               recipient_party
             end
  customer.present? && (customer.closed? || customer.bankrupt?)
end

#has_failed_contact_point?Boolean

Returns:

  • (Boolean)


370
371
372
373
# File 'app/models/communication.rb', line 370

def has_failed_contact_point?
  # check if any of linked contact points have previously been marked as 'failed' (i.e. they bounced)
  communication_recipients.any? && ContactPoint.where(detail: communication_recipients.pluck(:detail), state: 'failed').exists?
end

#has_inactive_contact?Boolean

Returns:

  • (Boolean)


375
376
377
# File 'app/models/communication.rb', line 375

def has_inactive_contact?
  communication_recipients.joins(contact_point: :party).where(Party[:inactive].eq(true)).exists?
end

#has_recipients?Boolean

Returns:

  • (Boolean)


355
356
357
# File 'app/models/communication.rb', line 355

def has_recipients?
  communication_recipients.select(&:valid?).present?
end

#has_suppressed_recipients?Boolean

Returns:

  • (Boolean)


390
391
392
# File 'app/models/communication.rb', line 390

def has_suppressed_recipients?
  has_unsubscribed? || has_failed_contact_point? || has_inactive_contact? || has_closed_customer?
end

#has_unsubscribed?Boolean

Returns:

  • (Boolean)


363
364
365
366
367
368
# File 'app/models/communication.rb', line 363

def has_unsubscribed?
  return false if category == 'transactional' # cannot unsubscribe from transactional emails

  # check if they've unsubscribed to this type of email (if a category if present)
  category.present? && communication_recipients.any? { |cr| EmailPreference.where(email: cr.formatted_email_string).where("disable_#{category} is true").exists? }
end

#important?Boolean

This is used to determine if we notify the sender of a bounce or error

Returns:

  • (Boolean)


462
463
464
# File 'app/models/communication.rb', line 462

def important?
  category == 'transactional'
end

#inbound?Boolean

Returns:

  • (Boolean)


721
722
723
# File 'app/models/communication.rb', line 721

def inbound?
  direction == 'inbound'
end

#increment_publication_countersObject

Increment the counter of our publications, sort of a way to keep track of popularity



839
840
841
# File 'app/models/communication.rb', line 839

def increment_publication_counters
  publications.each { |p| p.increment!(:requested_counter) }
end

#is_not_campaign_delivery?Boolean

Returns:

  • (Boolean)


359
360
361
# File 'app/models/communication.rb', line 359

def is_not_campaign_delivery?
  resource_type != 'CampaignDelivery'
end

#is_triggered_by_mailbox?Boolean

Returns:

  • (Boolean)


194
195
196
# File 'app/models/communication.rb', line 194

def is_triggered_by_mailbox?
  triggered_by_mailbox.to_b
end

#literaturesObject

Alias for Uploads#literatures

Returns:

  • (Object)

    Uploads#literatures

See Also:



832
# File 'app/models/communication.rb', line 832

delegate :literatures, to: :uploads

#mark_associated_activities_completedObject



753
754
755
# File 'app/models/communication.rb', line 753

def mark_associated_activities_completed
  activities.each { |a| a.update(completion_datetime: Time.current, activity_result_type_id: ActivityResultTypeConstants::CMP) }
end

#no_recent_duplicate_template_sendObject (protected)

Guard against double-submit / double-click creating duplicate outbound emails.
If an identical template was already sent for the same resource within the last
30 seconds we reject the second save with a clear error message.
Only applies to template-driven, resource-scoped, outbound communications.



893
894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'app/models/communication.rb', line 893

def no_recent_duplicate_template_send
  return unless email_template_id.present?
  return unless resource_type.present? && resource_id.present?
  return if is_triggered_by_mailbox?

  duplicate = Communication.where(
    email_template_id: email_template_id,
    resource_type:     resource_type,
    resource_id:       resource_id,
    created_at:        30.seconds.ago..
  ).exists?

  errors.add(:base, "This template was just sent for this record. Please wait 30 seconds before sending again.") if duplicate
end

#not_unsubscribedObject



212
213
214
215
216
217
218
219
220
221
222
223
# File 'app/models/communication.rb', line 212

def not_unsubscribed
  return true if category.nil? or category == 'transactional'

  res = true
  communication_recipients.select { |cr| cr.category == 'email' }.each do |cr|
    if ep = EmailPreference.find_by(email: cr.detail) and ep.send(:"disable_#{category}") == true
      res = false
      errors.add(:base, "#{cr.detail} is unsubscribed from this type of email (#{category})")
    end
  end
  res
end

#outbound?Boolean

Returns:

  • (Boolean)


725
726
727
# File 'app/models/communication.rb', line 725

def outbound?
  direction == 'outbound'
end

#populate_category_from_templateObject



208
209
210
# File 'app/models/communication.rb', line 208

def populate_category_from_template
  self.category = email_template&.category
end

#populate_template_emailsObject



470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'app/models/communication.rb', line 470

def populate_template_emails
  return unless email_template

  if email_template.from.present?
    # this overrides any sender that may already be present
    self.sender = email_template.from
  elsif email_template.default_from.present?
    # this uses the default sender unless there's one already present
    self.sender = email_template.default_from unless sender.present? || sender_party_id.present?
  end
  build_recipients email_template.to
  build_recipients email_template.cc, 'cc'
  build_recipients email_template.bcc, 'bcc'
end

#preview_textObject



709
710
711
712
713
714
715
716
717
718
719
# File 'app/models/communication.rb', line 709

def preview_text
  if email_template && email_template.preview_text.present?
    <<-EOS
		<div style="display:none;font-size:1px;color:#333333;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;">
		  #{email_template.preview_text}
		</div>
    EOS
  else
    ''
  end
end

#provider_limitObject



819
820
821
# File 'app/models/communication.rb', line 819

def provider_limit
  20_480_000
end

#publicationsObject



834
835
836
# File 'app/models/communication.rb', line 834

def publications
  Item.joins(:literature).merge(literatures)
end

#recipient_partyParty

Returns:

See Also:



73
# File 'app/models/communication.rb', line 73

belongs_to :recipient_party, class_name: 'Party', inverse_of: :inbound_communications, optional: true

#releaseObject



198
199
200
201
202
203
204
205
206
# File 'app/models/communication.rb', line 198

def release
  return false unless (exception? || draft? || queued?) && can_release?

  if send_communication
    sent
  else
    failed
  end
end

#reply_to_options_for_selectObject



823
824
825
826
827
828
829
# File 'app/models/communication.rb', line 823

def reply_to_options_for_select
  if tracking_email_address.present?
    [tracking_email_address]
  else
    ['ar@warmlyyours.com', 'techteam@warmlyyours.com']
  end
end

#resourceResource

Returns:

  • (Resource)

See Also:



75
# File 'app/models/communication.rb', line 75

belongs_to :resource, polymorphic: true, optional: true

#resource_comboObject



684
685
686
# File 'app/models/communication.rb', line 684

def resource_combo
  "#{communication_resource.class.name}|#{communication_resource.id}" unless communication_resource.nil?
end

#resource_combo=(val) ⇒ Object



688
689
690
691
692
693
694
695
696
# File 'app/models/communication.rb', line 688

def resource_combo=(val)
  if val.present?
    rclass, rid = val.split('|')
    self.resource_type = rclass
    self.resource_id = rid
  else
    self.resource_type = nil, self.resource_id = nil
  end
end

#send_communicationObject



543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# File 'app/models/communication.rb', line 543

def send_communication
  if !skip_suppression_check.to_b && has_suppressed_recipients?
    mark_suppressed
    return false
  end

  # Mechanism to add a tracking email for every communication

  #####

  self.transmit_at = Time.current
  self.unique_id ||= SecureRandom.uuid

  email_options = { unique_id: }
  email_options[:uploads] = uploads
  # email_options[:temp_uploads] = self.temp_uploads

  if resource_type == 'SupportCase' and resource&.case_type == 'SmartService' and triggered_by_activity_id.present?
    acc = Activity.find(triggered_by_activity_id)
    email_options[:appointment] = resource.generate_service_calendar_event if acc.activity_type_id == ActivityTypeConstants::ONSITESERVICE
  end

  if resource.respond_to?(:tracking_email_address) && resource.tracking_email_address.present?
    rt = tracking_email_address
    self.reply_to = rt
  else
    rt = reply_to
  end

  email_options[:reply_to] = rt
  # Use effective_css to support Redactor 4 (returns empty CSS when redactor_4_ready, as styles are inlined)
  email_options[:inline_css] = email_template.try(:effective_css)
  email_options[:stylesheet] = external_stylesheet_for_email
  email_options[:template] = template_for_email
  email_options[:category] = category
  email_options[:show_mailing_address] = show_mailing_address?
  if mailbox_inbound_email_id.present?
    # This is to link emails from the same conversation so other emails clients group this email under the right thread instead of
    # having a standalone email
    inbound_email = ActionMailbox::InboundEmail.find_by(id: mailbox_inbound_email_id)
    if inbound_email
      reference = inbound_email.mail.message_id
      email_options[:references] = "<#{reference}>"
    end
  end
  if category.present? && category != 'transactional' and communication_recipients.any?(&:is_email?)
    to_formatted = communication_recipients.select { |cr| cr.is_email? and cr.email_method != 'cc' and cr.email_method != 'bcc' }.collect(&:detail).join(',')
    # locale: false ensures no locale prefix - Cloudflare worker will add appropriate locale based on user's country
    unsubscribe_link = UrlHelper.instance.(token: EmailPreference.encrypt_email(to_formatted), uid: unique_id, host: "https://#{WEB_HOSTNAME}", locale: false)
    email_options[:list_unsubscribe_link] = unsubscribe_link # unless body.include?('my_account/email_preferences?token=')
    # Check unsubscribes_mailbox for an understanding how this will be processed
    email_options[:list_unsubscribe_email] = "list-remove+#{unique_id}@#{Rails.application.config.x.email_domain}"
  end
  email_options[:skip_premailer] = should_skip_premailer?

  begin
    if communication_recipients.any?(&:is_email?)
      Retryable.retryable(tries: 3, sleep: lambda { |n| 4**n }, on: Retryable::TIMEOUT_CLASSES) do |_attempt_number, _exception|
        CommunicationMailer.email(
          sender_email,
          to(ContactPoint::EMAIL),
          subject,
          compliant_body,
          email_options.merge(
            cc:,
            bcc:,
            uploads:
          )
        ).deliver_now!
      end
    end
    if communication_recipients.any?(&:is_fax?)
      Retryable.retryable(tries: 3, sleep: lambda { |n| 4**n }, on: Retryable::TIMEOUT_CLASSES) do |_attempt_number, _exception|
        CommunicationMailer.email(
          sender_email,
          to(ContactPoint::FAX),
          "#{subject} /b /Portrait", # see https://www.interfax.net/en-us/dev/smtp/reference/271#attach
          compliant_body,
          email_options.merge(
            show_fax_unsubscribe: true,
            uploads: process_uploads_for_faxing
          )
        ).deliver_now!
      end
    end
    true
  rescue StandardError => e
    ErrorReporting.error(e, "From Communication #{id}")
    self.status_message = "Error releasing this communication: #{e.inspect}"
    raise(e) if Rails.env.development?

    false
  end
end

#sender_emailObject



520
521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'app/models/communication.rb', line 520

def sender_email
  email = self.class.parse_valid_email_address(email_template&.from)
  email ||= self.class.parse_valid_email_address(sender.email) if sender.respond_to?(:email)
  email ||= self.class.parse_valid_email_address(sender)
  email ||= self.class.parse_valid_email_address(sender_party.email) if sender_party.respond_to?(:email)
  email ||= DEFAULT_SENDER

  sender_name = sender_party.try(:full_name).presence
  if sender_name && !email.include?('<')
    Mail::Address.new(email).tap { |a| a.display_name = sender_name }.format
  else
    email
  end
end

#sender_partyParty

Returns:

See Also:



72
# File 'app/models/communication.rb', line 72

belongs_to :sender_party, class_name: 'Party', inverse_of: :outbound_communications, optional: true

#should_be_suppressed?Boolean

Returns:

  • (Boolean)


394
395
396
397
398
# File 'app/models/communication.rb', line 394

def should_be_suppressed?
  outbound? &&
    category != 'transactional' &&
    has_suppressed_recipients?
end

#should_skip_premailer?Boolean

Skip Premailer CSS inlining for:

  1. Templates with disable_premailer explicitly checked
  2. Redactor 4 ready templates (styles are already inlined by R4's email plugin)
  3. Any content that starts with DOCTYPE (R4 content loaded into a plain communication)

Returns:

  • (Boolean)


665
666
667
668
669
670
671
# File 'app/models/communication.rb', line 665

def should_skip_premailer?
  return true if email_template&.disable_premailer&.to_b
  return true if email_template&.redactor_4_ready?
  return true if body_for_email.to_s.strip.start_with?('<!DOCTYPE')

  false
end

#show_mailing_address?Boolean

Returns:

  • (Boolean)


535
536
537
538
539
540
541
# File 'app/models/communication.rb', line 535

def show_mailing_address?
  if Campaign::CATEGORIES.include?(category)
    !(body.include?('590 Telser') || body.include?('300 Granton'))
  else
    false
  end
end

#sourceSource

Returns:

See Also:



77
# File 'app/models/communication.rb', line 77

belongs_to :source, optional: true

#template_for_emailObject



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
# File 'app/models/communication.rb', line 644

def template_for_email
  # Received HTML emails store a full document — render it passthrough, no wrapper.
  if is_triggered_by_mailbox? && compliant_body.to_s.lstrip.start_with?('<')
    return 'v4'
  end

  return EmailTemplate::DEFAULT_TEMPLATE unless email_template.present?

  # Use v4 layout when we have a full HTML document (body_email or legacy body with DOCTYPE)
  raw_body = body_for_email.to_s.strip
  if raw_body.start_with?('<!DOCTYPE')
    'v4'
  else
    email_template.effective_template
  end
end

#to(category = [ContactPoint::FAX, ContactPoint::EMAIL]) ⇒ Object

default finding all categories



445
446
447
# File 'app/models/communication.rb', line 445

def to(category = [ContactPoint::FAX, ContactPoint::EMAIL]) # default finding all categories
  self.class.process_recipients(communication_recipients.where(category:).where("COALESCE(communication_recipients.email_method,'') NOT IN ('cc','bcc')"))
end

#to_sObject



431
432
433
# File 'app/models/communication.rb', line 431

def to_s
  "Communication #{id}"
end

#too_big?Boolean

Returns:

  • (Boolean)


466
467
468
# File 'app/models/communication.rb', line 466

def too_big?
  total_attachment_size > 10.megabytes
end

#total_attachment_sizeObject



457
458
459
# File 'app/models/communication.rb', line 457

def total_attachment_size
  uploads.map { |u| u.try(:attachment).try(:size) || 0 }.sum
end

#tracking_email_addressObject



757
758
759
760
761
762
763
764
# File 'app/models/communication.rb', line 757

def tracking_email_address
  return unless tracking_address = resource.try(:tracking_email_address)

  address = tracking_address
  sender_name = sender_party&.full_name
  address = "#{sender_name} <#{address}>" if sender_name
  address
end

#triggered_activityActivity

Returns:

See Also:



76
# File 'app/models/communication.rb', line 76

belongs_to :triggered_activity, class_name: 'Activity', optional: true

#uploadsActiveRecord::Relation<Upload>

Returns:

  • (ActiveRecord::Relation<Upload>)

See Also:



82
# File 'app/models/communication.rb', line 82

has_and_belongs_to_many :uploads, class_name: 'Upload'

#validate_attachment_limitsObject (protected)



885
886
887
# File 'app/models/communication.rb', line 885

def validate_attachment_limits
  errors.add(:base, "Attachments are too large and exceed the mail provider's limit (~20Mb)") if attachments_too_large?
end

#versions_for_audit_trail(_params = {}) ⇒ Object



843
844
845
846
847
848
849
850
851
852
# File 'app/models/communication.rb', line 843

def versions_for_audit_trail(_params = {})
  query_sql = %q{
                (item_type = 'Communication' and item_id = :id)
                OR (
                  item_type = 'CommunicationRecipient'
                    AND reference_data @> '{"communication_id": :id}'
                )
              }
  RecordVersion.where(query_sql, id:)
end