Skip to content
Permalink
master
Switch branches/tags
Go to file
 
 
Cannot retrieve contributors at this time
executable file 110 lines (88 sloc) 2.52 KB
#!/usr/bin/env ruby
require 'date'
require 'yaml'
require 'ballista'
require 'cymbal'
require 'burglar'
CONFIG_DIR = 'projections'.freeze
JOURNAL_DIR = 'journals'.freeze
def load_file(file)
YAML.safe_load(File.read(file))
end
def config_file_paths
@config_file_paths ||= Dir.glob("#{CONFIG_DIR}/*.yml")
end
def config_file
@config_file ||= config_file_paths.map { |x| load_file(x) }.reduce(:+)
end
def config
@config ||= Cymbal.symbolize(config_file)
end
def full_range
@full_range ||= [burglar_begin, Date.new(Date.today.year + 1, 12)]
end
def month_pairs
return @month_pairs if @month_pairs
month_starts = (full_range.first..full_range.last).select do |date|
date.day == 1 || date == full_range.first
end
@month_pairs = month_starts.map { |x| [x, Date.new(x.year, x.month, -1)] }
end
def month_file(start)
"#{JOURNAL_DIR}/#{start.strftime('%Y/%m')}.ldg"
end
def header
'; Records below generated by ./scripts/project using ballista'
end
def existing_content(file)
return Ledger.new unless File.exist? file
content = File.read(file).partition(header).first.rstrip
return Ledger.new if content.empty?
Ledger::Journal.from_text(content)
end
def burglar_begin
Date.today - 30
end
def burglar_end
Date.today
end
def all_burglar_content
@all_burglar_content ||= Burglar.new(
begin: burglar_begin,
end: burglar_end
).transactions
end
def past_content(file, first, last) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength,Metrics/LineLength
new = all_burglar_content.entries.select do |x|
first <= x.date && x.date <= last
end
content = existing_content(file)
known_ids = content.entries.map do |x|
x.tags.values_at('transaction_id', 'transaction_id2')
end.flatten.compact
new.each do |x|
next if known_ids.include? x.tags['transaction_id']
content.entries << x
end
content
end
def ballista_content(first, last)
first = Date.today if first < Date.today
return Ledger.new if first > last
Ballista.new(entries: config).project(first, last)
end
def walk_months # rubocop:disable Metrics/AbcSize
month_pairs.each do |first, last|
file = month_file(first)
content = past_content(file, first, last).to_s
future = ballista_content(first, last)
content << "\n#{header}\n\n#{future}" unless future.entries.empty?
Dir.mkdir(File.dirname(file)) unless Dir.exist?(File.dirname(file))
File.open(file, 'w') { |fh| fh << content }
end
end
unless Dir.exist? CONFIG_DIR
puts 'Run this from directory with journals and projections.yml'
exit 1
end
walk_months