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