Class: MercuryBanking::CLI::Main

Inherits:
Thor
  • Object
show all
Includes:
Accounts, Base, Financials, Reports, Transactions, Formatters::ExportFormatter, Formatters::TableFormatter
Defined in:
lib/mercury_banking/cli.rb

Overview

Main CLI class that includes all the modules

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Formatters::ExportFormatter

#export_to_beancount, #export_to_csv, #export_to_hledger, #export_to_ledger, #sort_transactions_chronologically, #verify_ledger_file

Methods included from Formatters::TableFormatter

#display_accounts_table, #display_recipients_table, #display_transaction_details, #display_transactions_table

Methods included from Financials

included

Methods included from Transactions

included

Methods included from Reports

included

Methods included from Accounts

included

Methods included from Base

#api_key, #command_exists?, #get_api_key, #log_transfer, #with_api_client

Class Method Details

Add version banner to help output



35
36
37
# File 'lib/mercury_banking/cli.rb', line 35

def self.banner(command, _namespace = nil, _subcommand = false)
  "#{basename} #{command.usage}"
end

.exit_on_failure?Boolean

Handle Thor deprecation warning

Returns:

  • (Boolean)


46
47
48
# File 'lib/mercury_banking/cli.rb', line 46

def self.exit_on_failure?
  true
end

.help(shell, _subcommand = false) ⇒ Object



39
40
41
42
43
# File 'lib/mercury_banking/cli.rb', line 39

def self.help(shell, _subcommand = false)
  shell.say "Mercury Banking CLI v#{MercuryBanking::VERSION} - Command-line interface for Mercury Banking API"
  shell.say
  super
end

Instance Method Details

#set_keyObject



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/mercury_banking/cli.rb', line 64

def set_key
  # Create the .mercury-banking directory if it doesn't exist
  config_dir = File.join(Dir.home, '.mercury-banking')
  FileUtils.mkdir_p(config_dir)

  # Generate a random key and IV for encryption
  key = SecureRandom.random_bytes(32)
  iv = SecureRandom.random_bytes(16)

  # Create a cipher config
  cipher_config = {
    key: Base64.strict_encode64(key),
    iv: Base64.strict_encode64(iv),
    cipher_name: 'aes-256-cbc'
  }

  # Save the cipher config to a file
  key_config_path = File.join(config_dir, 'key_config.json')
  File.write(key_config_path, JSON.pretty_generate(cipher_config))

  # Initialize the SymmetricEncryption with the generated cipher
  cipher = SymmetricEncryption::Cipher.new(
    key: key,
    iv: iv,
    cipher_name: 'aes-256-cbc'
  )

  # Set the cipher as the primary one
  SymmetricEncryption.cipher = cipher

  # Get the API key from the user
  api_key = ask('Enter your Mercury API key:')

  # Encrypt the API key
  encrypted_key = cipher.encrypt(api_key)

  # Save the encrypted API key to a file
  api_key_path = File.join(config_dir, 'api_key.enc')
  File.write(api_key_path, encrypted_key)

  puts "API key encrypted and saved to #{api_key_path}"
end

#transactions(account_identifier) ⇒ Object



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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
# File 'lib/mercury_banking/cli.rb', line 114

def transactions()
  with_api_client do |client|
    # Determine if we're dealing with an account ID or account number
     = nil
    if .match?(/^\d+$/) && !.include?('-')
      begin
         = client.()
         = ["id"]
      rescue StandardError
        # Handle error without assigning to unused variable
        puts "Error: Could not find account with identifier #{account_identifier}"
        return []
      end
    else
       = 
       = client.()
    end

    # Get transactions for the account
    start_date = options[:start]
    end_date = options[:end]

    transactions = client.get_transactions(, start_date)

    # Filter by end date if specified
    if end_date
      end_date_obj = Date.parse(end_date)
      transactions = transactions.select do |t|
        transaction_date = Date.parse(t["postedAt"] || t["createdAt"])
        transaction_date <= end_date_obj
      end
    end

    # Filter by status if specified
    transactions = transactions.select { |t| t["status"] == options[:status] } if options[:status]

    # Filter by search term if specified
    if options[:search]
      search_term = options[:search].downcase
      transactions = transactions.select do |t|
        description = t["bankDescription"] || t["externalMemo"] || ""
        description.downcase.include?(search_term)
      end
    end

    if options[:json] || options[:format] == 'json'
      # Format transactions for JSON output
      formatted_transactions = transactions.map do |t|
        {
          'id' => t["id"],
          'date' => t["postedAt"] || t["createdAt"],
          'description' => t["bankDescription"] || t["externalMemo"] || "Unknown transaction",
          'amount' => t["amount"],
          'status' => t["status"],
          'kind' => t["kind"],
          'reconciled' => false,
          'failed_at' => t["failedAt"],
          'reason_for_failure' => t["reasonForFailure"]
        }
      end

      puts JSON.pretty_generate({
                                  'account_id' => ,
                                  'account_name' => ['name'],
                                  'account_number' => ['accountNumber'],
                                  'total_transactions' => transactions.size,
                                  'transactions' => formatted_transactions
                                })
    else
      # Display transactions in a table
      puts "Transactions for #{account['name']} (#{account['accountNumber']})"
      puts "Period: #{start_date} to #{end_date || 'present'}"
      puts "Total transactions: #{transactions.size}"
      puts

      rows = transactions.map do |t|
        date = t["postedAt"] ? Time.parse(t["postedAt"]).strftime("%Y-%m-%d") : Time.parse(t["createdAt"]).strftime("%Y-%m-%d")
        description = t["bankDescription"] || t["externalMemo"] || "Unknown transaction"
        description = description.length > 30 ? "#{description[0..27]}..." : description
        amount = format("$%.2f", t["amount"])
        status = t["status"]
        kind = t["kind"]
        reconciled = false
        failure_reason = t["reasonForFailure"] || ""

        [t["id"], date, description, amount, status, kind, reconciled, failure_reason]
      end

      table = ::Terminal::Table.new(
        headings: ['Transaction ID', 'Date', 'Description', 'Amount', 'Status', 'Type', 'Reconciled',
                   'Failure Reason'],
        rows: rows
      )

      puts table
    end
  end
end

#versionObject



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mercury_banking/cli.rb', line 51

def version
  if options[:json]
    puts JSON.pretty_generate({
                                'name' => 'mercury-banking',
                                'version' => MercuryBanking::VERSION,
                                'ruby_version' => RUBY_VERSION
                              })
  else
    puts "Mercury Banking CLI v#{MercuryBanking::VERSION} (Ruby #{RUBY_VERSION})"
  end
end