93 lines
2.4 KiB
PHP
93 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Credit;
|
|
|
|
use App\Enums\Credit\BalanceOperationEnum;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
/**
|
|
* @property int $id
|
|
* @property BalanceOperationEnum $type Enum Credit\BalanceOperationEnum
|
|
* @property float $amount Montant de l'opération
|
|
* @property int $credit_account_id
|
|
* @property string $created_at
|
|
* @property-read \App\Models\Credit\Account $account
|
|
* @property-read \App\Models\Credit\EstimationLog|null $pivot
|
|
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Credit\Estimation> $estimation
|
|
* @mixin \Eloquent
|
|
*/
|
|
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');
|
|
}
|
|
}
|