Class: MFYNAB::MoneyForward

Inherits:
Object
  • Object
show all
Defined in:
lib/mfynab/money_forward.rb,
lib/mfynab/money_forward/session.rb,
lib/mfynab/money_forward/account_status.rb

Defined Under Namespace

Classes: AccountStatus, Session

Constant Summary collapse

CSV_PATH =
"/cf/csv"

Instance Method Summary collapse

Constructor Details

#initialize(session, logger:) ⇒ MoneyForward

Returns a new instance of MoneyForward.



10
11
12
13
# File 'lib/mfynab/money_forward.rb', line 10

def initialize(session, logger:)
  @session = session
  @logger = logger
end

Instance Method Details

#download_csv(path:, months:) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/mfynab/money_forward.rb', line 48

def download_csv(path:, months:)
  month = Date.today
  month -= month.day - 1 # First day of month
  months.times do
    date_string = month.strftime("%Y-%m")

    logger.info("Downloading CSV for #{date_string}")

    # FIXME: I don't really need to save the CSV files to disk anymore.
    # Maybe just return parsed CSV data?
    File.open(File.join(path, "#{date_string}.csv"), "wb") do |file|
      file << download_csv_string(date: month)
    end

    month = month.prev_month
  end
end

#download_csv_string(date:) ⇒ Object

FIXME: make private or inline



67
68
69
70
71
72
73
# File 'lib/mfynab/money_forward.rb', line 67

def download_csv_string(date:)
  # FIXME: handle errors/edge cases
  session
    .http_get(CSV_PATH, from: date.strftime("%Y/%m/%d"))
    .force_encoding(Encoding::SJIS)
    .encode(Encoding::UTF_8)
end

#fetch_data(months) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mfynab/money_forward.rb', line 35

def fetch_data(months)
  Dir.mktmpdir("mfynab") do |save_path|
    download_csv(
      path: save_path,
      months: months,
    )

    MoneyForwardData.new(logger: logger).tap do |data|
      data.read_all_csv(save_path)
    end
  end
end

#update_accounts(account_names, update_invalid: true) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mfynab/money_forward.rb', line 15

def update_accounts(, update_invalid: true)
   = AccountStatus::Fetcher.new(session, logger: logger).fetch(account_names: )

  finished = .map do ||
    (, update_invalid: update_invalid)
  end.all?

  return if finished

  logger.info("Waiting for a while before checking status again...")
  # FIXME: I'm never comfortable with using sleep().
  # Do I want to implement a solution based on callbacks?
  # For example, the script could say:
  # > Accounts are out of date.
  # > I triggered the updates, and will call myself again in X seconds/minutes.
  # > When the accounts are updated, I'll proceed to the next step.
  sleep(5)
  update_accounts(, update_invalid: false)
end