|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Bavix\Wallet\Interfaces\Product; |
|
6
|
|
|
use Bavix\Wallet\Models\Transfer; |
|
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
8
|
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException; |
|
9
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany; |
|
10
|
|
|
use Illuminate\Support\Facades\DB; |
|
11
|
|
|
|
|
12
|
|
|
trait CanBePaid |
|
13
|
|
|
{ |
|
14
|
|
|
|
|
15
|
|
|
use HasWallet; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @param Product $product |
|
19
|
|
|
* @return Transfer |
|
20
|
|
|
* @throws |
|
21
|
|
|
*/ |
|
22
|
|
|
public function pay(Product $product): Transfer |
|
23
|
|
|
{ |
|
24
|
|
|
return $this->transfer($product, $product->getAmountProduct(), $product->getMetaProduct()); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @param Product $product |
|
29
|
|
|
* @return Transfer|null |
|
30
|
|
|
*/ |
|
31
|
|
|
public function safePay(Product $product): ?Transfer |
|
32
|
|
|
{ |
|
33
|
|
|
try { |
|
34
|
|
|
return $this->pay($product); |
|
35
|
|
|
} catch (\Throwable $throwable) { |
|
36
|
|
|
return null; |
|
37
|
|
|
} |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* @param Product $product |
|
42
|
|
|
* @return null|Transfer |
|
43
|
|
|
*/ |
|
44
|
|
|
public function paid(Product $product): ?Transfer |
|
45
|
|
|
{ |
|
46
|
|
|
/** |
|
47
|
|
|
* @var Model $product |
|
48
|
|
|
*/ |
|
49
|
|
|
return $this->transfers() |
|
50
|
|
|
->where('to_type', $product->getMorphClass()) |
|
51
|
|
|
->where('to_id', $product->getKey()) |
|
52
|
|
|
->where('refund', 0) |
|
53
|
|
|
->orderBy('id', 'desc') |
|
54
|
|
|
->firstOrFail(); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @param Product $product |
|
59
|
|
|
* @return bool |
|
60
|
|
|
* @throws |
|
61
|
|
|
*/ |
|
62
|
|
|
public function refund(Product $product): bool |
|
63
|
|
|
{ |
|
64
|
|
|
$transfer = $this->paid($product); |
|
65
|
|
|
|
|
66
|
|
|
if (!$transfer) { |
|
67
|
|
|
throw (new ModelNotFoundException()) |
|
68
|
|
|
->setModel($this->transfers()->getMorphClass()); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return DB::transaction(function () use ($product, $transfer) { |
|
72
|
|
|
$product->transfer($this, $product->getAmountProduct(), $product->getMetaProduct()); |
|
|
|
|
|
|
73
|
|
|
return $transfer->update(['refund' => 1]); |
|
74
|
|
|
}); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
/** |
|
78
|
|
|
* @param Product $product |
|
79
|
|
|
* @return bool |
|
80
|
|
|
*/ |
|
81
|
|
|
public function safeRefund(Product $product): bool |
|
82
|
|
|
{ |
|
83
|
|
|
try { |
|
84
|
|
|
return $this->refund($product); |
|
85
|
|
|
} catch (\Throwable $throwable) { |
|
86
|
|
|
return false; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|
|
90
|
|
|
} |
|
91
|
|
|
|