Class: CommunicationBuilder

Inherits:
Object
  • Object
show all
Defined in:
app/models/communication_builder.rb

Overview

Factory that assembles an unsaved Communication from a wide variety of
inputs (recipients, an EmailTemplate, a source resource such as an
Invoice / Quote / Order / etc.) and renders the body/subject so the
CRM communication form can preview before sending.

The class dispatches on the resource's model name to call a matching
initialize_for_<model> private method, which contributes
resource-specific recipients, default templates, default attachments, and
merge variables. New resource types are wired up by adding another
initialize_for_<model> method.

rubocop:disable Metrics/ClassLength -- pre-existing god-class (419 lines on master); decompose separately

Defined Under Namespace

Classes: ContactContactPointExtractor, ContactPointExtractor, CustomerContactPointExtractor

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ CommunicationBuilder

Returns a new instance of CommunicationBuilder.

Parameters:

  • options (Hash, nil) (defaults to: nil)

    builder options

Options Hash (options):

  • logger (Logger, nil)

    logger to use instead of Rails.logger

  • merge_options (Hash)

    extra merge variables for template rendering

  • source_id (Integer, nil)
  • resource (ApplicationRecord, nil)

    the source resource (Invoice, Quote, Order, ...)

  • resource_type (String, nil)

    class name used with :resource_id to load the resource

  • resource_id (Integer, nil)

    id used with :resource_type to load the resource

  • skip_resource_init (Boolean)

    skip the resource-specific initializer

  • sender_party_id (Integer, nil)

    explicit sender party id, takes precedence

  • sender_party (Party, nil)

    default sender party

  • sender (Employee, nil)

    the sending employee

  • recipient_contact_points (Array<ContactPoint>, nil)

    recipient contact points

  • recipient_contact_point_id (Integer, nil)

    single recipient contact point id

  • recipient_contact_point_ids (Array<Integer>, String, nil)

    recipient contact point ids

  • recipient_party (Party, nil)

    recipient party

  • recipient_party_id (Integer, nil)

    recipient party id, overrides :recipient_party

  • recipient_name (String, nil)

    override for the recipient name

  • recipient_first_name (String, nil)

    override for the recipient first name

  • current_user (Employee, nil)

    last-resort sender party

  • template (EmailTemplate, nil)

    the email template

  • email_template_id (Integer, nil)
  • template_system_code (String, nil)

    system code of the email template

  • reply_to_parent_id (Integer, nil)

    id of the parent communication when replying

  • category (String, nil)

    communication category

  • appointment (Object, nil)

    related appointment

  • uploads (Array<Upload>, nil)

    attachments

  • upload_ids (Array<Integer>, nil)

    ids of uploads to attach

  • upload_id (Integer, nil)

    id of a single upload to attach

  • skip_attachments (Boolean)

    skip building attachments

  • triggered_by_activity_id (Integer, nil)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'app/models/communication_builder.rb', line 48

def initialize(options = nil)
  @options = (options || {}).to_h.symbolize_keys

  @logger = @options[:logger] || Rails.logger
  @extra_merge_options = @options[:merge_options] || {}

  Rails.logger.debug { "CommunicationBuilder, initialize: @extra_merge_options!!: #{@extra_merge_options.inspect}" }

  # Defaults
  @recipient_contact_points = []
  @uploads = []
  # @temp_uploads = []
  @communication_recipients = []

  # source
  @source_id = @options[:source_id]

  # Extract
  @resource = @options[:resource]
  @resource = @options[:resource_type].classify.constantize.find(options[:resource_id]) if @resource.nil? && options[:resource_id].present? && @options[:resource_type].present?
  # If a resource is specified, we run a custom extractor if we have one
  # Custom method would be initialize_for_<singular form of model name>, e.g. initialize_for_invoice
  if @resource && !@options[:skip_resource_init].to_b
    klass = @resource.class
    while klass < ApplicationRecord
      method_name = :"initialize_for_#{klass.name.tableize.singularize}"
      if respond_to?(method_name, true)
        send(method_name, @resource)
        break
      end
      klass = klass.superclass
    end
  end
  # Sender
  # Explicit sender_party_id always takes precedence (e.g. when user changes the
  # sender dropdown on the communications form).  Resource initializers like
  # initialize_for_quote may set @sender_party as a default, but the caller's
  # explicit choice should win.
  if @options[:sender_party_id].present?
    @sender_party = Party.find(@options[:sender_party_id])
  else
    @sender_party ||= @options[:sender_party]
  end

  @sender ||= options[:sender]

  # Contact points
  @recipient_contact_points += @options[:recipient_contact_points] if @options[:recipient_contact_points].present? && @options[:recipient_contact_points].respond_to?(:to_a)
  cp_ids = [] + [@options[:recipient_contact_point_id]] + (@options[:recipient_contact_point_ids].try(:split, ',') || @options[:recipient_contact_point_ids] || [])
  cp_ids = cp_ids.uniq.compact
  if cp_ids.present?
    contact_points = ContactPoint.where(id: cp_ids)
    contact_points = contact_points.where.not(id: @recipient_contact_points.map(&:id)) if @recipient_contact_points.present?
    @recipient_contact_points += contact_points
  end
  @recipient_contact_points.uniq!(&:detail)

  # Recipient
  @recipient_party = @options[:recipient_party] if @options[:recipient_party].present?
  # recipient_party_id overrides recipient_party
  # this is so when changing the recipient from the communication form, it will set a new recipient
  @recipient_party = Party.find(@options[:recipient_party_id]) if @options[:recipient_party_id].present?
  # If our recipient is not specified, but contact points are we try to extract from them the first valid party
  @recipient_party ||= @recipient_contact_points.filter_map(&:party).uniq.first if @recipient_party.nil? && @recipient_contact_points.present?

  # override recipient name
  @recipient_name = @options[:recipient_name]
  @recipient_first_name = @options[:recipient_first_name]

  # Last resort is current user.
  @sender_party ||= @options[:current_user]

  # Email Template
  @template ||= @options[:template]
  @template ||= EmailTemplate.find(@options[:email_template_id]) if @options[:email_template_id].present?
  @template ||= EmailTemplate.find_by(system_code: @options[:template_system_code]) if @options[:template_system_code].present?
  @template ||= @default_template
  @template ||= resolve_default_blank_template

  # Conversation
  @parent_communication_id ||= @options[:reply_to_parent_id]

  # category
  @category ||= @options[:category] ||= @template.category if @template

  # Appointment
  @appointment = @options[:appointment] if @options[:appointment].present?

  # Uploads
  @uploads += @options[:uploads] if @options[:uploads].present? && @options[:uploads].respond_to?(:to_a)
  @uploads += Upload.where(id: @options[:upload_ids]).to_a if @options[:upload_ids].present?
  @uploads += Upload.where(id: @options[:upload_id]).to_a if @options[:upload_id].present?
  @uploads = @uploads.compact.uniq
  @recipient_contact_points = @recipient_contact_points.compact.uniq
  @skip_attachments = @options[:skip_attachments]

  # Trigger activity
  @triggered_by_activity_id = options[:triggered_by_activity_id]
end

Instance Method Details

#buildObject

Builds instantiate the communication object but does not save it
rubocop:disable Metrics/AbcSize -- pre-existing god-method (103+ on master); out of scope to decompose here



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'app/models/communication_builder.rb', line 150

def build
  return unless @template

  local_merge_options = merge_options # Just to do this once
  Communication.new.tap do |c|
    @recipient_contact_points.each do |cp|
      c.communication_recipients.build category: cp.category, detail: cp.detail, name: cp.party.try(:full_name), contact_point_id: cp.id
    end
    @communication_recipients.each do |cr|
      c.communication_recipients << cr
    end
    # Add from email string
    create_recipients_from_string(c, @options[:emails])

    # Add our template defaults
    create_recipients_from_string(c, @template.to.presence)
    create_recipients_from_string(c, @options[:cc].presence || @template.cc.presence, 'cc')
    create_recipients_from_string(c, @options[:bcc].presence || @template.bcc.presence, 'bcc')

    # Find the best email contact recipient if we have nothing
    if c.communication_recipients.empty? && @options[:use_best_email] && @recipient_party
      cpe = ContactPointExtractor.build(@recipient_party)
      cp = cpe.best_contact_point
      c.communication_recipients.build category: cp.category, detail: cp.detail, name: cp.party.try(:full_name), contact_point_id: cp.id if cp
    end

    snapshot_tracking_consent(c)

    # adding the unsubscribe link to local_merge_options here as we can't do it until we've determined the recipients
    to = c.communication_recipients.select { |cr| cr.email_method != 'cc' and cr.email_method != 'bcc' }.map(&:detail).join(',')
    c.unique_id = SecureRandom.uuid
    # Generate an unsubscribe url for merge templates
    # locale: false ensures no locale prefix - Cloudflare worker will add appropriate locale based on user's country
    unsubscribe_url = UrlHelper.instance.(token: EmailPreference.encrypt_email(to), uid: c.unique_id, host: "https://#{WEB_HOSTNAME}", locale: false)
    local_merge_options['unsubscribe_url'] = unsubscribe_url
    c.subject = @options[:subject].presence || @template.render_subject(local_merge_options)
    # Use v4 body if template has body_v4 content:
    # - for_editor: true -> use body_v4 (editable content for Redactor)
    # - for_editor: false/nil -> use body_v4_email (email output) when redactor_4_ready
    c.body = if @template.body_v4.present? && @options[:for_editor].to_b
               @template.render_editable_body(local_merge_options)
             elsif (@template.redactor_4_ready? || @options[:force_v4].to_b) && @template.body_v4_email.present?
               @template.render_body_v4(local_merge_options)
             else
               @template.render_body(local_merge_options)
             end
    c.sender_party = @sender_party
    c.sender = @sender
    c.sender ||= @template.from.presence
    c.reply_to = @options[:reply_to].presence || @template.default_reply_to
    c.recipient_party = @recipient_party
    c.email_template = @template
    c.category = @category
    c.resource = @resource
    c.uploads += @uploads if @uploads.present?
    c.appointment = @appointment if @appointment.present?
    c.source_id = @source_id
    c.reply_to_parent_id = @parent_communication_id
    c.triggered_by_activity_id = @triggered_by_activity_id
    c.template_merge_options = @extra_merge_options if @options[:save_merge_options].to_b
    c.transmit_at = @options[:transmit_at]
  end
end

#create(options = {}) ⇒ Communication?

Create essentially builds and save

Parameters:

  • options (Hash) (defaults to: {})

    send options

Options Hash (options):

  • skip_suppression_check (Boolean)

    skip the recipient suppression check

  • send_immediately (Boolean)

    release the communication immediately instead of queueing

  • keep_as_draft (Boolean)

    leave the communication as a draft

Returns:



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'app/models/communication_builder.rb', line 260

def create(options = {})
  # Reports (never blocks) if an archived system template just got resolved —
  # see EmailTemplate#assert_sendable!. Lives here rather than in #initialize
  # so it isn't a new line inside a method already over the AbcSize limit.
  @template&.assert_sendable!

  communication = build
  return unless communication

  if communication.save
    communication.reload
    communication.skip_suppression_check = options[:skip_suppression_check]

    if @deferred_pdf_article_id
      dispatch = if options[:send_immediately].to_b then 'release'
                 elsif !options[:keep_as_draft].to_b then 'queue'
                 end
      ArticlePdfWorker.perform_async(@deferred_pdf_article_id, communication.id, dispatch)
    elsif options[:send_immediately].to_b
      communication.release
    elsif !options[:keep_as_draft].to_b
      communication.queue
    end
  end
  communication
end

#create_recipients_from_string(communication, string_email, email_method = 'to') ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'app/models/communication_builder.rb', line 225

def create_recipients_from_string(communication, string_email, email_method = 'to')
  cpds = if string_email.is_a?(Array)
           string_email
         else
           string_email.to_s.split(',').map(&:strip)
         end
  cpds.each do |cpd|
    # Parse "Name <email>" format using Mail::Address
    parsed = begin
      Mail::Address.new(cpd)
    rescue StandardError
      nil
    end

    if parsed&.address.present?
      email = parsed.address.downcase
      name = parsed.display_name.presence
    else
      email = cpd.strip.downcase
      name = nil
    end

    unless communication.communication_recipients.find { |cp| cp.category == ContactPoint::EMAIL && cp.detail.to_s.downcase == email }
      communication.communication_recipients.build(category: ContactPoint::EMAIL, detail: email, name: name, email_method:)
    end
  end
end

#initialize_for_article(article) ⇒ Object

Note:

i could do this as subclass but since the difference between are so small i am opting for this method. Forgive me gods of OOP

