2019-01-13 07:05:54 +01:00
|
|
|
class FinancialLink < ApplicationRecord
|
2018-09-14 19:33:27 +02:00
|
|
|
has_many :bank_transactions
|
2017-10-13 14:36:56 +02:00
|
|
|
has_many :financial_transactions
|
|
|
|
has_many :invoices
|
2019-11-19 12:51:08 +01:00
|
|
|
|
|
|
|
scope :incomplete, -> { with_full_sum.where.not('full_sums.full_sum' => 0) }
|
2021-02-08 02:44:07 +01:00
|
|
|
scope :unused, -> {
|
|
|
|
includes(:bank_transactions, :financial_transactions, :invoices)
|
|
|
|
.where(bank_transactions: { financial_link_id: nil })
|
|
|
|
.where(financial_transactions: { financial_link_id: nil })
|
|
|
|
.where(invoices: { financial_link_id: nil})
|
|
|
|
}
|
2019-11-19 12:51:08 +01:00
|
|
|
scope :with_full_sum, -> {
|
|
|
|
select(:id, :note, :full_sum).joins(<<-SQL)
|
|
|
|
LEFT JOIN (
|
|
|
|
SELECT id, COALESCE(bt_sum, 0) - COALESCE(ft_sum, 0) + COALESCE(i_sum, 0) AS full_sum
|
|
|
|
FROM financial_links fl
|
|
|
|
LEFT JOIN (
|
|
|
|
SELECT financial_link_id, SUM(amount) AS bt_sum
|
|
|
|
FROM bank_transactions
|
|
|
|
GROUP BY financial_link_id
|
|
|
|
) bt ON bt.financial_link_id = fl.id
|
|
|
|
LEFT JOIN (
|
|
|
|
SELECT financial_link_id, SUM(amount) AS ft_sum
|
|
|
|
FROM financial_transactions
|
|
|
|
GROUP BY financial_link_id
|
|
|
|
) ft ON ft.financial_link_id = fl.id
|
|
|
|
LEFT JOIN (
|
|
|
|
SELECT financial_link_id, SUM(amount) AS i_sum
|
|
|
|
FROM invoices
|
|
|
|
GROUP BY financial_link_id
|
|
|
|
) i ON i.financial_link_id = fl.id
|
|
|
|
) full_sums ON full_sums.id = financial_links.id
|
|
|
|
SQL
|
|
|
|
}
|
2021-02-08 02:44:07 +01:00
|
|
|
|
|
|
|
def self.first_unused_or_create
|
|
|
|
unused.first || create
|
|
|
|
end
|
2021-02-08 02:47:05 +01:00
|
|
|
|
|
|
|
def amount
|
|
|
|
bank_transactions.sum(:amount) + invoices.sum(:amount) - financial_transactions.sum(:amount)
|
|
|
|
end
|
2017-10-13 14:36:56 +02:00
|
|
|
end
|