Skip to content

Instantly share code, notes, and snippets.

@Diasporism
Last active December 13, 2015 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Diasporism/4973203 to your computer and use it in GitHub Desktop.
Save Diasporism/4973203 to your computer and use it in GitHub Desktop.
These are all the methods that we use in order to return the top x merchants by revenue. It seems ugly and it's spread out between 3 or so classes. Also, we aren't sure how to handle converting total revenue and money into a BigDecimal. We just end up with a number like 0.237864E7637 instead of a readable number. Any thoughts on how we can impro…
#First method starts in the Merchant class
def self.most_revenue(rank)
if rank == 0
rank = 1
end
Transaction.get_successful_transaction
@merchant_revenues_array[0..(rank - 1)]
end
#Move into the Transaction class
def self.get_successful_transaction
successful_transactions = @@transactions.select { |transaction| transaction.result == 'success' }
InvoiceItem.gather_invoice_items_from_successful_transactions(successful_transactions)
end
#Move into the InvoiceItem class
def self.gather_invoice_items_from_successful_transactions(successful_transactions)
invoice_items = []
successful_transactions.each do |transaction|
invoice_items << InvoiceItem.find_all_by_invoice_id(transaction.invoice_id)
end
invoice_items.flatten!
sum_invoice_items_for_each_invoice(invoice_items)
end
def self.sum_invoice_items_for_each_invoice(invoice_items)
invoice_totals = Hash.new(0)
invoice_items.each do |invoice_item|
value = (invoice_item.quantity * invoice_item.unit_price)
value = BigDecimal.new(value)
value = value.truncate(2)
key = invoice_item.invoice_id
invoice_totals[key] += value
end
Merchant.sum_invoice_revenue_by_merchant_id(invoice_totals)
end
#Finally move back into the Merchant class to finish
def self.sum_invoice_revenue_by_merchant_id(invoice_totals)
merchant_revenues = Hash.new(0)
invoice_totals.each_pair do |k, v|
invoice = Invoice.find_by_id(k)
key = invoice.merchant_id
merchant_revenues[key] += v
end
@merchant_revenues_array = merchant_revenues.sort_by { |k,v| v }.reverse
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment