Class: SimpleWallet::Account

Inherits:
ApplicationRecord
  • Object
show all
Defined in:
app/models/simple_wallet/account.rb

Instance Method Summary collapse

Instance Method Details

#recalculate_balance!Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'app/models/simple_wallet/account.rb', line 11

def recalculate_balance!
  SimpleWallet::Account.where(id: id).update_all(<<~SQL)
    balance = (
      SELECT COALESCE(SUM(amount), 0)
      FROM simple_wallet_transactions
      WHERE simple_wallet_transactions.account_id = simple_wallet_accounts.id
    ),
    income = (
      SELECT COALESCE(SUM(amount), 0)
      FROM simple_wallet_transactions
      WHERE
        simple_wallet_transactions.type = 'SimpleWallet::Transaction::Credit'
        AND simple_wallet_transactions.account_id = simple_wallet_accounts.id
    ),
    outcome = (
      SELECT COALESCE(SUM(amount), 0)
      FROM simple_wallet_transactions
      WHERE
        simple_wallet_transactions.type = 'SimpleWallet::Transaction::Debit'
        AND simple_wallet_transactions.account_id = simple_wallet_accounts.id
    )
  SQL
end