Class: Reckon::App

Inherits:
Object
  • Object
show all
Defined in:
lib/reckon/app.rb

Overview

The main app

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ App

Returns a new instance of App.



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/reckon/app.rb', line 11

def initialize(opts = {})
  self.options = opts
  LOGGER.level = options[:verbose] || Logger::WARN

  self.regexps = {}
  self.seen = Set.new
  options[:sort] ||= :date
  @cli = HighLine.new
  @csv_parser = CSVParser.new(options)
  @matcher = CosineSimilarity.new(options)
  @parser = options[:format] =~ /beancount/i ? BeancountParser.new : LedgerParser.new
  learn!
end

Instance Attribute Details

#csv_parserObject

Returns the value of attribute csv_parser.



9
10
11
# File 'lib/reckon/app.rb', line 9

def csv_parser
  @csv_parser
end

#matcherObject

Returns the value of attribute matcher.



9
10
11
# File 'lib/reckon/app.rb', line 9

def matcher
  @matcher
end

#optionsObject

Returns the value of attribute options.



9
10
11
# File 'lib/reckon/app.rb', line 9

def options
  @options
end

#regexpsObject

Returns the value of attribute regexps.



9
10
11
# File 'lib/reckon/app.rb', line 9

def regexps
  @regexps
end

#seenObject

Returns the value of attribute seen.



9
10
11
# File 'lib/reckon/app.rb', line 9

def seen
  @seen
end

Instance Method Details

#add_description(row) ⇒ Object



259
260
261
262
263
264
265
266
267
# File 'lib/reckon/app.rb', line 259

def add_description(row)
  desc_answer = @cli.ask("Enter a new description for this transaction (empty line aborts)\n") do |q|
    q.overwrite = true
    q.readline = true
    q.default = row[:description]
  end

  row[:description] = desc_answer unless desc_answer.empty?
end

#add_note(row) ⇒ Object



269
270
271
272
273
274
275
276
277
# File 'lib/reckon/app.rb', line 269

def add_note(row)
  desc_answer = @cli.ask("Enter a new note for this transaction (empty line aborts)\n") do |q|
    q.overwrite = true
    q.readline = true
    q.default = row[:note]
  end

  row[:note] = desc_answer unless desc_answer.empty?
end

#add_regexp(account, regex_str) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/reckon/app.rb', line 98

def add_regexp(, regex_str)
  # https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/to_ruby.rb
  match = regex_str.match(/^\/(.*)\/([ix]*)$/m)
  fail "failed to parse regexp #{regex_str}" unless match

  options = 0
  (match[2] || '').split('').each do |option|
    case option
    when 'x' then options |= Regexp::EXTENDED
    when 'i' then options |= Regexp::IGNORECASE
    end
  end
  regexps[Regexp.new(match[1], options)] = 
end

#already_seen?(row) ⇒ Boolean

Returns:

  • (Boolean)


302
303
304
# File 'lib/reckon/app.rb', line 302

def already_seen?(row)
  seen.include?(seen_key(row[:pretty_date], row[:pretty_money]))
end

#ask_account_question(msg, row) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/reckon/app.rb', line 218

def (msg, row)
  # return account token if it matches
  token_answer = most_specific_regexp_match(row)
  if token_answer.any?
    row[:note] = "Matched account token"
    puts "NOTE: Matched account token"
    puts token_answer[0]
    return token_answer[0]
  end

  possible_answers = suggest(row)
  LOGGER.info "possible_answers===> #{possible_answers.inspect}"

  if options[:unattended]
    if options[:fail_on_unknown_account] && possible_answers.empty?
      raise %(Couldn't find any matches for '#{row[:description]}'
        Try adding an account token with --account-tokens)
    end

    default = options[:default_outof_account]
    default = options[:default_into_account] if row[:pretty_money][0] == '-'
    return possible_answers[0] || default
  end

  answer = @cli.ask(msg) do |q|
    q.completion = possible_answers
    q.readline = true
    q.default = possible_answers.first
  end

  # if answer isn't n/note/d/description, must be an account name, or skip, or quit
  return answer unless %w[n note d description].include?(answer)

  add_description(row) if %w[d description].include?(answer)
  add_note(row) if %w[n note].include?(answer)

  print_transaction([row])
  # give user a chance to set account name or retry description
  return (msg, row)
