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 :enum 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

Modules: CanaryToken Classes: ClickBotScorer, EventParser

Constant Summary collapse

VALID_TRANSMIT_METHODS =

Valid transmit methods.

[ContactPoint::EMAIL, ContactPoint::FAX].freeze
DEFAULT_SENDER =

Default sender.

'info@warmlyyours.com'
MIN_EMBEDDABLE_BODY_LENGTH =

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

80
ZOOM_SCHEDULER_PATTERN =
%r{https?://(?:scheduler\.zoom\.us|zoom\.us/(?:s|scheduler|meeting/schedule))/}i

Constants included from Models::Embeddable

Models::Embeddable::MAX_CONTENT_LENGTH

Constants included from Models::Auditable

Models::Auditable::ALWAYS_IGNORED

Constants included from Schedulable

Schedulable::SIMPLE_FORM_OPTIONS

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 Schedulable

config

Methods included from Models::AfterCommittable

#after_commit

Methods included from Models::EventPublishable

#publish_event

Instance Attribute Details

#appointmentObject

Returns the value of attribute appointment.



96
97
98
# File 'app/models/communication.rb', line 96

def appointment
  @appointment
end

#bodyObject (readonly)



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

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

#check_subscription_preferencesObject

Returns the value of attribute check_subscription_preferences.



96
97
98
# File 'app/models/communication.rb', line 96

def check_subscription_preferences
  @check_subscription_preferences
end

#existing_upload_idsObject

Returns the value of attribute existing_upload_ids.



96
97
98
# File 'app/models/communication.rb', line 96

def existing_upload_ids
  @existing_upload_ids
end

#multi_emailsObject

Returns the value of attribute multi_emails.



96
97
98
# File 'app/models/communication.rb', line 96

def multi_emails
  @multi_emails
end

#skip_suppression_checkObject

Returns the value of attribute skip_suppression_check.



96
97
98
# File 'app/models/communication.rb', line 96

def skip_suppression_check
  @skip_suppression_check
end

#subjectObject (readonly)



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

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

Class Method Details



791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
# File 'app/models/communication.rb', line 791

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.presence&.to_query)
    # 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:



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

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

.default_signature(employee = nil) ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'app/models/communication.rb', line 249

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



357
358
359
360
361
362
363
364
365
366
367
# File 'app/models/communication.rb', line 357

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



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

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:



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

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:



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

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:



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

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

.parse_valid_email_address(email) ⇒ Object



524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'app/models/communication.rb', line 524

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:



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

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

.process_recipients(rel_cr) ⇒ Object



441
442
443
444
445
446
447
448
449
# File 'app/models/communication.rb', line 441

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:



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

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

.signature_to_html(text = '') ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'app/models/communication.rb', line 320

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



245
246
247
# File 'app/models/communication.rb', line 245

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



310
311
312
313
314
315
316
317
318
# File 'app/models/communication.rb', line 310

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:



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

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:



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

has_many :activities, dependent: :nullify

#attachments_too_large?Boolean

Returns:

  • (Boolean)


877
878
879
# File 'app/models/communication.rb', line 877

def attachments_too_large?
  total_attachment_size > provider_limit
end

#bccObject



474
475
476
# File 'app/models/communication.rb', line 474

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).



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

def body_for_email
  body_email.presence || body
end

#build_recipients(email, email_method = nil) ⇒ Object



506
507
508
509
510
511
512
513
# File 'app/models/communication.rb', line 506

def build_recipients(email, email_method = nil)
  return if email.blank?

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

#can_be_edited?Boolean

Communications can only be edited while in draft state

Returns:

  • (Boolean)


210
211
212
# File 'app/models/communication.rb', line 210

def can_be_edited?
  draft?
end

#can_release?Boolean

Returns:

  • (Boolean)


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

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

Invisible per-recipient "canary" link for security-scanner detection. Only for
marketing/campaign sends (category != 'transactional') with a single 'to' email
recipient — campaign emails are one Communication per recipient. clicktracking="off"
keeps SendGrid from rewriting it, so a link scanner that fetches every href hits
our own API (Api::V1::EmailCanaryController) directly; no human can see an invisible
link. Returns nil when no canary applies. See Communication::ClickBotScorer.

Returns:

  • (String, nil)


743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
# File 'app/models/communication.rb', line 743

def canary_link_html
  return if category.blank? || category == 'transactional'

  recipient = single_email_recipient
  return unless recipient&.id

  url = UrlHelper.instance.v1_email_canary_url(
    token: Communication::CanaryToken.encode(recipient.id),
    host: "https://#{API_HOSTNAME}"
  )
  "<a clicktracking=\"off\" href=\"#{url}\" style=\"display:none;font-size:0;line-height:0;color:transparent\" aria-hidden=\"true\">.</a>"
