88 lines
2.1 KiB
PHP
88 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Credit;
|
|
|
|
use App\Enums\Credit\BalanceOperationEnum;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
/**
|
|
* @property BalanceOperationEnum $type
|
|
* @property double $amount
|
|
* @property Account $credit_account_id
|
|
* @property date $created_at
|
|
*/
|
|
class CreditLog extends Model
|
|
{
|
|
/**
|
|
* Indicates if the model should be timestamped.
|
|
*
|
|
* @var boolean
|
|
*/
|
|
public $timestamps = false;
|
|
|
|
/**
|
|
* The attributes that are fillable.
|
|
*
|
|
* @var array
|
|
*/
|
|
protected $fillable = [
|
|
'type',
|
|
'amount',
|
|
'credit_account_id',
|
|
'created_at',
|
|
];
|
|
|
|
/**
|
|
* The attributes that should be cast.
|
|
*
|
|
* @var array
|
|
*/
|
|
protected $casts = [
|
|
'type' => BalanceOperationEnum::class
|
|
];
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted()
|
|
{
|
|
static::creating(function (self $model) {
|
|
$model->created_at = now();
|
|
if ($model->type->equals(BalanceOperationEnum::debit)) {
|
|
$model->account->balance = $model->account->balance - $model->amount;
|
|
}
|
|
if ($model->type->equals(BalanceOperationEnum::credit)) {
|
|
$model->account->balance = $model->account->balance + $model->amount;
|
|
}
|
|
$model->account->saveOrFail();
|
|
});
|
|
static::deleting(function () {
|
|
throw new \Error('Action impossible');
|
|
});
|
|
}
|
|
|
|
// * RELATIONSHIPS
|
|
|
|
/**
|
|
* BelongsToMany estimation relation (1 nullable)
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
|
|
*/
|
|
public function estimation()
|
|
{
|
|
return $this->belongsToMany(Estimation::class, EstimationLog::class, 'credit_log_id', 'credit_estimation_id')
|
|
->withTimestamps();
|
|
}
|
|
|
|
/**
|
|
* BelongsTo account relation
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
|
*/
|
|
public function account()
|
|
{
|
|
return $this->belongsTo(Account::class, 'credit_account_id');
|
|
}
|
|
}
|