Class: Renalware::Letters::Mailshots::Mailshot

Inherits:
ApplicationRecord
  • Object
show all
Includes:
Accountable
Defined in:
app/models/renalware/letters/mailshots/mailshot.rb

Instance Method Summary collapse

Methods included from Accountable

#first_or_create_by!, #save_by, #save_by!, #update_by

Instance Method Details

#common_letter_attributesObject

These attributes apply to all letters in the mailshot rubocop:disable Metrics/MethodLength



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'app/models/renalware/letters/mailshots/mailshot.rb', line 60

def common_letter_attributes
  @common_letter_attributes ||= begin
    {
      letterhead_id: letterhead_id,
      description: description,
      body: body,
      author_id: author_id,
      issued_on: Time.zone.now,
      main_recipient_attributes: {
        person_role: :patient,
        id: nil,
        addressee_id: nil
      }
    }
  end
end

#create_lettersObject

Called usually by a background job, creates all the letters in the mailshot. The patients to create letters for are defined by the SQL view output. The other data items required for creating the letters are stored in the mailshot object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/models/renalware/letters/mailshots/mailshot.rb', line 45

def create_letters
  Mailshot.transaction do
    recipient_patients.each do |patient|
      letter = MailshotLetterFactory.new(
        patient: patient,
        current_user: created_by,
        letter_attributes: common_letter_attributes
      ).create
      items.create!(letter: letter)
    end
  end
end

#recipient_patientsObject

The sql view should ideally only have one column - ‘patient_id’ because we use this to filter the patients we want.



31
32
33
34
35
36
37
38
39
# File 'app/models/renalware/letters/mailshots/mailshot.rb', line 31

def recipient_patients
  @recipient_patients ||= begin
    return Patient.none if sql_view_name.blank?

    Patient
      .where(Arel.sql("id in (select distinct patient_id from #{sql_view_name})"))
      .order(:family_name, :given_name)
  end
end