rescue StandardError => e
  # The canary is non-critical instrumentation — it must never break an email
  # send. Log and ship the email without it.
  ErrorReporting.error(e, "canary_link_html Communication ##{id}")
  nil
end

#ccObject



470
471
472
# File 'app/models/communication.rb', line 470

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

#clear_bounce_listObject



515
516
517
518
519
520
521
522
# File 'app/models/communication.rb', line 515

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



828
829
830
831
832
833
834
835
836
# File 'app/models/communication.rb', line 828

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 if reply_to_parent_id.blank?

  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 })


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

has_many :communication_recipients, inverse_of: :communication

#communication_resourceObject



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

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

#compliant_bodyObject



729
730
731
732
733
# File 'app/models/communication.rb', line 729

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



925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
# File 'app/models/communication.rb', line 925

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



838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
# File 'app/models/communication.rb', line 838

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.find { |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



867
868
869
870
# File 'app/models/communication.rb', line 867

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

#custom_resource_queued_actionsObject



857
858
859
860
# File 'app/models/communication.rb', line 857

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

#custom_resource_sent_actionsObject



862
863
864
865
# File 'app/models/communication.rb', line 862

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

#custom_resource_suppressed_actionsObject



872
873
874
875
# File 'app/models/communication.rb', line 872

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

#deep_dupObject



137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'app/models/communication.rb', line 137

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



433
434
435
436
437
438
439
# File 'app/models/communication.rb', line 433

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



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

def default_resource_for_select
  return [] unless communication_resource

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

#email_templateEmailTemplate



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

belongs_to :email_template, optional: true

#embedding_content_changed?Boolean

Returns:

  • (Boolean)


941
942
943
# File 'app/models/communication.rb', line 941

def embedding_content_changed?
  saved_change_to_body? || saved_change_to_subject?
end

#enqueue_release_workerObject



455
456
457
458
459
460
461
462
463
# File 'app/models/communication.rb', line 455

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



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

def external_stylesheet_for_email
  return if email_template.blank?

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

#feed_historiesActiveRecord::Relation<FeedHistory>

Returns:

See Also:



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

has_many :feed_histories, dependent: :destroy

#fill_suppressed_reasonObject



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

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)


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

def has_closed_customer?
  return false if recipient_party.nil?

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

#has_failed_contact_point?Boolean

Returns:

  • (Boolean)


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

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)


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

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

#has_recipients?Boolean

Returns:

  • (Boolean)


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

def has_recipients?
  communication_recipients.any?(&:valid?)
end

#has_suppressed_recipients?Boolean

Returns:

  • (Boolean)


410
411
412
# File 'app/models/communication.rb', line 410

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

#has_unsubscribed?Boolean

Returns:

  • (Boolean)


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

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)


483
484
485
# File 'app/models/communication.rb', line 483

def important?
  category == 'transactional'
end

#inbound?Boolean

Returns:

  • (Boolean)


783
784
785
# File 'app/models/communication.rb', line 783

def inbound?
  direction == 'inbound'
end

#increment_publication_countersObject

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



901
902
903
# File 'app/models/communication.rb', line 901

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

#is_not_campaign_delivery?Boolean

Returns:

  • (Boolean)


379
380
381
# File 'app/models/communication.rb', line 379

def is_not_campaign_delivery?
  resource_type != 'CampaignDelivery'
end

#is_triggered_by_mailbox?Boolean

Returns:

  • (Boolean)


214
215
216
# File 'app/models/communication.rb', line 214

def is_triggered_by_mailbox?
  triggered_by_mailbox.to_b
end

#literaturesObject

Alias for Uploads#literatures

Returns:

  • (Object)

    Uploads#literatures

See Also:



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

delegate :literatures, to: :uploads

#mark_associated_activities_completedObject



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

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.



964
965
966
967
968
969
970
971
972
973
974
975
976
977
# File 'app/models/communication.rb', line 964

def no_recent_duplicate_template_send
  return if email_template_id.blank?
  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


953
954
955
956
957
958
# File 'app/models/communication.rb', line 953

def no_zoom_scheduler_links
  text = "#{body} #{body_email} #{subject}"
  return unless text.match?(ZOOM_SCHEDULER_PATTERN)

  errors.add(:body, "contains a Zoom scheduler link. Zoom scheduler is no longer in use — please use Heatwave Scheduler instead")
end

#not_unsubscribedObject



232
233
234
235
236
237
238
239
240
241
242
243
# File 'app/models/communication.rb', line 232

def not_unsubscribed
  return true if category.nil? || (category == 'transactional')

  res = true
  communication_recipients.select { |cr| cr.category == 'email' }.each do |cr|
    if (ep = EmailPreference.find_by(email: cr.detail)) && (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)