end

#each_row_backwardsObject



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/reckon/app.rb', line 163

def each_row_backwards
  rows = []
  (0...@csv_parser.columns.first.length).to_a.each do |index|
    if @csv_parser.date_for(index).nil?
      LOGGER.warn("Skipping row: '#{@csv_parser.row(index)}' that doesn't have a valid date")
      next
    end
    rows << { :date => @csv_parser.date_for(index),
              :pretty_date => @csv_parser.pretty_date_for(index),
              :pretty_money => @csv_parser.pretty_money_for(index),
              :pretty_money_negated => @csv_parser.pretty_money_for(index, :negate),
              :money => @csv_parser.money_for(index),
              :description => @csv_parser.description_for(index) }
  end
  rows.sort_by do |n|
    [n[options[:sort]], -n[:money], n[:description]]
  end.each do |row|
    yield row
  end
end

#extract_account_tokens(subtree, account = nil) ⇒ Object

Add tokens from account_tokens_file to accounts



83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/reckon/app.rb', line 83

def (subtree,  = nil)
  if subtree.nil? || !subtree
    puts "Warning: empty #{} tree"
    {}
  elsif subtree.is_a?(Array)
    {  => subtree }
  else
    at = subtree.map do |k, v|
      merged_acct = [, k].compact.join(':')
      (v, merged_acct)
    end
    at.inject({}) { |memo, e| memo.merge!(e) }
  end
end

#finishObject



306
307
308
309
310
# File 'lib/reckon/app.rb', line 306

def finish
  options[:output_file].close unless options[:output_file] == STDOUT
  interactive_output "Exiting."
  exit
end

#interactive_output(str, fh = $stdout) ⇒ Object



25
26
27
28
29
# File 'lib/reckon/app.rb', line 25

def interactive_output(str, fh = $stdout)
  return if options[:unattended]

  fh.puts str
end

#learn!Object

Learn from previous transactions. Used to recommend accounts for a transaction.



32
33
34
35
36
37
38
# File 'lib/reckon/app.rb', line 32

def learn!
  (options[:account_tokens_file])
  learn_from_ledger_file(options[:existing_ledger_file])
  # TODO: make this work
  # this doesn't work because output_file is an IO object
  # learn_from_ledger_file(options[:output_file]) if File.exist?(options[:output_file])
end

#learn_from_account_tokens(filename) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/reckon/app.rb', line 40

def (filename)
  return unless filename

  raise "#{filename} doesn't exist!" unless File.exist?(filename)

  (YAML.load_file(filename)).each do |, tokens|
    tokens.each do |t|
      if t.start_with?('/')
        add_regexp(, t)
      else
        @matcher.add_document(, t)
      end
    end
  end
end

#learn_from_ledger(ledger) ⇒ Object

Takes an IO-like object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/reckon/app.rb', line 65

def learn_from_ledger(ledger)
  LOGGER.info "learning from #{ledger}"
  @parser.parse(ledger).each do |entry|
    entry[:accounts].each do ||
      str = [entry[:desc], [:amount]].join(" ")
      if [:name] != options[:bank_account]
        LOGGER.info "adding document #{[:name]} #{str}"
        @matcher.add_document([:name], str)
      end
      pretty_date = entry[:date].iso8601
      if [:name] == options[:bank_account]
        seen << seen_key(pretty_date, @csv_parser.pretty_money([:amount]))
      end
    end
  end
end

