Class: Guevara::Batch

Inherits:
Object
  • Object
show all
Defined in:
lib/guevara/batch.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Batch

Returns a new instance of Batch.



12
13
14
15
# File 'lib/guevara/batch.rb', line 12

def initialize(attributes)
  @transactions = attributes.delete(:transactions)
  @attributes   = attributes
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



10
11
12
# File 'lib/guevara/batch.rb', line 10

def attributes
  @attributes
end

#transactionsObject (readonly)

Returns the value of attribute transactions.



10
11
12
# File 'lib/guevara/batch.rb', line 10

def transactions
  @transactions
end

Instance Method Details

#addenda(transaction, index) ⇒ Object



64
65
66
# File 'lib/guevara/batch.rb', line 64

def addenda transaction, index
  Addenda.new transaction.merge(entry_number: index + 1)
end

#batch_controlObject



33
34
35
36
37
38
39
40
41
# File 'lib/guevara/batch.rb', line 33

def batch_control
  control_attributes = {
    entry_count:    transactions.size * 2,
    entry_hash:     entry_hash,
    total_debit:    total('debit'),
    total_credit:   total('credit')
  }.merge(attributes)
  BatchControl.new control_attributes
end

#batch_headerObject



29
30
31
# File 'lib/guevara/batch.rb', line 29

def batch_header
  BatchHeader.new attributes
end

#entry(transaction, index) ⇒ Object



58
59
60
61
62
# File 'lib/guevara/batch.rb', line 58

def entry transaction, index
  entry_attributes = transaction.merge(number: index + 1,
                                       origin_id: attributes[:origin_id])
  Entry.new entry_attributes
end

#entry_hashObject



43
44
45
46
47
48
# File 'lib/guevara/batch.rb', line 43

def entry_hash
  transactions.
    map{ |t| t[:routing_number].to_i / 10 }. # ignore the check digit
    reduce(:+).                              # sum
    modulo(10_000_000_000)                   # cap to 10 digits
end

#to_sObject



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/guevara/batch.rb', line 17

def to_s
  batch = []

  batch << batch_header.to_s
  transactions.each_with_index do |transaction, index|
    batch << entry(transaction, index).to_s
    batch << addenda(transaction, index).to_s
  end
  batch << batch_control
  batch.join
end

#total(type) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/guevara/batch.rb', line 50

def total type
  transactions.
    select{ |t| t[:type] == type }.
    map{ |t| t[:amount] }.
    reduce(0, :+).
    modulo(1_000_000_000_000)
end