]> jaekl.net Git - oct_sched.git/blob - lib/report.rb
Add monthly summary report
[oct_sched.git] / lib / report.rb
1 # frozen_string_literal: true
2
3 require "pry"
4
5 class Report
6   def initialize
7     @monthly_totals = {}
8   end
9
10   def run(base_path:, prefix:)
11     totals = {}
12     @cached_months = {}
13
14     Dir["#{base_path}/#{prefix}*"].each do |filename|
15       totals = add_month(totals: totals, filename: filename)
16     end
17
18     headers = ["Month"]
19     routes = totals.keys.reject{|x| x.is_a? Symbol}.sort_by(&:to_i)
20     headers.append(routes)
21
22     puts headers.join(";")
23     @monthly_totals.keys.sort_by(&:to_i).each do |month|
24       values = @monthly_totals[month]
25       puts [
26         "#{values[:year]}-#{values[:month]}",
27         routes.map{|route| values[route] || ""},
28       ].flatten.join(";")
29     end
30
31     puts [
32       "TOTAL",
33       routes.map{|route| totals[route] || ""},
34     ].flatten.join(";")
35   end
36
37   private
38
39   def add_month(totals:, filename:)
40     current_month = parse_month(filename: filename)
41
42     current_month.each do |key, count|
43       sum = totals[key] || 0
44       sum += count.to_i
45       totals[key] = sum
46     end
47
48     @monthly_totals[current_month[:month]] = current_month
49
50     totals
51   end
52
53   def parse_month(filename:)
54     totals = {}
55     File.open(filename, "r") do |fd|
56       fd.readlines.each do |line|
57         tokens = line.split(";")
58         next unless 3 == tokens.count
59
60         date, total, spec = line.split(";")
61         hash = eval(spec)
62         year, month = date.split("-")
63         totals[:year] ||= year
64         totals[:month] ||= month
65
66         sum = totals[:sum] || 0
67         sum += total.to_i
68         totals[:sum] = sum
69
70         hash.each do |route, count|
71           sum = totals[route] || 0
72           sum += count.to_i
73           totals[route] = sum
74         end
75       end
76     end
77
78     totals
79   end
80 end