class Moneylovercli::Commands::AddTransaction

Public Class Methods

new(options) click to toggle source
# File lib/moneylovercli/commands/add_transaction.rb, line 13
def initialize(options)
  @options = options
  @wallet_id = options[:wallet_id]
end

Public Instance Methods

execute(input: $stdin, output: $stdout) click to toggle source
# File lib/moneylovercli/commands/add_transaction.rb, line 18
def execute(input: $stdin, output: $stdout)
  config.read
  current_wallet = @wallet_id || config.fetch(:current_wallet)
  access_token = config.fetch(:access_token)
  unless current_wallet
    request = Moneylovercli::Api::Wallet.new(token: access_token).list
    response = request.parsed_response

    if !response['data'].nil?
      wallet_id = prompt.select('Choose your wallet', response['data'].map { |a| [a['name'], a['_id']] }.to_h)
      config.set_if_empty(:wallet_id, value: wallet_id)
      config.write(force: true)

      amount = prompt.ask('Ammount', convert: :int, default: 10)

      categories = config.fetch(:categories, wallet_id)
      unless categories
        prompt.ok('categories are not exist, fetching...')

        categories_response = Moneylovercli::Api::Category
                              .new(token: access_token)
                              .list(wallet_id: wallet_id)
                              .parsed_response

        if !categories_response['data'].nil?
          config.set(:categories, wallet_id, value: categories_response['data'].map { |a| a.slice('_id', 'name')})
          config.write(force: true)
          prompt.ok('fetched categories succesfully')
        else
          prompt.error('Failed to fetch categories')
          return
        end
      end

      categories = config.fetch(:categories, wallet_id)
      cats = categories.each_with_object({}) { |a, hash| hash[a['name']] = a['_id']; }
      category_id = prompt.select('Category', cats, filter: true, show_help: :always)
      display_date = prompt.ask('Date (Eg: YYYY-mm-dd)', default: DateTime.now.strftime('%F'))

      puts "#{amount} - #{category_id} - #{display_date}"
      transaction_request = Moneylovercli::Api::Transaction.new(token: access_token)
                                                           .add(account: wallet_id, category_id: category_id,
                                                                amount: amount, display_date: display_date)
      if transaction_request.parsed_response['msg'] == 'transaction_add_success'
        prompt.ok('Great! Your transaction has been created')
      else
        prompt.error("Failed to add transaction: #{transaction_request.parsed_response['msg'] }")
      end
    elsif response['msg'] != 'get_list_account_success'
      prompt.error('Failed to fetch wallet')
      return
    end
  end
end