Custom initializer
By default our builder will derive a lot of the information from the parameters
but sometime different defaults or options are required.
When a custom initializer is required just define one as intialize_for_<class_name_lower_case_tableized_singularized and add any
special processing in there
for instance. the recipient_party can be extracted from the resource in question rather than detected as a parameter.
or a default template must be specified to process the resource



421
422
423
424
425
# File 'app/models/communication_builder.rb', line 421

def initialize_for_article(article)
  @default_template = EmailTemplate.find_by(system_code: 'ARTICLE')
  @deferred_pdf_article_id = article.id
  @extra_merge_options['article'] = article
end

#initialize_for_contact(contact) ⇒ Object



432
433
434
435
# File 'app/models/communication_builder.rb', line 432

def initialize_for_contact(contact)
  @recipient_party = contact
  @recipient_contact_points << contact.contact_points.emails.first if contact.contact_points.emails.present?
end

#initialize_for_credit_application(credit_application) ⇒ Object



625
626
627
# File 'app/models/communication_builder.rb', line 625

def initialize_for_credit_application(credit_application)
  @recipient_party = credit_application.customer
end

#initialize_for_credit_memo(credit_memo) ⇒ Object



593
594
595
596
597
598
599
# File 'app/models/communication_builder.rb', line 593

def initialize_for_credit_memo(credit_memo)
  @recipient_party = credit_memo.primary_transmission_contact || credit_memo.customer
  @recipient_contact_points.concat(credit_memo.transmission_contact_points)
  @sender_party = @recipient_party.try(:primary_sales_rep)
  @default_template = EmailTemplate.find_by(system_code: 'CREDITMEMO')
  @uploads << credit_memo.get_or_regen_pdf unless options_has_uploads?
end

#initialize_for_customer(customer) ⇒ Object



427
428
429
430
# File 'app/models/communication_builder.rb', line 427

def initialize_for_customer(customer)
  @recipient_party = customer
  @recipient_contact_points << customer.contact_points.emails.first if customer.contact_points.emails.present?
end

#initialize_for_exported_catalog_item_packet(exported_catalog_item_packet) ⇒ Object



437
438
439
440
441
# File 'app/models/communication_builder.rb', line 437

def initialize_for_exported_catalog_item_packet(exported_catalog_item_packet)
  @default_template = EmailTemplate.find_by(system_code: 'EXPORTED_CATALOG')
  @extra_merge_options[:token] = exported_catalog_item_packet.uploads.last.download_tokens.last.token
  # uploads << exported_catalog_item_packet.generate_packet
end

#initialize_for_invoice(invoice) ⇒ Object



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'app/models/communication_builder.rb', line 443

def initialize_for_invoice(invoice)
  @recipient_party = invoice.primary_transmission_contact || invoice.customer
  @recipient_contact_points.concat(invoice.transmission_contact_points)
  @extra_merge_options[:account_receivable_email] = ACCOUNTS_RECEIVABLE_EMAIL
  @sender_party = invoice.customer.try(:primary_sales_rep)
  @default_template = EmailTemplate.find_by(system_code: 'INVOICE')
  @options[:emails] ||= []
  @options[:emails] += invoice.billing_emails || []
  return if options_has_uploads?

  @uploads << invoice.get_or_regen_pdf(@logger)
  return unless invoice.order.present? && invoice.order.funded_by_advance_replacement? && invoice.order.try(:rma).try(:return_instructions)

  @uploads << invoice.order.rma.return_instructions
end

#initialize_for_locator_record(locator_record) ⇒ Object



585
586
587
588
589
590
591
# File 'app/models/communication_builder.rb', line 585

def initialize_for_locator_record(locator_record)
  @recipient_party = locator_record.customer
  @recipient_contact_points << ContactPoint.find(locator_record.email_id) if locator_record.email_id
  @options[:use_best_email] = true
  @sender_party = locator_record.customer.try(:primary_sales_rep) || locator_record.customer.try(:sales_manager)
  @default_template = EmailTemplate.find_by(system_code: 'DEALER_INVITE')
end

#initialize_for_opportunity(opportunity) ⇒ Object



633
634
635
636
637
638
639
640
# File 'app/models/communication_builder.rb', line 633

