1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Traits; |
4
|
|
|
|
5
|
|
|
use Bavix\Wallet\Exceptions\ConfirmedInvalid; |
6
|
|
|
use Bavix\Wallet\Exceptions\WalletOwnerInvalid; |
7
|
|
|
use Bavix\Wallet\Models\Transaction; |
8
|
|
|
use Bavix\Wallet\Services\CommonService; |
9
|
|
|
use Bavix\Wallet\Services\WalletService; |
10
|
|
|
use Illuminate\Support\Facades\DB; |
11
|
|
|
|
12
|
|
|
trait CanConfirm |
13
|
|
|
{ |
14
|
|
|
|
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param Transaction $transaction |
18
|
|
|
* @return bool |
19
|
|
|
*/ |
20
|
4 |
|
public function confirm(Transaction $transaction): bool |
21
|
|
|
{ |
22
|
|
|
return DB::transaction(function() use ($transaction) { |
23
|
4 |
|
$wallet = app(WalletService::class) |
24
|
4 |
|
->getWallet($this); |
|
|
|
|
25
|
|
|
|
26
|
4 |
|
if (!$wallet->refreshBalance()) { |
27
|
|
|
// @codeCoverageIgnoreStart |
28
|
|
|
return false; |
29
|
|
|
// @codeCoverageIgnoreEnd |
30
|
|
|
} |
31
|
|
|
|
32
|
4 |
|
if ($transaction->type === Transaction::TYPE_WITHDRAW) { |
33
|
1 |
|
app(CommonService::class)->verifyWithdraw( |
34
|
1 |
|
$wallet, |
35
|
1 |
|
\abs($transaction->amount) |
|
|
|
|
36
|
|
|
); |
37
|
|
|
} |
38
|
|
|
|
39
|
3 |
|
return $this->forceConfirm($transaction); |
40
|
4 |
|
}); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param Transaction $transaction |
45
|
|
|
* @return bool |
46
|
|
|
*/ |
47
|
1 |
|
public function safeConfirm(Transaction $transaction): bool |
48
|
|
|
{ |
49
|
|
|
try { |
50
|
1 |
|
return $this->confirm($transaction); |
51
|
1 |
|
} catch (\Throwable $throwable) { |
52
|
1 |
|
return false; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param Transaction $transaction |
58
|
|
|
* @return bool |
59
|
|
|
* @throws ConfirmedInvalid |
60
|
|
|
* @throws WalletOwnerInvalid |
61
|
|
|
*/ |
62
|
4 |
|
public function forceConfirm(Transaction $transaction): bool |
63
|
|
|
{ |
64
|
|
|
return DB::transaction(function() use ($transaction) { |
65
|
|
|
|
66
|
4 |
|
$wallet = app(WalletService::class) |
67
|
4 |
|
->getWallet($this); |
|
|
|
|
68
|
|
|
|
69
|
4 |
|
if ($transaction->confirmed) { |
70
|
1 |
|
throw new ConfirmedInvalid(); // todo |
71
|
|
|
} |
72
|
|
|
|
73
|
3 |
|
if ($wallet->id !== $transaction->wallet_id) { |
|
|
|
|
74
|
1 |
|
throw new WalletOwnerInvalid(); // todo |
75
|
|
|
} |
76
|
|
|
|
77
|
2 |
|
return $transaction->update(['confirmed' => true]) && |
78
|
|
|
|
79
|
|
|
// update balance |
80
|
2 |
|
app(CommonService::class) |
81
|
2 |
|
->addBalance($wallet, $transaction->amount); |
82
|
|
|
|
83
|
4 |
|
}); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
} |
87
|
|
|
|