Skip to content

Commit 986bed5

Browse files
author
Babichev Maxim
committed
add refresh balance
1 parent 72daf69 commit 986bed5

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/Commands/RefreshBalance.php

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
3+
namespace Bavix\Commands;
4+
5+
use Illuminate\Database\Query\JoinClause;
6+
use Illuminate\Support\Facades\DB;
7+
use Illuminate\Console\Command;
8+
use function config;
9+
10+
class RefreshBalance extends Command
11+
{
12+
13+
/**
14+
* The name and signature of the console command.
15+
*
16+
* @var string
17+
*/
18+
protected $signature = 'wallet:refresh';
19+
20+
/**
21+
* The console command description.
22+
*
23+
* @var string
24+
*/
25+
protected $description = 'Recalculates all wallets';
26+
27+
/**
28+
* @return void
29+
*/
30+
public function handle(): void
31+
{
32+
DB::transaction(function () {
33+
$wallet = config('wallet.wallet.table');
34+
$trans = config('wallet.transaction.table');
35+
36+
$availableBalance = DB::table($trans)
37+
->select('wallet_id', DB::raw('sum(amount) balance'))
38+
->where('confirmed', true)
39+
->groupBy('wallet_id');
40+
41+
$joinClause = function (JoinClause $join) use ($wallet) {
42+
$join->on("$wallet.id", '=', 'b.wallet_id');
43+
};
44+
45+
DB::table($wallet)->update(['balance' => 0]);
46+
DB::table($wallet)
47+
->joinSub($availableBalance, 'b', $joinClause, null, null, 'left')
48+
->update(['balance' => DB::raw('b.balance')]);
49+
});
50+
}
51+
52+
}

src/WalletServiceProvider.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Bavix\Wallet;
44

5+
use Bavix\Commands\RefreshBalance;
56
use Bavix\Wallet\Models\Transaction;
67
use Bavix\Wallet\Models\Transfer;
78
use Bavix\Wallet\Models\Wallet;
@@ -33,6 +34,8 @@ public function boot(): void
3334
return;
3435
}
3536

37+
$this->commands([RefreshBalance::class]);
38+
3639
$this->loadMigrationsFrom([
3740
__DIR__ . '/../database/migrations_v1',
3841
__DIR__ . '/../database/migrations_v2',

0 commit comments

Comments
 (0)