def initialize_for_opportunity(opportunity)
  @sender_party = opportunity.customer.primary_sales_rep
  @recipient_party = opportunity.primary_party
  @recipient_contact_points += ([@recipient_party] + opportunity.parties).filter_map { |p| p.contact_points.emails.first }.uniq
  # Legacy IQ room merge options removed - IQ system deprecated
  @extra_merge_options[:iq_rooms] = [] if @extra_merge_options[:iq_rooms].nil? && @extra_merge_options[:iq_room_ids]
  @default_template = EmailTemplate.find_by(system_code: 'INSTANT_QUOTES')
end

#initialize_for_order(order) ⇒ Object



629
630
631
# File 'app/models/communication_builder.rb', line 629

def initialize_for_order(order)
  @recipient_party = order.customer
end

#initialize_for_payment(pp) ⇒ Object



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'app/models/communication_builder.rb', line 488

def initialize_for_payment(pp)
  # set a default recipient, unless one was already passed in the emails option
  if @options[:emails]
    email = @options[:emails].split(',').first
    if email && (cp = ContactPoint.where(detail: email).first)
      @recipient_contact_points << cp
      @recipient_party = cp.party
    else
      @recipient_party = pp.order.customer
    end
  else
    @recipient_party = pp.order.customer
    # @recipient_party = receipt.primary_transmission_contact || receipt.customer
    # @recipient_contact_points.concat(receipt.transmission_contact_points)
  end
  # @sender_party = invoice.customer.try(:primary_sales_rep)
  @extra_merge_options[:receipt_number] = "PP#{pp.id}"
  @extra_merge_options[:receipt_date] = pp.created_at.to_fs(:crm_date_only)
  @extra_merge_options[:receipt_items] = [{ 'description' => pp.order.reference_number, 'amount' => ActionController::Base.helpers.number_to_currency(pp.amount) }]
  @extra_merge_options[:payment_method] = pp.category
  @extra_merge_options[:card_type] = pp.card_type
  @extra_merge_options[:card_name] = pp.name
  @extra_merge_options[:auth_code] = pp.authorization_code
  @extra_merge_options[:receipt_reference] = pp.reference
  @extra_merge_options[:receipt_amount] = ActionController::Base.helpers.number_to_currency(pp.amount)
  @default_template = EmailTemplate.find_by(system_code: 'AUTH_RECEIPT')
end

#initialize_for_purchase_order(po) ⇒ Object



543
544
545
546
547
548
549
550
# File 'app/models/communication_builder.rb', line 543

def initialize_for_purchase_order(po)
  @recipient_party = po.supplier
  @recipient_contact_points << @recipient_party.contact_points.emails.first if @recipient_party.contact_points.emails.present?
  @recipient_contact_points << @recipient_party.contact_points.faxes.first if @recipient_party.contact_points.faxes.present? && @recipient_contact_points.empty?
  @uploads << po.get_or_regen_pdf unless options_has_uploads?
  @sender_party = @options[:current_user] # using the po creator or updater is just wrong when a guest customer can order a drop-shipped item oneline po.creator || po.updater
  @default_template = EmailTemplate.find_by(system_code: 'PURCHASEORDER')
end

#initialize_for_quote(quote) ⇒ Object



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

def initialize_for_quote(quote)
  @sender_party = quote.customer.primary_sales_rep
  @recipient_party = quote.primary_party || quote.customer
  # SmartService quotes were discontinued
  # @default_template = EmailTemplate.where(system_code: 'QUOTE_SMARTSERVICE').first if quote.is_smart_service_quote?
  # Online-quote (/ql/) flow: rep just transmits a link to the customer-
  # facing viewer, no PDF attachment. PDF flow uses the legacy QUOTE
  # template + the freshly generated PDF as the attachment.
  @default_template = if @options[:online_quote].to_b
                        EmailTemplate.find_by(system_code: 'QUOTE_ONLINE')
                      else
                        EmailTemplate.find_by(system_code: 'QUOTE')
                      end

  @recipient_contact_points += quote.contact_points.transmittable.to_a
  @uploads << quote.uploads.last unless options_has_uploads? || skip_attachments? || @options[:online_quote].to_b
end

#initialize_for_receipt(receipt) ⇒ Object



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'app/models/communication_builder.rb', line 459

