tab/app/controllers/concerns/transactions_query.rb

74 lines
1.9 KiB
Ruby
Raw Normal View History

class TransactionsQuery
2015-09-10 14:40:15 +00:00
attr_reader :arel_table
def initialize user
@user = user
@transactions = Arel::Table.new(:transactions)
@perspectived = Arel::Table.new(:perspectived_transactions)
@peers = Arel::Table.new(:users).alias('peers')
@arel_table = Arel::Table.new("#{@user.name}_transactions")
end
2015-09-10 14:40:15 +00:00
def query
2015-09-10 13:47:54 +00:00
Arel::SelectManager.new(ActiveRecord::Base)
2015-09-10 14:40:15 +00:00
.from(arel)
2015-09-10 13:47:54 +00:00
end
2015-09-10 14:40:15 +00:00
def arel
Arel::Nodes::TableAlias.new(
issued_by(User).union(:all, issued_by(Client)),
2015-09-10 14:40:15 +00:00
arel_table.name
)
end
2015-09-10 13:47:54 +00:00
def issued_by klass
issuers = klass.arel_table.alias('issuer')
Arel::SelectManager.new(ActiveRecord::Base)
.from(transactions)
.join(@peers).on(@peers[:id].eq(@perspectived[:peer_id]))
2015-09-10 13:47:54 +00:00
.join(issuers).on(issuers[:id].eq(@perspectived[:issuer_id]))
.where(@perspectived[:issuer_type].eq(klass.name))
.project(
@perspectived[:amount],
2015-09-10 17:41:47 +00:00
@perspectived[:time],
2015-09-10 13:47:54 +00:00
@perspectived[:message],
@peers[:name].as('peer'),
2015-09-10 13:47:54 +00:00
issuers[:name].as('issuer')
)
end
def transactions
2015-09-10 13:47:54 +00:00
Arel::Nodes::TableAlias.new(
2015-09-10 13:59:22 +00:00
incoming.union(:all, outgoing),
2015-09-10 13:47:54 +00:00
@perspectived.name
)
end
def outgoing
@transactions
.where(@transactions[:debtor_id].eq(@user.id))
.project(
(@transactions[:amount]*Arel::Nodes::SqlLiteral.new("-1")).as('amount'),
@transactions[:creditor_id].as('peer_id'),
2015-09-10 17:41:47 +00:00
@transactions[:created_at].as('time'),
@transactions[:issuer_id],
@transactions[:issuer_type],
@transactions[:message]
)
end
def incoming
@user.incoming_transactions.arel
@transactions
2015-09-11 10:07:39 +00:00
.where(@transactions[:creditor_id].eq(@user.id))
.project(
@transactions[:amount],
2015-09-11 10:07:39 +00:00
@transactions[:debtor_id].as('peer_id'),
2015-09-10 17:41:47 +00:00
@transactions[:created_at].as('time'),
@transactions[:issuer_id],
@transactions[:issuer_type],
@transactions[:message]
)
end
end