1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Commands; |
4
|
|
|
|
5
|
|
|
use Bavix\Wallet\Models\Wallet; |
6
|
|
|
use Bavix\Wallet\Services\ProxyService; |
7
|
|
|
use Illuminate\Console\Command; |
8
|
|
|
use Illuminate\Database\Query\JoinClause; |
9
|
|
|
use Illuminate\Database\SQLiteConnection; |
10
|
|
|
use Illuminate\Support\Facades\DB; |
11
|
|
|
use function config; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class RefreshBalance |
15
|
|
|
* @package Bavix\Wallet\Commands |
16
|
|
|
* @codeCoverageIgnore |
17
|
|
|
*/ |
18
|
|
|
class RefreshBalance extends Command |
19
|
|
|
{ |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* The name and signature of the console command. |
23
|
|
|
* |
24
|
|
|
* @var string |
25
|
|
|
*/ |
26
|
|
|
protected $signature = 'wallet:refresh'; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* The console command description. |
30
|
|
|
* |
31
|
|
|
* @var string |
32
|
|
|
*/ |
33
|
|
|
protected $description = 'Recalculates all wallets'; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @return void |
37
|
|
|
*/ |
38
|
|
|
public function handle(): void |
39
|
|
|
{ |
40
|
|
|
app(ProxyService::class)->fresh(); |
41
|
|
|
DB::transaction(function() { |
42
|
|
|
$wallet = config('wallet.wallet.table'); |
43
|
|
|
DB::table($wallet)->update(['balance' => 0]); |
44
|
|
|
|
45
|
|
|
if (DB::connection() instanceof SQLiteConnection) { |
46
|
|
|
$this->sqliteUpdate(); |
47
|
|
|
} else { |
48
|
|
|
$this->multiUpdate(); |
49
|
|
|
} |
50
|
|
|
}); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* SQLite |
55
|
|
|
* |
56
|
|
|
* @return void |
57
|
|
|
*/ |
58
|
|
|
protected function sqliteUpdate(): void |
59
|
|
|
{ |
60
|
|
|
Wallet::query()->each(static function (Wallet $wallet) { |
61
|
|
|
$wallet->refreshBalance(); |
62
|
|
|
}); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* MySQL/PgSQL |
67
|
|
|
* |
68
|
|
|
* @return void |
69
|
|
|
*/ |
70
|
|
|
protected function multiUpdate(): void |
71
|
|
|
{ |
72
|
|
|
$wallet = config('wallet.wallet.table'); |
73
|
|
|
$trans = config('wallet.transaction.table'); |
74
|
|
|
$availableBalance = DB::table($trans) |
75
|
|
|
->select('wallet_id', DB::raw('sum(amount) balance')) |
76
|
|
|
->where('confirmed', true) |
77
|
|
|
->groupBy('wallet_id'); |
78
|
|
|
|
79
|
|
|
$joinClause = static function(JoinClause $join) use ($wallet) { |
80
|
|
|
$join->on("$wallet.id", '=', 'b.wallet_id'); |
81
|
|
|
}; |
82
|
|
|
|
83
|
|
|
DB::table($wallet) |
84
|
|
|
->joinSub($availableBalance, 'b', $joinClause, null, null, 'left') |
85
|
|
|
->update(['balance' => DB::raw('b.balance')]); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
} |
89
|
|
|
|