def initialize_for_receipt(receipt)
  # set a default recipient, unless one was already passed in the emails option
  if @options[:emails]
    email = @options[:emails].split(',').first
    if email && (cp = ContactPoint.where(detail: email).first)
      @recipient_contact_points << cp
      @recipient_party = cp.party
    else
      @recipient_party = receipt.customer
    end
  else
    @recipient_party = receipt.primary_transmission_contact || receipt.customer
    @recipient_contact_points.concat(receipt.transmission_contact_points)
  end
  # @sender_party = invoice.customer.try(:primary_sales_rep)
  @extra_merge_options[:receipt_number] = "R#{receipt.id}"
  @extra_merge_options[:receipt_date] = receipt.receipt_date.to_fs(:crm_default)
  @extra_merge_options[:receipt_items] = receipt.receipt_details.map { |rd| { 'description' => rd.description(true), 'amount' => ActionController::Base.helpers.number_to_currency(rd.amount) } }
  @extra_merge_options[:payment_method] = receipt.category
  @extra_merge_options[:payment_amount] = receipt.amount
  @extra_merge_options[:card_type] = receipt.card_type
  @extra_merge_options[:card_name] = receipt.card_name
  @extra_merge_options[:auth_code] = receipt.authorization_code
  @extra_merge_options[:receipt_reference] = receipt.reference
  @extra_merge_options[:receipt_authorization_code] = receipt.authorization_code
  @extra_merge_options[:receipt_amount] = ActionController::Base.helpers.number_to_currency(receipt.amount)
  @default_template = EmailTemplate.find_by(system_code: 'PURCHASE_RECEIPT')
end

#initialize_for_rma(rma) ⇒ Object



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'app/models/communication_builder.rb', line 552

def initialize_for_rma(rma)
  @sender_party = @options[:current_user] || rma.send_from || rma.customer.try(:primary_sales_rep) || rma.creator
  @recipient_party = rma.customer
  @default_template = EmailTemplate.find_by(system_code: 'RMA')
  # Return instructions + labels belong ONLY on the 'RMA' return-instructions
  # email — not on the inspection / rejection / return-confirmation
  # notifications that also use the RMA as their resource. Gate on the
  # template the communication will actually use, not on @default_template
  # (which is the RMA template here, so it can't tell the cases apart).
  if resolved_template&.system_code == 'RMA'
    # Include return instructions if available
    @uploads << rma.return_instructions if rma.return_instructions.present?
    # Include return labels if available
    @uploads += rma.return_labels if rma.return_labels.present?
  end
  initialize_recipients_from_array(rma.transmission_email, ContactPoint::EMAIL)
  initialize_recipients_from_array(rma.transmission_fax, ContactPoint::FAX)
end

#initialize_for_spiff_enrollment(spiff_enrollment) ⇒ Object



601
602
603
604
605
606
607
608
609
610
611
# File 'app/models/communication_builder.rb', line 601

def initialize_for_spiff_enrollment(spiff_enrollment)
  @recipient_party = spiff_enrollment.contact
  @recipient_contact_points << @recipient_party.contact_points.emails.first if @recipient_party.contact_points.emails.present?
  @sender_party = begin
    Account.find_by(login: 'epasek').party
  rescue StandardError
    nil
  end || @recipient_party.customer.primary_sales_rep
  initialize_from_email_string spiff_enrollment.notification_email
  @default_template = EmailTemplate.find_by(system_code: 'SPIFF_ENROLL')
end

#initialize_for_statement_of_account(soa) ⇒ Object



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

def (soa)
  @recipient_party = soa.primary_transmission_contact || soa.customer
  @recipient_contact_points.concat(soa.transmission_contact_points)
  @extra_merge_options[:account_receivable_email] = ACCOUNTS_RECEIVABLE_EMAIL
  @sender_party = soa.customer.try(:primary_sales_rep)
  @default_template = EmailTemplate.find_by(system_code: 'STATEMENTOFACCOUNT')
  @uploads << soa.uploads.in_category('statement_of_account_pdf').first unless options_has_uploads?
end

#initialize_for_support_case(support_case) ⇒ Object



613
614
615
616
617
618
619
620
621
622
623
# File 'app/models/communication_builder.rb', line 613

