Class: CommunicationBuilder

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

Defined Under Namespace

Classes: ContactContactPointExtractor, ContactPointExtractor, CustomerContactPointExtractor

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ CommunicationBuilder

Returns a new instance of CommunicationBuilder.



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
# File 'app/models/communication_builder.rb', line 2

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? and 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



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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'app/models/communication_builder.rb', line 103

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? and @options[:use_best_email] and @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

    # 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' }.collect(&: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 = {}) ⇒ Object

Create essentially builds and save



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'app/models/communication_builder.rb', line 194

def create(options = {})
  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



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
# File 'app/models/communication_builder.rb', line 165

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 { |e| e.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.detect { |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

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



351
352
353
354
355
# File 'app/models/communication_builder.rb', line 351

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



362
363
364
365
# File 'app/models/communication_builder.rb', line 362

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



531
532
533
# File 'app/models/communication_builder.rb', line 531

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

#initialize_for_credit_memo(credit_memo) ⇒ Object



499
500
501
502
503
504
505
# File 'app/models/communication_builder.rb', line 499

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



357
358
359
360
# File 'app/models/communication_builder.rb', line 357

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



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

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



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'app/models/communication_builder.rb', line 373

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? and invoice.order.funded_by_advance_replacement? and invoice.order.try(:rma).try(:return_instructions)

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

#initialize_for_locator_record(locator_record) ⇒ Object



491
492
493
494
495
496
497
# File 'app/models/communication_builder.rb', line 491

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



539
540
541
542
543
544
545
546
# File 'app/models/communication_builder.rb', line 539

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

#initialize_for_order(order) ⇒ Object



535
536
537
# File 'app/models/communication_builder.rb', line 535

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

#initialize_for_payment(pp) ⇒ Object



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'app/models/communication_builder.rb', line 418

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 and 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



466
467
468
469
470
471
472
473
# File 'app/models/communication_builder.rb', line 466

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? and @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



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

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?
  @default_template = EmailTemplate.find_by(system_code: 'QUOTE') # quote.catalog.store_id == Store::WARMLYYOURS_CA_ID ? "QUOTE_CA" : "QUOTE")

  @recipient_contact_points += quote.contact_points.transmittable.to_a
  @uploads << quote.uploads.last unless options_has_uploads? || skip_attachments?
end

#initialize_for_receipt(receipt) ⇒ Object



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'app/models/communication_builder.rb', line 389

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 and 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.collect { |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



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'app/models/communication_builder.rb', line 475

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')
  # Attach return instructions and return labels for RMA template
  # Do this specifically for the 'RMA' template regardless of RMA state
  if @options[:template_system_code].to_s == 'RMA' || @default_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



507
508
509
510
511
512
513
514
515
516
517
# File 'app/models/communication_builder.rb', line 507

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



446
447
448
449
450
451
452
453
# File 'app/models/communication_builder.rb', line 446

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



519
520
521
522
523
524
525
526
527
528
529
# File 'app/models/communication_builder.rb', line 519

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 and @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



312
313
314
315
316
317
# File 'app/models/communication_builder.rb', line 312

def initialize_from_email_string(email_string)
  return unless email_string.present?

  email_array = email_string.to_s.split(',').select { |cp| cp.present? }.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



303
304
305
306
307
308
# File 'app/models/communication_builder.rb', line 303

def initialize_from_fax_string(fax_string)
  return unless fax_string.present?

  fax_array = fax_string.to_s.split(',').select { |cp| cp.present? }.uniq
  initialize_recipients_from_array(fax_array, ContactPoint::FAX)
end

#initialize_recipients_from_array(detail_array, category) ⇒ Object



319
320
321
322
323
324
325
326
327
# File 'app/models/communication_builder.rb', line 319

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



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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
286
287
288
289
290
291
# File 'app/models/communication_builder.rb', line 233

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 && @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)


293
294
295
# File 'app/models/communication_builder.rb', line 293

def options_has_uploads?
  (%i[uploads upload_id upload_ids] & @options.keys).present?
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.



331
332
333
334
335
336
337
338
339
340
341
# File 'app/models/communication_builder.rb', line 331

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

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

#skip_attachments?Boolean

Returns:

  • (Boolean)


297
298
299
# File 'app/models/communication_builder.rb', line 297

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

#to_paramsObject

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



217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'app/models/communication_builder.rb', line 217

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? and @recipient_contact_points.respond_to? :to_a

  params
end