Sha256: a7d985eec8eef40ab2e3caff8ab4137255f7c0b431493d2baf3b0fe6fca05395

Contents?: true

Size: 1.54 KB

Versions: 10

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true

require_dependency "renalware/letters"

module Renalware
  module Letters
    class ApproveLetter
      include Broadcasting
      pattr_initialize :letter

      class << self
        alias_method :build, :new
      end

      def call(by:)
        Letter.transaction do
          add_missing_counterpart_cc_recipients
          archive_recipients
          sign(by: by)
          archive_content(by: by)
          # Cast the letter to the base Letter class in case it becomes a Letters::Completed
          # before any async listeners have time to process it.
          broadcast(:letter_approved, letter.becomes(Letters::Letter))
        end
      end

      private

      def sign(by:)
        # Needs to be saved before changing the STI type (signature would be lost otherwise)
        letter.sign(by: by).save!
      end

      # Note that generate_archive returns the letter as a Letter::Approved object.
      # We need to update our letter reference as it's this Approved letter we need to broadcast
      # to subscribers.
      def archive_content(by:)
        @letter = letter.generate_archive(by: by)
        letter.save!
      end

      def archive_recipients
        letter.archive_recipients!
      end

      def add_missing_counterpart_cc_recipients
        DetermineCounterpartCCs.new(letter).call.each do |recipient|
          already_a_recipient = letter.recipients.exists?(addressee: recipient.addressee)
          unless already_a_recipient
            recipient.save!
          end
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
renalware-core-2.1.1 app/models/renalware/letters/approve_letter.rb
renalware-core-2.1.0 app/models/renalware/letters/approve_letter.rb
renalware-core-2.0.167 app/models/renalware/letters/approve_letter.rb
renalware-core-2.0.166 app/models/renalware/letters/approve_letter.rb
renalware-core-2.0.165 app/models/renalware/letters/approve_letter.rb
renalware-core-2.0.164 app/models/renalware/letters/approve_letter.rb
renalware-core-2.0.163 app/models/renalware/letters/approve_letter.rb
renalware-core-2.0.162 app/models/renalware/letters/approve_letter.rb
renalware-core-2.0.161 app/models/renalware/letters/approve_letter.rb
renalware-core-2.0.160 app/models/renalware/letters/approve_letter.rb