2015-09-10 14:04:36 +02:00
|
|
|
class TransactionsQuery
|
|
|
|
def initialize user
|
|
|
|
@user = user
|
|
|
|
@transactions = Arel::Table.new(:transactions)
|
2015-09-10 15:05:46 +02:00
|
|
|
@perspectived = Arel::Table.new(:perspectived_transactions)
|
|
|
|
@peers = Arel::Table.new(:users).alias('peers')
|
2015-09-10 14:04:36 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def arel
|
|
|
|
Arel::SelectManager.new(ActiveRecord::Base)
|
|
|
|
.from(transactions)
|
2015-09-10 15:05:46 +02:00
|
|
|
.join(@peers).on(@peers[:id].eq(@perspectived[:peer_id]))
|
2015-09-10 14:04:36 +02:00
|
|
|
.project(
|
2015-09-10 15:05:46 +02:00
|
|
|
@perspectived[:amount],
|
|
|
|
@perspectived[:date],
|
|
|
|
@peers[:name].as('peer'),
|
|
|
|
@perspectived[:issuer_id],
|
|
|
|
@perspectived[:message]
|
2015-09-10 14:04:36 +02:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def transactions
|
2015-09-10 15:05:46 +02:00
|
|
|
Arel::Nodes::TableAlias.new(incoming.union(outgoing), @perspectived.name)
|
2015-09-10 14:04:36 +02:00
|
|
|
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'),
|
|
|
|
@transactions[:created_at].as('date'),
|
|
|
|
@transactions[:issuer_id],
|
2015-09-10 15:05:46 +02:00
|
|
|
@transactions[:issuer_type],
|
|
|
|
@transactions[:message]
|
2015-09-10 14:04:36 +02:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def incoming
|
|
|
|
@user.incoming_transactions.arel
|
|
|
|
@transactions
|
|
|
|
.where(@transactions[:debtor_id].eq(@user.id))
|
|
|
|
.project(
|
|
|
|
@transactions[:amount],
|
|
|
|
@transactions[:debtor_id].as('peer_id'),
|
|
|
|
@transactions[:created_at].as('date'),
|
|
|
|
@transactions[:issuer_id],
|
2015-09-10 15:05:46 +02:00
|
|
|
@transactions[:issuer_type],
|
|
|
|
@transactions[:message]
|
2015-09-10 14:04:36 +02:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|