def initialize_for_support_case(support_case)
  # @options[:reply_to] = support_case.tracking_email_address
  if %w[SUPPORTCASE_UPDATE ACCT_TCKT_UPDATE ECOM_TCKT_UPDATE].include?(@options[:template_system_code])
    @sender_party = @options[:current_user]
  elsif %w[SUPPORTCASE_ASSIGN SUPPORTCASE_OPEN ACCT_TCKT_ASSIGN ECOM_TCKT_ASSIGN].include?(@options[:template_system_code])
    @options[:reply_to] = nil
    @sender_party = support_case.updater || support_case.creator
    @recipient_party = support_case.assigned_to
    @recipient_contact_points << @recipient_party.contact_points.emails.first if @recipient_party && @recipient_party.contact_points.emails.present?
  end
end

#initialize_from_email_string(email_string) ⇒ Object

Used as a helper method to initialize defaults recipient contact points and recipients from an email string, e.g. email1@mail.com,email2@mail.com
this looks to see if we can match it to a recipient party contact point first and maps it



384
385
386
387
388
389
# File 'app/models/communication_builder.rb', line 384

def initialize_from_email_string(email_string)
  return if email_string.blank?

  email_array = email_string.to_s.split(',').compact_blank.uniq
  initialize_recipients_from_array(email_array, ContactPoint::EMAIL)
end

#initialize_from_fax_string(fax_string) ⇒ Object

Used as a helper method to initialize defaults recipient contact points and recipients from a fax string, e.g. 2342342342,5242342344
this looks to see if we can match it to a recipient party contact point first and maps it



375
376
377
378
379
380
# File 'app/models/communication_builder.rb', line 375

def initialize_from_fax_string(fax_string)
  return if fax_string.blank?

  fax_array = fax_string.to_s.split(',').compact_blank.uniq
  initialize_recipients_from_array(fax_array, ContactPoint::FAX)
end

#initialize_recipients_from_array(detail_array, category) ⇒ Object



391
392
393
394
395
396
397
398
399
# File 'app/models/communication_builder.rb', line 391

def initialize_recipients_from_array(detail_array, category)
  detail_array.each do |cpd|
    if (cp = @recipient_party.contact_points.where(category:, detail: cpd).first)
      @recipient_contact_points << cp
    else
      @communication_recipients << CommunicationRecipient.new(detail: cpd, category:, name: @recipient_name || @recipient_party.try(:full_name))
    end
  end
end

#merge_optionsObject

This gets fed to the templating system



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'app/models/communication_builder.rb', line 305

def merge_options
  options = {}
  if @resource
    # If the resource responds to liquid proxy it through this
    resource_for_merge = @resource.to_liquid if @resource.respond_to?(:to_liquid)
    resource_for_merge ||= @resource
    options[@resource.class.name.tableize.singularize] = resource_for_merge
    options[:resource] = resource_for_merge
  end

  options[:sender_party] = options[:sender] = @sender_party
  options[:recipient_party] = @recipient_party
  options[:first_name] = @recipient_first_name || (@recipient_party.first_name if @recipient_party.respond_to?(:first_name) && @recipient_party.is_person?)
  options[:recipient] = @recipient_name || (@recipient_party.full_name if @recipient_party.respond_to? :full_name)
  options[:first_name] = nil if options[:first_name]&.casecmp('Guest')&.zero?
  options[:recipient] = nil if options[:recipient]&.casecmp('Guest')&.zero?
  options[:salutation] = "Dear #{options[:first_name]}," if options[:first_name].present?
  options[:salutation] ||= "Dear #{options[:recipient]}," if options[:recipient].present?
  options[:salutation] ||= 'Greetings,'

  options[:customer] = @recipient_party if @recipient_party.is_a? Customer
  options[:customer] ||= @recipient_party.customer if @recipient_party.respond_to? :customer
  options[:customer_number] = @recipient_party.reference_number if @recipient_party.is_a? Customer
  options[:customer_number] = @recipient_party.customer.reference_number if @recipient_party&.customer # employee.respond_to?'customer' yields true on employees yet employee.customer is nil - Ramie
  options[:customer] ||= @resource.customer if @resource.respond_to?(:customer)
  if (rep = options[:customer]&.primary_sales_rep)
    options[:primary_sales_rep] = rep
    options[:primary_sales_rep_signature] = EmailTemplate.render_signature(rep)
    options[:sender_party] ||= rep
  end
  options[:review_url] = options[:customer]&.company_review_url ||
                         'https://www.reviews.io/company-reviews/store/warmlyyours-com'

  options[:contact] = @recipient_party if @recipient_party.is_a? Contact
  options[:uploads] = @uploads
  options[:recipient_contact_points] = @recipient_contact_points
  if options[:sender_party]
    signature_theme = @resource.is_a?(SupportCase) ? :technical : :default
    options[:signature] = EmailTemplate.render_signature(options[:sender_party], theme: signature_theme)
    options[:interesting_fact] = options[:sender_party].try(:interesting_fact)
    options[:years_at_warmlyyours] = options[:sender_party].try(:years_at_warmlyyours)
    options[:certifications] = options[:sender_party].try(:certifications)
    options[:sender_photo_url] = options[:sender_party].try(:signature_picture_small)
    options[:sender_job_title] = options[:sender_party].try(:job_title)
    options[:sender_name] = options[:sender_party].try(:full_name)
    options[:sender_phone] = options[:sender_party].try(:phone_formatted)
  else
    options[:signature] = Communication.default_signature
  end

  options.merge!(@extra_merge_options)
  Rails.logger.debug { "CommunicationBuilder: @extra_merge_options: #{@extra_merge_options.inspect}" }
  safe_options = {}
  options.stringify_keys.each do |k, v|
    # This is necessary because liquid does not like active relation and will bug out otherwise
    safe_options[k] = v.is_a?(ActiveRecord::Relation) ? v.to_a : v
  end
  safe_options