787
788
789
# File 'app/models/communication.rb', line 787

def outbound?
  direction == 'outbound'
end

#populate_category_from_templateObject



228
229
230
# File 'app/models/communication.rb', line 228

def populate_category_from_template
  self.category = email_template&.category
end

#populate_template_emailsObject



491
492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'app/models/communication.rb', line 491

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



771
772
773
774
775
776
777
778
779
780
781
# File 'app/models/communication.rb', line 771

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



881
882
883
# File 'app/models/communication.rb', line 881

def provider_limit
  20_480_000
end

#publicationsObject



896
897
898
# File 'app/models/communication.rb', line 896

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

#recipient_partyParty

Returns:

See Also:



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

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

#releaseObject



218
219
220
221
222
223
224
225
226
# File 'app/models/communication.rb', line 218

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

  if send_communication
    sent
  else
    failed
  end
end

#reply_to_options_for_selectObject



885
886
887
888
889
890
891
# File 'app/models/communication.rb', line 885

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:



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

belongs_to :resource, polymorphic: true, optional: true

#resource_comboObject



710
711
712
# File 'app/models/communication.rb', line 710

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

#resource_combo=(val) ⇒ Object



714
715
716
717
718
719
720
721
722
# File 'app/models/communication.rb', line 714

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



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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# File 'app/models/communication.rb', line 564

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') && (resource&.case_type == 'SmartService') && 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' && communication_recipients.any?(&:is_email?)
    to_formatted = communication_recipients.select { |cr| cr.is_email? and cr.email_method != 'cc' and cr.email_method != 'bcc' }.map(&: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?

  # Append the invisible security-scanner canary link to the email body
  # (campaign/marketing single-recipient sends only — see #canary_link_html).
  email_body = compliant_body
  if email_body.present? && (canary = canary_link_html)
    email_body = "#{email_body}#{canary}"
  end

  begin
    if communication_recipients.any?(&:is_email?)
      Retryable.retryable(tries: 3, sleep: ->(n) { 4**n }, on: Retryable::TIMEOUT_CLASSES) do |_attempt_number, _exception|
        CommunicationMailer.email(
          sender_email,
          to(ContactPoint::EMAIL),
          subject,
          email_body,
          email_options.merge(
            cc:,
            bcc:,
            uploads:
          )
        ).deliver_now!
      end
    end
    if communication_recipients.any?(&:is_fax?)
      Retryable.retryable(tries: 3, sleep: ->(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



541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'app/models/communication.rb', line 541

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.exclude?('<')
    Mail::Address.new(email).tap { |a| a.display_name = sender_name }.format
  else
    email
  end
end

#sender_partyParty

Returns:

See Also:



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

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

#should_be_suppressed?Boolean

Returns:

  • (Boolean)


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

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)


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

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)


556
557
558
559
560
561
562
# File 'app/models/communication.rb', line 556

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

#single_email_recipientCommunicationRecipient?

The sole 'to' email recipient, or nil unless there's exactly one (cc/bcc
excluded). The canary is per-recipient, so it only applies to single-recipient
(campaign) sends.

Returns:



766
767
768
769
# File 'app/models/communication.rb', line 766

def single_email_recipient
  to = communication_recipients.select { |cr| cr.is_email? && cr.email_method != 'cc' && cr.email_method != 'bcc' }
  to.one? ? to.first : nil
end

#sourceSource

Returns:

See Also:



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

belongs_to :source, optional: true

#template_for_emailObject



672
673
674
675
676
677
678
679
680
681
682
683
684
685
# File 'app/models/communication.rb', line 672

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

  return EmailTemplate::DEFAULT_TEMPLATE if email_template.blank?

  # 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



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

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

#to_sObject



451
452
453
# File 'app/models/communication.rb', line 451

def to_s
  "Communication #{id}"
end

#too_big?Boolean

Returns:

  • (Boolean)


487
488
489
# File 'app/models/communication.rb', line 487

def too_big?
  total_attachment_size > 10.megabytes
end

#total_attachment_sizeObject



478
479
480
# File 'app/models/communication.rb', line 478

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

#tracking_email_addressObject



819
820
821
822
823
824
825
826
# File 'app/models/communication.rb', line 819

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:



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

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

#uploadsActiveRecord::Relation<Upload>

Returns:

  • (ActiveRecord::Relation<Upload>)

See Also:



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

has_and_belongs_to_many :uploads, class_name: 'Upload'

#validate_attachment_limitsObject (protected)



947
948
949
# File 'app/models/communication.rb', line 947

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



905
906
907
908
909
910
911
912
913
914
# File 'app/models/communication.rb', line 905

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_json
                )
              }
  RecordVersion.where(query_sql, id:, communication_id_json: { communication_id: id }.to_json)
end