Lae/app/Models/Balance.php

83 lines
2.0 KiB
PHP
Raw Normal View History

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 14:12:32 +00:00
use App\Events\Users;
use App\Notifications\User\UserCharged;
2023-02-07 09:04:11 +00:00
use function auth;
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-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',
2023-01-30 16:14:07 +00:00
'trade_id',
2022-09-01 09:48:29 +00:00
];
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();
2023-01-13 14:12:32 +00:00
static::creating(function (self $balance) {
2023-01-05 14:12:47 +00:00
// $balance->remaining_amount = $balance->amount;
$balance->remaining_amount = 0;
2023-02-07 09:04:11 +00:00
$balance->order_id = date('YmdHis').$balance->id.rand(1000, 9999);
2023-01-05 14:12:47 +00:00
});
2023-01-13 12:26:09 +00:00
2023-01-13 14:12:32 +00:00
static::created(function (self $balance) {
broadcast(new Users($balance->user, 'balance.created', $balance));
});
static::updated(function (self $balance) {
2023-01-13 12:26:09 +00:00
if ($balance->isDirty('paid_at')) {
if ($balance->paid_at) {
$balance->notify(new UserCharged());
2023-01-13 14:12:32 +00:00
broadcast(new Users($balance->user, 'balance.updated', $balance));
2023-01-16 20:36:43 +00:00
$balance->user->charge($balance->amount, $balance->payment, $balance->order_id);
2023-01-13 12:26:09 +00:00
}
}
});
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-05 14:12:47 +00:00
public function canPay(): bool
{
2023-02-07 09:04:11 +00:00
return ! $this->isPaid() && ! $this->isOverdue();
2023-01-05 14:12:47 +00:00
}
public function isPaid(): bool
{
return $this->paid_at !== null;
}
public function isOverdue(): bool
{
2023-02-07 09:04:11 +00:00
return $this->created_at->diffInDays(now()) > 1 && ! $this->isPaid();
}
2022-09-01 09:48:29 +00:00
}