Skip to content

Commit 1c4785b

Browse files
committed
Add method to get balance and decrementBalance
1 parent fd80185 commit 1c4785b

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

src/Models/Wallet.php

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,15 @@ public function walletType()
2525
return $this->belongsTo(WalletType::class);
2626
}
2727

28+
public function getBalanceAttribute()
29+
{
30+
if ($this->walletType->decimals === 0) {
31+
return $this->raw_balance;
32+
}
33+
34+
return $this->raw_balance * pow(10, $this->walletType->decimals);
35+
}
36+
2837
/**
2938
* @param $transaction WalletTransaction|integer
3039
* @throws Exception
@@ -50,9 +59,38 @@ public function incrementBalance($transaction)
5059
return;
5160
}
5261

53-
private function createWalletLedgerEntry($transaction, $newRunningRawBalance)
62+
/**
63+
* @param $transaction WalletTransaction|integer
64+
* @throws Exception
65+
*/
66+
public function decrementBalance($transaction)
67+
{
68+
if (is_int($transaction)) {
69+
$this->decrement('raw_balance', $transaction);
70+
$this->createWalletLedgerEntry($transaction, $this->raw_balance, 'decrement');
71+
72+
return;
73+
}
74+
75+
if (! $transaction instanceof WalletTransaction) {
76+
throw new Exception('Decrement balance expects parameter to be an integer or a WalletTransaction object.');
77+
}
78+
79+
$this->decrement('raw_balance', $transaction->getAmount());
80+
81+
// Record in ledger
82+
$this->createWalletLedgerEntry($transaction, $this->raw_balance, 'decrement');
83+
84+
return;
85+
}
86+
87+
private function createWalletLedgerEntry($transaction, $newRunningRawBalance, $type = 'increment')
5488
{
5589
if (is_int($transaction)) {
90+
if ($type === 'decrement') {
91+
$transaction = -$transaction;
92+
}
93+
5694
return WalletLedger::query()->create([
5795
'wallet_id' => $this->id,
5896
'amount' => $transaction,
@@ -64,11 +102,17 @@ private function createWalletLedgerEntry($transaction, $newRunningRawBalance)
64102
throw new Exception('Increment balance expects parameter to be an integer or a WalletTransaction object.');
65103
}
66104

105+
$amount = $transaction->getAmount();
106+
107+
if ($type === 'decrement') {
108+
$amount = -$amount;
109+
}
110+
67111
return WalletLedger::query()->create([
68112
'wallet_id' => $this->id,
69113
'transaction_id' => $transaction->id,
70114
'transaction_type' => get_class($transaction),
71-
'amount' => $transaction->getAmount(),
115+
'amount' => $amount,
72116
'running_raw_balance' => $newRunningRawBalance,
73117
]);
74118
}

0 commit comments

Comments
 (0)