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