2022-09-01 09:48:29 +00:00
|
|
|
<?php
|
|
|
|
|
2022-11-06 11:28:22 +00:00
|
|
|
namespace App\Models;
|
2022-09-01 09:48:29 +00:00
|
|
|
|
2023-01-13 12:26:09 +00:00
|
|
|
use App\Notifications\UserCharged;
|
2022-11-06 11:28:22 +00:00
|
|
|
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo as BelongsToAlias;
|
2023-01-13 12:26:09 +00:00
|
|
|
use Illuminate\Notifications\Notifiable;
|
2022-11-06 11:28:22 +00:00
|
|
|
use function auth;
|
2022-09-01 09:48:29 +00:00
|
|
|
|
|
|
|
class Balance extends Model
|
|
|
|
{
|
2023-01-13 12:26:09 +00:00
|
|
|
use Cachable, Notifiable;
|
2022-09-01 09:48:29 +00:00
|
|
|
|
|
|
|
protected $fillable = [
|
|
|
|
'order_id',
|
|
|
|
'payment',
|
|
|
|
'amount',
|
|
|
|
'user_id',
|
|
|
|
'paid_at',
|
|
|
|
'trade_id'
|
|
|
|
];
|
|
|
|
|
2022-12-27 16:24:41 +00:00
|
|
|
protected $casts = [
|
|
|
|
'paid_at' => 'datetime',
|
|
|
|
'amount' => 'decimal:2',
|
|
|
|
];
|
|
|
|
|
2023-01-05 14:12:47 +00:00
|
|
|
protected static function boot()
|
|
|
|
{
|
|
|
|
parent::boot();
|
|
|
|
|
|
|
|
static::creating(function ($balance) {
|
|
|
|
// $balance->remaining_amount = $balance->amount;
|
|
|
|
$balance->remaining_amount = 0;
|
|
|
|
|
|
|
|
$balance->order_id = date('YmdHis') . $balance->id . rand(1000, 9999);
|
|
|
|
});
|
2023-01-13 12:26:09 +00:00
|
|
|
|
|
|
|
static::updated(function ($balance) {
|
|
|
|
if ($balance->isDirty('paid_at')) {
|
|
|
|
if ($balance->paid_at) {
|
|
|
|
$balance->notify(new UserCharged());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2023-01-05 14:12:47 +00:00
|
|
|
}
|
|
|
|
|
2022-11-06 11:28:22 +00:00
|
|
|
public function user(): BelongsToAlias
|
2022-09-01 09:48:29 +00:00
|
|
|
{
|
|
|
|
return $this->belongsTo(User::class);
|
|
|
|
}
|
2022-09-01 13:15:13 +00:00
|
|
|
|
|
|
|
public function scopeThisUser($query)
|
|
|
|
{
|
|
|
|
return $query->where('user_id', auth()->id());
|
|
|
|
}
|
2023-01-03 07:24:29 +00:00
|
|
|
|
2023-01-05 14:12:47 +00:00
|
|
|
public function canPay(): bool
|
|
|
|
{
|
|
|
|
return !$this->isPaid() && !$this->isOverdue();
|
|
|
|
}
|
|
|
|
|
2023-01-03 07:24:29 +00:00
|
|
|
public function isPaid(): bool
|
|
|
|
{
|
|
|
|
return $this->paid_at !== null;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function isOverdue(): bool
|
|
|
|
{
|
|
|
|
return $this->created_at->diffInDays(now()) > 1 && !$this->isPaid();
|
|
|
|
}
|
2022-09-01 09:48:29 +00:00
|
|
|
}
|