Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.82 KB | None | 0 0
  1. class TransactionsReportBuilder
  2.   attr_reader :from_date, :to_date
  3.   IMPORTANT_SHORTCUTS = %w[BTC LTC ETH BCH].freeze
  4.   def initialize(from_date, to_date)
  5.     @from_date = from_date
  6.     @to_date = to_date
  7.   end
  8.  
  9.   def build_report
  10.     result = []
  11.  
  12.     IMPORTANT_SHORTCUTS.each do |shortcut|
  13.       result << [shortcut, sum_in_currency(shortcut)]
  14.     end
  15.     result << ['Total quantity', total_quantity]
  16.     result << ['Others quantity', others_quantity]
  17.     result << ['Total in ETH', total_in_eth]
  18.     result << ['Total in USD', total_in_usd]
  19.     first_row = []
  20.     last_row = []
  21.     result.each do |name, value|
  22.       first_row << name
  23.       last_row << value
  24.     end
  25.     [first_row, last_row]
  26.   end
  27.  
  28.   def sum_in_currency(shortcut)
  29.     currency_id = CryptoCurrency.find_by(shortcut: shortcut)
  30.     Transaction.joins(:personal_address)
  31.                .where('personal_addresses.crypto_currency_id = ?', currency_id)
  32.                .where(updated_at: date_range)
  33.                .sum(:amount)
  34.   end
  35.  
  36.   def total_quantity
  37.     transactions_in_date_range.count
  38.   end
  39.  
  40.   def others_quantity
  41.     other_ids = other_shortcuts.map { |sc| CryptoCurrency.find_by(shortcut: sc).id }
  42.     transactions_in_date_range.where('personal_addresses.crypto_currency_id IN (?)', other_ids).count
  43.   end
  44.  
  45.   def total_in_eth
  46.     shortcuts = CryptoCurrency.pluck(:shortcut)
  47.     shortcuts.map do |shortcut|
  48.       sum_in_currency(shortcut) * Rate.actual_for_currency(shortcut)
  49.     end.sum
  50.   end
  51.  
  52.   def total_in_usd
  53.     total_in_eth * Rate.actual_eth_to_usd
  54.   end
  55.  
  56.   private
  57.  
  58.   def date_range
  59.     (from_date..to_date)
  60.   end
  61.  
  62.   def transactions_in_date_range
  63.     Transaction.joins(:personal_address).where(updated_at: date_range)
  64.   end
  65.  
  66.   def other_shortcuts
  67.     CryptoCurrency.pluck(:shortcut) - IMPORTANT_SHORTCUTS
  68.   end
  69. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement