Class: Pomodoro::Commands::Expenses

Inherits:
Command
  • Object
show all
Defined in:
lib/pomodoro/commands/expenses.rb

Instance Method Summary collapse

Constructor Details

This class inherits a constructor from Pomodoro::Commands::Command

Instance Method Details

#convert(from:, to:, amount:) ⇒ Object

convert from: 'USD', to: 'EUR', amount: 1 => 0.82884


22
23
24
# File 'lib/pomodoro/commands/expenses.rb', line 22

def convert(from:, to:, amount:)
  self.rates[from][to] * amount
end

#ratesObject


12
13
14
15
16
17
18
# File 'lib/pomodoro/commands/expenses.rb', line 12

def rates
  @rates ||= Hash.new do |hash, currency|
    open("http://api.fixer.io/latest?base=#{currency}") do |stream|
      hash[currency] = JSON.parse(stream.read, symbolize_names: true)[:rates]
    end
  end
end

#runObject


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/pomodoro/commands/expenses.rb', line 32

def run
  # week, month
  today = Date.today
  monday = today - (today.wday - 1) % 7
  archive = Pomodoro::Formats::Today::Archive.new(monday, today)
  archive.days.each do |day|
    totals = day.review.expenses.data.totals.map { |key, value| "<yellow>#{key}</yellow> #{value}" }.join(', ')
    total = total(day.review.expenses.data.totals)
    puts "<green>#{day.date.strftime('%a %-d/%-m')}</green> #{totals} = <blue.bold>EUR</blue.bold> #{total.round(2)}"
  end

  overall_totals = archive.days.each_with_object(Hash.new { |hash, key| hash[key] = 0 }) do |day, sums|
    day.review.expenses.data.totals.each do |key, value|
      sums[key] += value
    end
  end

  overall_total = archive.days.reduce(0) do |sum, day|
    sum + total(day.review.expenses.data.totals)
  end

  overall_totals = overall_totals.map { |key, value| "<yellow>#{key}</yellow> #{value}" }.join(', ')
  puts "\n<green>Overall</green> #{overall_totals} = <blue.bold>EUR</blue.bold> #{overall_total.round(2)}"
  puts "<green>Daily average</green> <blue.bold>EUR</blue.bold> #{(overall_total / archive.days.length).round(2)}"
end

#total(totals) ⇒ Object


26
27
28
29
30
# File 'lib/pomodoro/commands/expenses.rb', line 26

def total(totals)
  totals.reduce(0) do |sum, (currency, amount)|
    sum + convert(from: currency, to: :EUR, amount: amount)
  end
end