end

#options_has_uploads?Boolean

Returns:

  • (Boolean)


365
366
367
# File 'app/models/communication_builder.rb', line 365

def options_has_uploads?
  %i[uploads upload_id upload_ids].intersect?(@options.keys)
end

#resolve_default_blank_templateObject

Resolves the default blank template based on the sender's department.
Tech Support employees get BLANK_TECH; everyone else gets BLANK.



403
404
405
406
407
408
409
410
411
# File 'app/models/communication_builder.rb', line 403

def resolve_default_blank_template
  employee = if @sender_party.is_a?(Employee)
               @sender_party
             elsif @sender_party.respond_to?(:employee)
               @sender_party.employee
             end

  (EmailTemplate.find_by(system_code: 'BLANK_TECH') if employee&.employee_record&.department == 'Tech Support') || EmailTemplate.find_by(system_code: 'BLANK')
end

#resolved_templateEmailTemplate?

The template this communication will actually use, resolved with the same
precedence as #initialize (explicit template > email_template_id >
template_system_code > the resource's @default_template). Lets resource
initializers decide which default attachments belong on the email before
#initialize has finished resolving @template.

Returns:



578
579
580
581
582
583
# File 'app/models/communication_builder.rb', line 578

def resolved_template
  @options[:template] ||
    (@options[:email_template_id].present? && EmailTemplate.find_by(id: @options[:email_template_id])) ||
    (@options[:template_system_code].present? && EmailTemplate.find_by(system_code: @options[:template_system_code])) ||
    @default_template
end

#skip_attachments?Boolean

Returns:

  • (Boolean)


369
370
371
# File 'app/models/communication_builder.rb', line 369

def skip_attachments?
  @options[:skip_attachments].to_b
end

Snapshot the tracking-consent decision at build time for immutable reporting
(CNIL/Garante). The live send-time gate is re-evaluated in Communication#deliver.



217
218
219
220
221
222
223
# File 'app/models/communication_builder.rb', line 217

def snapshot_tracking_consent(communication)
  communication.communication_recipients.each do |cr|
    next unless cr.category == ContactPoint::EMAIL && cr.detail.present?

    cr.tracking_disabled = !EmailPreference.can_track_email?(cr.detail)
  end
end

#to_paramsObject

Build a params hash that can be used to re-create a communication as new



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'app/models/communication_builder.rb', line 288

def to_params
  params = {}
  if @resource
    params[:resource_id] = @resource.id
    params[:resource_type] = @resource.class.name
  end
  params[:sender_party_id] = @sender_party.id if @sender_party
  params[:recipient_party_id] = @recipient_party.id if @recipient_party
  params[:email_template_id] = @template.id if @template
  params[:upload_ids] = @uploads.map(&:id) if @uploads.present?
  params[:recipient_contact_point_ids] = @recipient_contact_points.to_a.compact.uniq.map(&:id) if @recipient_contact_points.present? && @recipient_contact_points.respond_to?(:to_a)
  params[:online_quote] = 1 if @options[:online_quote].to_b

  params
end