KamaKAzii
3/4/2018 - 9:27 AM

gistfile1.txt

class DirectDebitSummary < ApplicationRecord

  attr_accessor :unbatched_recovered_val

  belongs_to :term

  after_initialize :init

  def init
    self.batched_approved_data    ||= []
    self.batched_declined_data    ||= []
    self.unprocessable_data       ||= []
    self.processable_data         ||= []

    self.batched                  ||= 0
    self.batched_approved         ||= 0
    self.batched_declined         ||= 0
    self.unbatched                ||= 0
    self.unprocessable            ||= 0
    self.processable              ||= 0
  end

  def unbatched_recovered
    unbatched_recovered_val ||= calc_unbatched_recovered
  end

  def unbatched_outstanding
    unbatched - unbatched_recovered
  end

  private

  def calc_unbatched_recovered
    parent_unpro_tx_ids       = unprocessable_data.map  { |d| d["transaction_id"] }
    parent_pro_tx_ids         = processable_data.map    { |d| d["transaction_id"] }

    parent_tx_ids             = parent_unpro_tx_ids + parent_pro_tx_ids
    parent_txs                = Transaction.where(id: parent_tx_ids).includes(:children)

    target_record_payment_txs  = []

    parent_txs.each do |t|
      t.children.each do |ct|

        is_processed_after_cycle = ct.processed_at >= created_at

        is_success = ct.status == Transaction::STATUSES.Success

        is_correct_tx_type =
          ct.transaction_type == Transaction::TRANSACTION_TYPES.RecordPayment

        if is_correct_tx_type && is_processed_after_cycle && is_success
          target_record_payment_txs.push(ct)
        end
      end
    end

    target_record_payment_txs.map { |t| t.amount.abs }.reduce(:+)
  end

end