1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Models; |
4
|
|
|
|
5
|
|
|
use Bavix\Wallet\Interfaces\Customer; |
6
|
|
|
use Bavix\Wallet\Interfaces\WalletFloat; |
7
|
|
|
use Bavix\Wallet\Services\WalletService; |
8
|
|
|
use Bavix\Wallet\Traits\CanPayFloat; |
9
|
|
|
use Bavix\Wallet\Traits\HasGift; |
10
|
|
|
use Illuminate\Database\Eloquent\Model; |
11
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphTo; |
12
|
|
|
use Illuminate\Support\Str; |
13
|
|
|
use function app; |
14
|
|
|
use function array_key_exists; |
15
|
|
|
use function config; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Class Wallet |
19
|
|
|
* @package Bavix\Wallet\Models |
20
|
|
|
* @property string $slug |
21
|
|
|
* @property int $balance |
22
|
|
|
* @property \Bavix\Wallet\Interfaces\Wallet $holder |
23
|
|
|
*/ |
24
|
|
|
class Wallet extends Model implements Customer, WalletFloat |
25
|
|
|
{ |
26
|
|
|
|
27
|
|
|
use CanPayFloat; |
|
|
|
|
28
|
|
|
use HasGift; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var array |
32
|
|
|
*/ |
33
|
|
|
protected $fillable = [ |
34
|
|
|
'holder_type', |
35
|
|
|
'holder_id', |
36
|
|
|
'name', |
37
|
|
|
'slug', |
38
|
|
|
'description', |
39
|
|
|
'balance', |
40
|
|
|
]; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @var array |
44
|
|
|
*/ |
45
|
|
|
protected $casts = [ |
46
|
|
|
'balance' => 'int', |
47
|
|
|
]; |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @return string |
51
|
|
|
*/ |
52
|
|
|
public function getTable(): string |
53
|
|
|
{ |
54
|
|
|
if (!$this->table) { |
55
|
|
|
$this->table = config('wallet.wallet.table'); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return parent::getTable(); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param string $name |
63
|
|
|
* @return void |
64
|
|
|
*/ |
65
|
|
|
public function setNameAttribute(string $name): void |
66
|
|
|
{ |
67
|
|
|
$this->attributes['name'] = $name; |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Must be updated only if the model does not exist |
71
|
|
|
* or the slug is empty |
72
|
|
|
*/ |
73
|
|
|
if (!$this->exists && !array_key_exists('slug', $this->attributes)) { |
74
|
|
|
$this->attributes['slug'] = Str::slug($name); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @return bool |
80
|
|
|
*/ |
81
|
|
|
public function refreshBalance(): bool |
82
|
|
|
{ |
83
|
|
|
return app(WalletService::class)->refresh($this); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* @return int |
88
|
|
|
*/ |
89
|
|
|
public function getAvailableBalance(): int |
90
|
|
|
{ |
91
|
|
|
return $this->transactions() |
92
|
|
|
->where('wallet_id', $this->getKey()) |
93
|
|
|
->where('confirmed', true) |
94
|
|
|
->sum('amount'); |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
/** |
98
|
|
|
* @return MorphTo |
99
|
|
|
*/ |
100
|
|
|
public function holder(): MorphTo |
101
|
|
|
{ |
102
|
|
|
return $this->morphTo(); |
103
|
|
|
} |
104
|
|
|
|
105
|
|
|
} |
106
|
|
|
|