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
|
4 |
|
$self = $this; |
23
|
|
|
return DB::transaction(static function() use ($self, $transaction) { |
24
|
4 |
|
$wallet = app(WalletService::class) |
25
|
4 |
|
->getWallet($self); |
|
|
|
|
26
|
|
|
|
27
|
4 |
|
if (!$wallet->refreshBalance()) { |
28
|
|
|
// @codeCoverageIgnoreStart |
29
|
|
|
return false; |
30
|
|
|
// @codeCoverageIgnoreEnd |
31
|
|
|
} |
32
|
|
|
|
33
|
4 |
|
if ($transaction->type === Transaction::TYPE_WITHDRAW) { |
34
|
1 |
|
app(CommonService::class)->verifyWithdraw( |
35
|
1 |
|
$wallet, |
36
|
1 |
|
\abs($transaction->amount) |
|
|
|
|
37
|
|
|
); |
38
|
|
|
} |
39
|
|
|
|
40
|
3 |
|
return $self->forceConfirm($transaction); |
41
|
4 |
|
}); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param Transaction $transaction |
46
|
|
|
* @return bool |
47
|
|
|
*/ |
48
|
1 |
|
public function safeConfirm(Transaction $transaction): bool |
49
|
|
|
{ |
50
|
|
|
try { |
51
|
1 |
|
return $this->confirm($transaction); |
52
|
1 |
|
} catch (\Throwable $throwable) { |
53
|
1 |
|
return false; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param Transaction $transaction |
59
|
|
|
* @return bool |
60
|
|
|
* @throws ConfirmedInvalid |
61
|
|
|
* @throws WalletOwnerInvalid |
62
|
|
|
*/ |
63
|
4 |
|
public function forceConfirm(Transaction $transaction): bool |
64
|
|
|
{ |
65
|
4 |
|
$self = $this; |
66
|
|
|
return DB::transaction(static function() use ($self, $transaction) { |
67
|
|
|
|
68
|
4 |
|
$wallet = app(WalletService::class) |
69
|
4 |
|
->getWallet($self); |
|
|
|
|
70
|
|
|
|
71
|
4 |
|
if ($transaction->confirmed) { |
72
|
1 |
|
throw new ConfirmedInvalid(trans('wallet::errors.confirmed_invalid')); |
|
|
|
|
73
|
|
|
} |
74
|
|
|
|
75
|
3 |
|
if ($wallet->id !== $transaction->wallet_id) { |
|
|
|
|
76
|
1 |
|
throw new WalletOwnerInvalid(trans('wallet::errors.owner_invalid')); |
|
|
|
|
77
|
|
|
} |
78
|
|
|
|
79
|
2 |
|
return $transaction->update(['confirmed' => true]) && |
80
|
|
|
|
81
|
|
|
// update balance |
82
|
2 |
|
app(CommonService::class) |
83
|
2 |
|
->addBalance($wallet, $transaction->amount); |
84
|
|
|
|
85
|
4 |
|
}); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
} |
89
|
|
|
|