71 lines
1.8 KiB
PHP
71 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\StockChangeType;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class StockLog extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'stock_id',
|
|
'source_type',
|
|
'source_id',
|
|
'previous_quantity',
|
|
'new_quantity',
|
|
'quantity_change',
|
|
'change_type',
|
|
'description',
|
|
'user_id'
|
|
];
|
|
|
|
protected $casts = [
|
|
'change_type' => StockChangeType::class,
|
|
'previous_quantity' => 'decimal:2',
|
|
'new_quantity' => 'decimal:2',
|
|
'quantity_change' => 'decimal:2'
|
|
];
|
|
|
|
protected static function booted()
|
|
{
|
|
static::creating(function ($stockLog) {
|
|
// Hitung quantity_change
|
|
$stockLog->quantity_change = $stockLog->new_quantity - $stockLog->previous_quantity;
|
|
|
|
// Tentukan change_type berdasarkan quantity_change
|
|
if ($stockLog->quantity_change == 0) {
|
|
// Jika quantity sama persis (tanpa toleransi)
|
|
$stockLog->change_type = StockChangeType::NO_CHANGE;
|
|
} else if ($stockLog->quantity_change > 0) {
|
|
$stockLog->change_type = StockChangeType::INCREASE;
|
|
} else {
|
|
$stockLog->change_type = StockChangeType::DECREASE;
|
|
}
|
|
});
|
|
}
|
|
|
|
public function stock()
|
|
{
|
|
return $this->belongsTo(Stock::class);
|
|
}
|
|
|
|
public function user()
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
public function source()
|
|
{
|
|
return $this->morphTo();
|
|
}
|
|
|
|
// Helper method untuk mendapatkan label change_type
|
|
public function getChangeTypeLabelAttribute()
|
|
{
|
|
return $this->change_type->label();
|
|
}
|
|
}
|