lib/aba/batch.rb in aba-1.0.1 vs lib/aba/batch.rb in aba-1.0.2

- old
+ new

@@ -1,5 +1,7 @@ +# frozen_string_literal: true + class Aba class Batch include Aba::Validations attr_accessor :bsb, :financial_institution, :user_name, :user_id, :description, :process_at, :entries @@ -26,10 +28,13 @@ # Process at Date validates_length :process_at, 6 validates_integer :process_at, false + # Totals + validates_max_length :debit_total_amount, 10 + validates_max_length :credit_total_amount, 10 def initialize(attrs = {}, transactions = []) attrs.each do |key, value| send("#{key}=", value) end @@ -85,11 +90,14 @@ has_entry_errors? # Build errors all_errors = {} all_errors[:aba] = self.error_collection unless self.error_collection.empty? - entry_error_collection = entries.each_with_index.map { |t, i| [i, t.error_collection] }.reject { |e| e[1].nil? || e[1].empty? }.to_h + entry_error_collection = entries.each_with_index + .map { |t, i| [i, t.error_collection] } + .reject { |e| e[1].nil? || e[1].empty? } + .to_h all_errors[:entries] = entry_error_collection unless entry_error_collection.empty? all_errors unless all_errors.empty? end @@ -163,21 +171,13 @@ # Char position: 81-120 output += " " * 40 end def batch_control_record - credit_total_amount = 0 - debit_total_amount = 0 + cached_credit_total_amount = credit_total_amount + cached_debit_total_amount = debit_total_amount - entries.each do |entry| - if entry.debit? - debit_total_amount += Integer(entry.amount).abs - else - credit_total_amount += Integer(entry.amount).abs - end - end - # Record type # Max: 1 # Char position: 1 output = "7" @@ -192,21 +192,21 @@ output += " " * 12 # Net total # Max: 10 # Char position: 21-30 - output += (credit_total_amount - debit_total_amount).abs.to_s.rjust(10, "0") + output += (cached_credit_total_amount - cached_debit_total_amount).abs.to_s.rjust(10, "0") # Credit Total Amount # Max: 10 # Char position: 31-40 - output += credit_total_amount.to_s.rjust(10, "0") + output += cached_credit_total_amount.to_s.rjust(10, "0") # Debit Total Amount # Max: 10 # Char position: 41-50 - output += debit_total_amount.to_s.rjust(10, "0") + output += cached_debit_total_amount.to_s.rjust(10, "0") # Reserved # Max: 24 # Char position: 51-74 output += " " * 24 @@ -218,8 +218,20 @@ # Reserved # Max: 40 # Char position: 81-120 output += " " * 40 + end + + def credit_total_amount + credit_total_amount ||= entries.reject(&:debit?).sum(&method(:entry_amount)) + end + + def debit_total_amount + entries.select(&:debit?).sum(&method(:entry_amount)) + end + + def entry_amount(entry) + entry.amount.to_s[/\A\-?\d+\z/] ? Integer(entry.amount).abs : 0 end end end