ldc-supportweb/app/Models/Credit/CreditLog.php

89 lines
2.3 KiB
PHP
Raw Permalink Normal View History

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