# typed: true # frozen_string_literal: true require_relative '../command' require_relative '../api/wallet.rb' require_relative '../api/transaction.rb' require_relative '../api/category.rb' require 'byebug' module Moneylovercli module Commands class AddTransaction < Moneylovercli::Command def initialize(options) @options = options @wallet_id = options[:wallet_id] end 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 end end end