#learn_from_ledger_file(ledger_file) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/reckon/app.rb', line 56

def learn_from_ledger_file(ledger_file)
  return unless ledger_file

  raise "#{ledger_file} doesn't exist!" unless File.exist?(ledger_file)

  learn_from_ledger(File.new(ledger_file))
end

#most_specific_regexp_match(row) ⇒ Object



279
280
281
282
283
284
285
286
# File 'lib/reckon/app.rb', line 279

def most_specific_regexp_match(row)
  matches = regexps.map { |regexp, |
    if match = regexp.match(row[:description])
      [, match[0]]
    end
  }.compact
  matches.sort_by { |, matched_text| matched_text.length }.map(&:first)
end

#output(ledger_line) ⇒ Object



293
294
295
296
# File 'lib/reckon/app.rb', line 293

def output(ledger_line)
  options[:output_file].puts ledger_line
  options[:output_file].flush
end

#output_table(fh = $stdout) ⇒ Object



312
313
314
315
316
317
318
# File 'lib/reckon/app.rb', line 312

def output_table(fh = $stdout)
  rows = []
  each_row_backwards do |row|
    rows << row
  end
  print_transaction(rows, fh)
end


184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/reckon/app.rb', line 184

def print_transaction(rows, fh = $stdout)
  str = "\n"
  header = %w[Date Amount Description]
  header += ["Note"] if rows.map { |r| r[:note] }.any?
  maxes = header.map(&:length)
  rows = rows.map do |r|
    [r[:pretty_date], r[:pretty_money], r[:description], r[:note]].compact
  end

  rows.each do |r|
    r.length.times do |i|
      l = 0
      l = r[i].length if r[i]
      maxes[i] ||= 0
      maxes[i] = l if maxes[i] < l
    end
  end

  header.each_with_index do |n, i|
    str += " #{n.center(maxes[i])} |"
  end
  str += "\n"

  rows.each do |row|
    row.each_with_index do |_, i|
      just = maxes[i]
      str += sprintf(" %#{just}s |", row[i])
    end
    str += "\n"
  end

  interactive_output str, fh
end

#seen_key(date, amount) ⇒ Object



298
299
300
# File 'lib/reckon/app.rb', line 298

def seen_key(date, amount)
  return [date, amount].join("|")
end

#suggest(row) ⇒ Object



288
289
290
291
# File 'lib/reckon/app.rb', line 288

def suggest(row)
  most_specific_regexp_match(row) +
    @matcher.find_similar(row[:description]).map { |n| n[:account] }
end

#walk_backwardsObject



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/reckon/app.rb', line 113

def walk_backwards
  cmd_options = "[account]/[q]uit/[s]kip/[n]ote/[d]escription"
  seen_anything_new = false
  each_row_backwards do |row|
    print_transaction([row])

    if already_seen?(row)
      interactive_output "NOTE: This row is very similar to a previous one!"
      if !seen_anything_new
        interactive_output "Skipping..."
        next
      end
    else
      seen_anything_new = true
    end

    if row[:money] > 0
      # out_of_account
      answer = (
        "Which account provided this income? (#{cmd_options})", row
      )
      line1 = [options[:bank_account], row[:pretty_money]]
      line2 = [answer, ""]
    else
      # into_account
      answer = (
        "To which account did this money go? (#{cmd_options})", row
      )
      line1 = [answer, ""]
      line2 = [options[:bank_account], row[:pretty_money]]
    end

    if answer == '~~SKIP~~'
      LOGGER.info "skipping transaction: #{row}"
      next
    end

    finish if %w[quit q].include?(answer)
    if %w[skip s].include?(answer)
      interactive_output "Skipping"
      next
    end

    ledger = @parser.format_row(row, line1, line2)
    LOGGER.info "ledger line: #{ledger}"
    learn_from_ledger(StringIO.new(ledger)) unless options[:account_tokens_file]
    output(ledger)
  end
end