Class: Communication
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)
rubocop:disable Metrics/ClassLength -- pre-existing god-class (726 lines); decompose separately
Defined Under Namespace
Modules: CanaryToken
Classes: ClickBotScorer, EventParser
Constant Summary
collapse
- VALID_TRANSMIT_METHODS =
[ContactPoint::EMAIL, ContactPoint::FAX].freeze
- DEFAULT_SENDER =
'info@warmlyyours.com'
- MIN_EMBEDDABLE_BODY_LENGTH =
Minimum source-body length for a communication to be worth embedding.
HTML and quoted-history cleanup can leave a shorter reply; its subject and
SupportCase metadata still carry useful retrieval context.
80
- EMBEDDING_CONTENT_ATTRIBUTES =
%w[
body subject direction sender sender_party_id recipient_party_id
resource_type resource_id category
].freeze
- ZOOM_SCHEDULER_PATTERN =
%r{https?://(?:scheduler\.zoom\.us|zoom\.us/(?:s|scheduler|meeting/schedule))/}i
Models::Embeddable::MAX_CONTENT_LENGTH
Models::Auditable::ALWAYS_IGNORED
Models::Schedulable::SIMPLE_FORM_OPTIONS
Instance Attribute Summary collapse
#creator, #updater
#content_embeddings
Has and belongs to many
collapse
Delegated Instance Attributes
collapse
Class Method Summary
collapse
Instance Method Summary
collapse
-
#attachments_too_large? ⇒ Boolean
-
#bcc ⇒ Object
-
#body_for_email ⇒ Object
Body used for sending: full email document (body_email) when present, else editor content (body).
-
#body_without_editor_config ⇒ Object
Redactor 4 editor source keeps config chrome — .email-options (JSON) and .email-style (raw CSS) — that getEmail() consumes when the client captures body_email.
-
#build_recipients(email, email_method = nil) ⇒ Object
-
#can_be_edited? ⇒ Boolean
Communications can only be edited while in draft state.
-
#can_release? ⇒ Boolean
-
#canary_link_html ⇒ String?
Invisible per-recipient "canary" link for security-scanner detection.
-
#cc ⇒ Object
-
#clear_bounce_list ⇒ Object
-
#close_reply_activity ⇒ Object
-
#closed_or_bankrupt_customer ⇒ Customer?
The recipient's customer when it is closed or bankrupt, else nil.
-
#communication_resource ⇒ Object
-
#compliant_body ⇒ Object
-
#content_for_embedding(_content_type = :primary) ⇒ Object
-
#create_email_activities ⇒ Object
-
#custom_resource_exception_actions ⇒ Object
-
#custom_resource_queued_actions ⇒ Object
-
#custom_resource_sent_actions ⇒ Object
-
#custom_resource_suppressed_actions ⇒ Object
-
#deep_dup ⇒ Object
-
#default_recipient_list ⇒ Object
-
#default_resource_for_select ⇒ Object
-
#embedding_content_changed? ⇒ Boolean
-
#enqueue_release_worker ⇒ Object
-
#external_stylesheet_for_email ⇒ Object
rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity.
-
#failed_recipient_details ⇒ Array<String>
Recipient email addresses whose contact point previously bounced (state 'failed').
-
#fill_suppressed_reason ⇒ String
Set a human-readable status_message naming the specific recipient(s) that caused the send to be suppressed, so the CRM banner explains why delivery failed and to whom rather than a generic sentence.
-
#has_closed_customer? ⇒ Boolean
True when the recipient's customer is closed or bankrupt.
-
#has_failed_contact_point? ⇒ Boolean
True when any recipient address previously bounced.
-
#has_inactive_contact? ⇒ Boolean
True when any recipient is linked to an inactive party.
-
#has_recipients? ⇒ Boolean
-
#has_suppressed_recipients? ⇒ Boolean
True when any recipient trips a suppression guard.
-
#has_unsubscribed? ⇒ Boolean
True when any recipient unsubscribed from this category.
-
#important? ⇒ Boolean
This is used to determine if we notify the sender of a bounce or error.
-
#inactive_recipient_details ⇒ Array<String>
Recipient email addresses linked to a party flagged inactive.
-
#inbound? ⇒ Boolean
-
#increment_publication_counters ⇒ Object
Increment the counter of our publications, sort of a way to keep track of popularity.
-
#is_not_campaign_delivery? ⇒ Boolean
-
#is_triggered_by_mailbox? ⇒ Boolean
-
#mark_associated_activities_completed ⇒ Object
-
#no_recent_duplicate_template_send ⇒ Object
protected
Guard against double-submit / double-click creating duplicate outbound emails.
-
#no_zoom_scheduler_links ⇒ Object
protected
-
#not_unsubscribed ⇒ Object
-
#outbound? ⇒ Boolean
-
#populate_category_from_template ⇒ Object
-
#populate_template_emails ⇒ Object
-
#preview_text ⇒ Object
-
#provider_limit ⇒ Object
-
#publications ⇒ Object
-
#release ⇒ Object
-
#reply_to_options_for_select ⇒ Object
-
#resource_combo ⇒ Object
-
#resource_combo=(val) ⇒ Object
-
#send_communication ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity -- pre-existing god-method (121+ on master); out of scope to decompose here.
-
#sender_email ⇒ Object
-
#should_be_suppressed? ⇒ Boolean
Whether an outbound, non-transactional send should be held.
-
#should_skip_premailer? ⇒ Boolean
Skip Premailer CSS inlining for: 1.
-
#show_mailing_address? ⇒ Boolean
-
#single_email_recipient ⇒ CommunicationRecipient?
The sole 'to' email recipient, or nil unless there's exactly one (cc/bcc excluded).
-
#template_for_email ⇒ Object
-
#to(category = [ContactPoint::FAX, ContactPoint::EMAIL]) ⇒ Object
default finding all categories.
-
#to_s ⇒ Object
-
#too_big? ⇒ Boolean
-
#total_attachment_size ⇒ Object
-
#tracking_email_address ⇒ Object
-
#unsubscribed_recipient_details ⇒ Array<String>
Recipient email addresses that have unsubscribed from this email's category.
-
#validate_attachment_limits ⇒ Object
protected
-
#versions_for_audit_trail(_params = {}) ⇒ Object
embeddable_content_types, #embeddable_locales, #embedding_content_hash, #embedding_current?, #embedding_eligible?, 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, with_shape_lock
#all_skipped_columns, #audit_reference_data, #should_not_save_version, #stamp_record
#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
ransackable_associations, ransackable_attributes, ransackable_scopes, ransortable_attributes, #to_relation
config
#after_commit
#publish_event
Instance Attribute Details
#appointment ⇒ Object
Returns the value of attribute appointment.
97
98
99
|
# File 'app/models/communication.rb', line 97
def appointment
@appointment
end
|
#body ⇒ Object
125
|
# File 'app/models/communication.rb', line 125
validates :body, :subject, presence: { unless: proc { archived && is_triggered_by_mailbox? } }
|
#check_subscription_preferences ⇒ Object
Returns the value of attribute check_subscription_preferences.
97
98
99
|
# File 'app/models/communication.rb', line 97
def check_subscription_preferences
@check_subscription_preferences
end
|
#existing_upload_ids ⇒ Object
Returns the value of attribute existing_upload_ids.
97
98
99
|
# File 'app/models/communication.rb', line 97
def existing_upload_ids
@existing_upload_ids
end
|
#multi_emails ⇒ Object
Returns the value of attribute multi_emails.
97
98
99
|
# File 'app/models/communication.rb', line 97
def multi_emails
@multi_emails
end
|
#skip_suppression_check ⇒ Object
Returns the value of attribute skip_suppression_check.
97
98
99
|
# File 'app/models/communication.rb', line 97
def skip_suppression_check
@skip_suppression_check
end
|
#subject ⇒ Object
125
|
# File 'app/models/communication.rb', line 125
validates :body, :subject, presence: { unless: proc { archived && is_triggered_by_mailbox? } }
|
Class Method Details
.append_source_to_links(cbody, referral_code) ⇒ Object
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
|
# File 'app/models/communication.rb', line 837
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('/')
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[:referral_code] = referral_code if referral_code.present?
uri.query = (merged_params.presence&.to_query)
node['href'] = uri.to_s end
html_doc.to_html.gsub('&', '&')
end
|
.campaign_only ⇒ ActiveRecord::Relation<Communication>
A relation of Communications that are campaign only. Active Record Scope
95
|
# File 'app/models/communication.rb', line 95
scope :campaign_only, -> { where(resource_type: 'CampaignDelivery') }
|
.default_signature(employee = nil) ⇒ Object
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
|
# File 'app/models/communication.rb', line 250
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'
parts.join("\n")
end
|
.embeddable ⇒ ActiveRecord::Relation<Communication>
A relation of Communications that are embeddable. Active Record Scope
978
979
980
981
982
|
# File 'app/models/communication.rb', line 978
scope :embeddable, lambda {
where(category: nil)
.where("communications.body IS NOT NULL AND communications.body <> ''")
.where('LENGTH(communications.body) >= ?', MIN_EMBEDDABLE_BODY_LENGTH)
}
|
.most_recent_first ⇒ ActiveRecord::Relation<Communication>
A relation of Communications that are most recent first. Active Record Scope
90
|
# File 'app/models/communication.rb', line 90
scope :most_recent_first, -> { order('COALESCE(communications.transmit_at, communications.created_at) DESC') }
|
.non_campaign ⇒ ActiveRecord::Relation<Communication>
A relation of Communications that are non campaign. Active Record Scope
94
|
# File 'app/models/communication.rb', line 94
scope :non_campaign, -> { where("resource_type is null or resource_type <> 'CampaignDelivery'") }
|
.parse_valid_email_address(email) ⇒ Object
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
|
# File 'app/models/communication.rb', line 536
def self.parse_valid_email_address(email)
return nil unless email.is_a?(String) && email.include?('@')
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
truemail_result = Truemail.validate(email)
return email if truemail_result
nil
end
|
.problem_state ⇒ ActiveRecord::Relation<Communication>
A relation of Communications that are problem state. Active Record Scope
.process_recipients(rel_cr) ⇒ Object
453
454
455
456
457
458
459
460
461
|
# File 'app/models/communication.rb', line 453
def self.process_recipients(rel_cr)
to_array = []
rel_cr.each do |cr|
address = Mail::Address.new cr.formatted_email_string address.display_name = cr.name if cr.name.present? to_array << address.format end
to_array.empty? ? nil : to_array.uniq.compact.join(',')
end
|
.sent_today ⇒ ActiveRecord::Relation<Communication>
A relation of Communications that are sent today. Active Record Scope
92
|
# File 'app/models/communication.rb', line 92
scope :sent_today, -> { where(state: 'sent').where(transmit_at: Date.current.beginning_of_day...) }
|
.state_for_select ⇒ Object
246
247
248
|
# File 'app/models/communication.rb', line 246
def self.state_for_select
Communication.state_machines[:state].states.map { |s| [s.name.to_s.titleize, s.name.to_s] }
end
|
.with_a_recipient_in_state ⇒ ActiveRecord::Relation<Communication>
A relation of Communications that are with a recipient in state. Active Record Scope
91
|
# File 'app/models/communication.rb', line 91
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
#activities ⇒ ActiveRecord::Relation<Activity>
85
|
# File 'app/models/communication.rb', line 85
has_many :activities, dependent: :nullify
|
#attachments_too_large? ⇒ Boolean
923
924
925
|
# File 'app/models/communication.rb', line 923
def attachments_too_large?
total_attachment_size > provider_limit
end
|
#bcc ⇒ Object
486
487
488
|
# File 'app/models/communication.rb', line 486
def bcc
self.class.process_recipients(communication_recipients.where(email_method: 'bcc'))
end
|
#body_for_email ⇒ Object
Body used for sending: full email document (body_email) when present, else editor content (body).
749
750
751
|
# File 'app/models/communication.rb', line 749
def body_for_email
body_email.presence || body_without_editor_config
end
|
#body_without_editor_config ⇒ Object
Redactor 4 editor source keeps config chrome — .email-options (JSON) and
.email-style (raw CSS) — that getEmail() consumes when the client captures
body_email. When that capture failed (JS error, draft/scheduled transmit),
the fallback send would render the chrome as visible text in the customer's
inbox, so strip it and surface the otherwise-silent client failure.
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
|
# File 'app/models/communication.rb', line 758
def body_without_editor_config
return body unless body.to_s.match?(/email-options|email-style/)
@body_without_editor_config ||= begin
fragment = Email::ContentRules::Helpers.parse(body)
nodes = fragment.css('.email-options, .email-style')
if nodes.any?
nodes.each(&:unlink)
ErrorReporting.warning('Communication body_email missing at send — stripped Redactor 4 editor config from body',
communication_id: id, email_template_id: email_template_id)
fragment.to_html
else
body
end
end
end
|
#build_recipients(email, email_method = nil) ⇒ Object
518
519
520
521
522
523
524
525
|
# File 'app/models/communication.rb', line 518
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
211
212
213
|
# File 'app/models/communication.rb', line 211
def can_be_edited?
draft?
end
|
#can_release? ⇒ Boolean
311
312
313
314
315
|
# File 'app/models/communication.rb', line 311
def can_release?
has_recipients? &&
(transmit_at.nil? || (Time.current > transmit_at)) &&
valid?
end
|
#canary_link_html ⇒ String?
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.
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
|
# File 'app/models/communication.rb', line 789
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
ErrorReporting.error(e, "canary_link_html Communication ##{id}")
nil
end
|
#cc ⇒ Object
482
483
484
|
# File 'app/models/communication.rb', line 482
def cc
self.class.process_recipients(communication_recipients.where(email_method: 'cc'))
end
|
#clear_bounce_list ⇒ Object
527
528
529
530
531
532
533
534
|
# File 'app/models/communication.rb', line 527
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_activity ⇒ Object
874
875
876
877
878
879
880
881
882
|
# File 'app/models/communication.rb', line 874
def close_reply_activity
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
|
#closed_or_bankrupt_customer ⇒ Customer?
The recipient's customer when it is closed or bankrupt, else nil.
Memoized (nil-aware) so the suppression guard and fill_suppressed_reason
share one lookup.
400
401
402
403
404
405
406
407
408
409
|
# File 'app/models/communication.rb', line 400
def closed_or_bankrupt_customer
return @closed_or_bankrupt_customer if defined?(@closed_or_bankrupt_customer)
customer = if recipient_party.instance_of?(Contact)
recipient_party.customer
elsif recipient_party.instance_of?(Customer)
recipient_party
end
@closed_or_bankrupt_customer = (customer if customer.present? && (customer.closed? || customer.bankrupt?))
end
|
#communication_recipients ⇒ ActiveRecord::Relation<CommunicationRecipient>
Validations (unless => proc { is_triggered_by_mailbox? } ):
-
Nested_attributes_uniqueness
({ field: :detail })
86
|
# File 'app/models/communication.rb', line 86
has_many :communication_recipients, inverse_of: :communication
|
#communication_resource ⇒ Object
723
724
725
|
# File 'app/models/communication.rb', line 723
def communication_resource
resource.present? && resource.respond_to?(:communication_resource) ? resource.communication_resource : resource
end
|
#compliant_body ⇒ Object
775
776
777
778
779
|
# File 'app/models/communication.rb', line 775
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
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
|
# File 'app/models/communication.rb', line 984
def content_for_embedding(_content_type = :primary)
return nil if category.present?
return nil if body.blank? || body.length < MIN_EMBEDDABLE_BODY_LENGTH
text = stripped_body_for_embedding
parts = []
direction_description = case direction
when 'inbound' then 'Inbound from customer'
when 'outbound' then 'Outbound from staff'
else 'Unspecified'
end
parts << "Direction: #{direction_description}"
parts << "Subject: #{subject.strip}" if subject.present?
sender_name = sender_party&.full_name.presence || sender.presence
parts << "From: #{sender_name}" if sender_name
parts << "To: #{recipient_party&.full_name}" if recipient_party
parts << "Relates to: #{resource_type} ##{resource_id}" if resource_type.present?
parts << text.first(2000) if text.present?
parts.compact.join("\n")
end
|
#create_email_activities ⇒ Object
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
|
# File 'app/models/communication.rb', line 884
def create_email_activities
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_actions ⇒ Object
913
914
915
916
|
# File 'app/models/communication.rb', line 913
def custom_resource_exception_actions
resource.post_communication_exception_hook if resource.respond_to?(:post_communication_exception_hook)
true
end
|
#custom_resource_queued_actions ⇒ Object
903
904
905
906
|
# File 'app/models/communication.rb', line 903
def custom_resource_queued_actions
resource.post_communication_queued_hook if resource.respond_to?(:post_communication_queued_hook)
true
end
|
#custom_resource_sent_actions ⇒ Object
908
909
910
911
|
# File 'app/models/communication.rb', line 908
def custom_resource_sent_actions
resource.post_communication_sent_hook if resource.respond_to?(:post_communication_sent_hook)
true
end
|
#custom_resource_suppressed_actions ⇒ Object
918
919
920
921
|
# File 'app/models/communication.rb', line 918
def custom_resource_suppressed_actions
resource.post_communication_suppressed_hook if resource.respond_to?(:post_communication_suppressed_hook)
true
end
|
#deep_dup ⇒ Object
138
139
140
141
142
143
144
145
146
147
148
149
150
|
# File 'app/models/communication.rb', line 138
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_list ⇒ Object
445
446
447
448
449
450
451
|
# File 'app/models/communication.rb', line 445
def default_recipient_list
return nil unless resource || recipient_party
ContactPoint::AddressBookBuilder.options_for_select(resource:, party: recipient_party, group_results: false)
end
|
#default_resource_for_select ⇒ Object
727
728
729
730
731
732
|
# File 'app/models/communication.rb', line 727
def default_resource_for_select
return [] unless communication_resource
formatter = Activity::ResourceList.build_formatter(communication_resource)
[[formatter.display, formatter.identifier]]
end
|
80
|
# File 'app/models/communication.rb', line 80
belongs_to :email_template, optional: true
|
#embedding_content_changed? ⇒ Boolean
1006
1007
1008
|
# File 'app/models/communication.rb', line 1006
def embedding_content_changed?
EMBEDDING_CONTENT_ATTRIBUTES.any? { |attribute| saved_change_to_attribute?(attribute) }
end
|
#enqueue_release_worker ⇒ Object
467
468
469
470
471
472
473
474
475
|
# File 'app/models/communication.rb', line 467
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_email ⇒ Object
rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
690
691
692
693
694
|
# File 'app/models/communication.rb', line 690
def external_stylesheet_for_email
return if email_template.blank?
email_template.stylesheet end
|
#failed_recipient_details ⇒ Array<String>
Recipient email addresses whose contact point previously bounced (state 'failed').
Memoized so the suppression guard and fill_suppressed_reason share one lookup.
365
366
367
368
369
370
|
# File 'app/models/communication.rb', line 365
def failed_recipient_details
@failed_recipient_details ||= begin
details = communication_recipients.filter_map(&:detail).uniq
details.empty? ? [] : ContactPoint.where(detail: details, state: 'failed').distinct.pluck(:detail)
end
end
|
#feed_histories ⇒ ActiveRecord::Relation<FeedHistory>
87
|
# File 'app/models/communication.rb', line 87
has_many :feed_histories, dependent: :destroy
|
#fill_suppressed_reason ⇒ String
Set a human-readable status_message naming the specific recipient(s) that
caused the send to be suppressed, so the CRM banner explains why delivery
failed and to whom rather than a generic sentence. Falls back to a generic
message when no guard matches (e.g. a manual mark_suppressed), so the
banner never goes blank.
430
431
432
433
434
435
436
437
438
439
440
441
442
443
|
# File 'app/models/communication.rb', line 430
def fill_suppressed_reason
reason = if (unsubscribed = unsubscribed_recipient_details).any?
"Recipient unsubscribed from #{category} email: #{unsubscribed.to_sentence}"
elsif (failed = failed_recipient_details).any?
"Delivery previously failed (bounced) — address marked undeliverable: #{failed.to_sentence}"
elsif (inactive = inactive_recipient_details).any?
"Contact marked inactive: #{inactive.to_sentence}"
elsif (customer = closed_or_bankrupt_customer)
"Customer marked closed or bankrupt: #{customer.full_name}"
else
'This communication was suppressed.'
end
self.status_message = reason
end
|
#has_closed_customer? ⇒ Boolean
Returns true when the recipient's customer is closed or bankrupt.
391
392
393
|
# File 'app/models/communication.rb', line 391
def has_closed_customer?
closed_or_bankrupt_customer.present?
end
|
Returns true when any recipient address previously bounced.
357
358
359
|
# File 'app/models/communication.rb', line 357
def has_failed_contact_point?
failed_recipient_details.any?
end
|
Returns true when any recipient is linked to an inactive party.
373
374
375
|
# File 'app/models/communication.rb', line 373
def has_inactive_contact?
inactive_recipient_details.any?
end
|
#has_recipients? ⇒ Boolean
317
318
319
|
# File 'app/models/communication.rb', line 317
def has_recipients?
communication_recipients.any?(&:valid?)
end
|
#has_suppressed_recipients? ⇒ Boolean
Returns true when any recipient trips a suppression guard.
412
413
414
|
# File 'app/models/communication.rb', line 412
def has_suppressed_recipients?
has_unsubscribed? || has_failed_contact_point? || has_inactive_contact? || has_closed_customer?
end
|
#has_unsubscribed? ⇒ Boolean
Returns true when any recipient unsubscribed from this category.
326
327
328
|
# File 'app/models/communication.rb', line 326
def has_unsubscribed?
unsubscribed_recipient_details.any?
end
|
#important? ⇒ Boolean
This is used to determine if we notify the sender of a bounce or error
495
496
497
|
# File 'app/models/communication.rb', line 495
def important?
category == 'transactional'
end
|
#inactive_recipient_details ⇒ Array<String>
Recipient email addresses linked to a party flagged inactive.
The join brings in contact_points, which also has a detail column, so
the pluck is table-qualified to avoid an ambiguous-column error. Memoized
so the suppression guard and fill_suppressed_reason share one lookup.
384
385
386
387
388
|
# File 'app/models/communication.rb', line 384
def inactive_recipient_details
@inactive_recipient_details ||=
communication_recipients.joins(contact_point: :party).where(Party[:inactive].eq(true))
.distinct.pluck(CommunicationRecipient.arel_table[:detail])
end
|
#inbound? ⇒ Boolean
829
830
831
|
# File 'app/models/communication.rb', line 829
def inbound?
direction == 'inbound'
end
|
#increment_publication_counters ⇒ Object
Increment the counter of our publications, sort of a way to keep track of popularity
947
948
949
|
# File 'app/models/communication.rb', line 947
def increment_publication_counters
publications.each { |p| p.increment!(:requested_counter) }
end
|
#is_not_campaign_delivery? ⇒ Boolean
321
322
323
|
# File 'app/models/communication.rb', line 321
def is_not_campaign_delivery?
resource_type != 'CampaignDelivery'
end
|
#is_triggered_by_mailbox? ⇒ Boolean
215
216
217
|
# File 'app/models/communication.rb', line 215
def is_triggered_by_mailbox?
triggered_by_mailbox.to_b
end
|
#literatures ⇒ Object
Alias for Uploads#literatures
940
|
# File 'app/models/communication.rb', line 940
delegate :literatures, to: :uploads
|
#mark_associated_activities_completed ⇒ Object
861
862
863
|
# File 'app/models/communication.rb', line 861
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_send ⇒ Object
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.
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
|
# File 'app/models/communication.rb', line 1029
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
|
#no_zoom_scheduler_links ⇒ Object
1018
1019
1020
1021
1022
1023
|
# File 'app/models/communication.rb', line 1018
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_unsubscribed ⇒ Object
233
234
235
236
237
238
239
240
241
242
243
244
|
# File 'app/models/communication.rb', line 233
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
833
834
835
|
# File 'app/models/communication.rb', line 833
def outbound?
direction == 'outbound'
end
|
#populate_category_from_template ⇒ Object
229
230
231
|
# File 'app/models/communication.rb', line 229
def populate_category_from_template
self.category = email_template&.category
end
|
#populate_template_emails ⇒ Object
503
504
505
506
507
508
509
510
511
512
513
514
515
516
|
# File 'app/models/communication.rb', line 503
def populate_template_emails
return unless email_template
if email_template.from.present?
self.sender = email_template.from
elsif email_template.default_from.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_text ⇒ Object
817
818
819
820
821
822
823
824
825
826
827
|
# File 'app/models/communication.rb', line 817
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_limit ⇒ Object
927
928
929
|
# File 'app/models/communication.rb', line 927
def provider_limit
20_480_000
end
|
#publications ⇒ Object
942
943
944
|
# File 'app/models/communication.rb', line 942
def publications
Item.joins(:literature).merge(literatures)
end
|
#recipient_party ⇒ Party
79
|
# File 'app/models/communication.rb', line 79
belongs_to :recipient_party, class_name: 'Party', inverse_of: :inbound_communications, optional: true
|
#release ⇒ Object
219
220
221
222
223
224
225
226
227
|
# File 'app/models/communication.rb', line 219
def release
return false unless (exception? || draft? || queued?) && can_release?
if send_communication
sent
else
failed
end
end
|
#reply_to_options_for_select ⇒ Object
931
932
933
934
935
936
937
|
# File 'app/models/communication.rb', line 931
def reply_to_options_for_select
if tracking_email_address.present?
[tracking_email_address]
else
['ar@warmlyyours.com', 'techteam@warmlyyours.com']
end
end
|
#resource ⇒ Resource
81
|
# File 'app/models/communication.rb', line 81
belongs_to :resource, polymorphic: true, optional: true
|
#resource_combo ⇒ Object
734
735
736
|
# File 'app/models/communication.rb', line 734
def resource_combo
"#{communication_resource.class.name}|#{communication_resource.id}" unless communication_resource.nil?
end
|
#resource_combo=(val) ⇒ Object
738
739
740
741
742
743
744
745
746
|
# File 'app/models/communication.rb', line 738
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_communication ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity -- pre-existing god-method (121+ on master); out of scope to decompose here
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
|
# File 'app/models/communication.rb', line 577
def send_communication
if !skip_suppression_check.to_b && has_suppressed_recipients?
mark_suppressed
return false
end
self.transmit_at = Time.current
self.unique_id ||= SecureRandom.uuid
email_options = { unique_id: }
email_options[:uploads] = 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
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 category.present? && Campaign::CATEGORIES.include?(category)
email_options[:disable_email_tracking] =
communication_recipients.select(&:is_email?).any? { |cr| !EmailPreference.can_track_email?(cr.detail) }
end
if mailbox_inbound_email_id.present?
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(',')
unsubscribe_link = UrlHelper.instance.email_preferences_my_account_url(token: EmailPreference.encrypt_email(to_formatted), uid: unique_id, host: "https://#{WEB_HOSTNAME}", locale: false)
email_options[:list_unsubscribe_link] = unsubscribe_link email_options[:list_unsubscribe_email] = "list-remove+#{unique_id}@#{Rails.application.config.x.email_domain}"
end
email_options[:skip_premailer] = should_skip_premailer?
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", 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_email ⇒ Object
553
554
555
556
557
558
559
560
561
562
563
564
565
566
|
# File 'app/models/communication.rb', line 553
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_party ⇒ Party
78
|
# File 'app/models/communication.rb', line 78
belongs_to :sender_party, class_name: 'Party', inverse_of: :outbound_communications, optional: true
|
#should_be_suppressed? ⇒ Boolean
Returns whether an outbound, non-transactional send should be held.
417
418
419
420
421
|
# File 'app/models/communication.rb', line 417
def should_be_suppressed?
outbound? &&
category != 'transactional' &&
has_suppressed_recipients?
end
|
#should_skip_premailer? ⇒ Boolean
Skip Premailer CSS inlining for:
- Templates with disable_premailer explicitly checked
- Redactor 4 ready templates (styles are already inlined by R4's email plugin)
- Any content that starts with DOCTYPE (R4 content loaded into a plain communication)
715
716
717
718
719
720
721
|
# File 'app/models/communication.rb', line 715
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
568
569
570
571
572
573
574
|
# File 'app/models/communication.rb', line 568
def show_mailing_address?
if Campaign::CATEGORIES.include?(category)
!(body.include?('590 Telser') || body.include?('300 Granton'))
else
false
end
end
|
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.
812
813
814
815
|
# File 'app/models/communication.rb', line 812
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
|
83
|
# File 'app/models/communication.rb', line 83
belongs_to :source, optional: true
|
#template_for_email ⇒ Object
696
697
698
699
700
701
702
703
704
705
706
707
708
709
|
# File 'app/models/communication.rb', line 696
def template_for_email
return 'v4' if is_triggered_by_mailbox? && compliant_body.to_s.lstrip.start_with?('<')
return EmailTemplate::DEFAULT_TEMPLATE if email_template.blank?
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
478
479
480
|
# File 'app/models/communication.rb', line 478
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_s ⇒ Object
463
464
465
|
# File 'app/models/communication.rb', line 463
def to_s
"Communication #{id}"
end
|
#too_big? ⇒ Boolean
499
500
501
|
# File 'app/models/communication.rb', line 499
def too_big?
total_attachment_size > 10.megabytes
end
|
#total_attachment_size ⇒ Object
490
491
492
|
# File 'app/models/communication.rb', line 490
def total_attachment_size
uploads.sum { |u| u.try(:attachment).try(:size) || 0 }
end
|
#tracking_email_address ⇒ Object
865
866
867
868
869
870
871
872
|
# File 'app/models/communication.rb', line 865
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_activity ⇒ Activity
82
|
# File 'app/models/communication.rb', line 82
belongs_to :triggered_activity, class_name: 'Activity', foreign_key: 'triggered_by_activity_id', optional: true
|
#unsubscribed_recipient_details ⇒ Array<String>
Recipient email addresses that have unsubscribed from this email's category.
Empty for transactional (cannot unsubscribe) or category-less communications.
The category maps to an email_preferences.disable_<category> boolean
column. It is validated against the actual column list before use so it is
never interpolated into raw SQL, and the lookup is a single batched query
(hash condition) rather than one exists? per recipient. Memoized so the
state-machine suppression guard and fill_suppressed_reason share one
lookup per instance.
341
342
343
344
345
346
347
348
349
350
351
352
353
354
|
# File 'app/models/communication.rb', line 341
def unsubscribed_recipient_details
@unsubscribed_recipient_details ||=
if category == 'transactional' || category.blank? []
else
column = "disable_#{category}"
emails = communication_recipients.filter_map { |cr| cr.formatted_email_string.presence }.uniq
if EmailPreference.column_names.include?(column) && emails.any?
EmailPreference.where(email: emails, column => true).distinct.pluck(:email)
else
[]
end
end
end
|
#uploads ⇒ ActiveRecord::Relation<Upload>
88
|
# File 'app/models/communication.rb', line 88
has_and_belongs_to_many :uploads, class_name: 'Upload'
|
#validate_attachment_limits ⇒ Object
1012
1013
1014
|
# File 'app/models/communication.rb', line 1012
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
951
952
953
954
955
956
957
958
959
960
|
# File 'app/models/communication.rb', line 951
def versions_for_audit_trail(_params = {})
query_sql = <<~SQL.squish
(item_type = 'Communication' AND item_id = :id)
OR (
item_type = 'CommunicationRecipient'
AND reference_data @> :communication_id_json
)
SQL
RecordVersion.where(query_sql, id:, communication_id_json: { communication_id: id }.to_json)
end
|