118 lines
2.9 KiB
PHP
118 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
|
|
class Opname extends Model
|
|
{
|
|
use HasFactory, SoftDeletes;
|
|
|
|
protected $fillable = [
|
|
'dealer_id',
|
|
'opname_date',
|
|
'user_id',
|
|
'note',
|
|
'status',
|
|
'approved_by',
|
|
'approved_at',
|
|
'rejection_note'
|
|
];
|
|
|
|
protected $casts = [
|
|
'approved_at' => 'datetime'
|
|
];
|
|
|
|
protected static function booted()
|
|
{
|
|
static::updated(function ($opname) {
|
|
// Jika status berubah menjadi approved
|
|
if ($opname->isDirty('status') && $opname->status === 'approved') {
|
|
// Update stock untuk setiap detail opname
|
|
foreach ($opname->details as $detail) {
|
|
$stock = Stock::firstOrCreate(
|
|
[
|
|
'product_id' => $detail->product_id,
|
|
'dealer_id' => $opname->dealer_id
|
|
],
|
|
['quantity' => 0]
|
|
);
|
|
|
|
// Update stock dengan physical_stock dari opname
|
|
$stock->updateStock(
|
|
$detail->physical_stock,
|
|
$opname,
|
|
"Stock adjustment from approved opname #{$opname->id}"
|
|
);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
public function dealer()
|
|
{
|
|
return $this->belongsTo(Dealer::class);
|
|
}
|
|
|
|
public function details()
|
|
{
|
|
return $this->hasMany(OpnameDetail::class);
|
|
}
|
|
|
|
public function user()
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
public function approver()
|
|
{
|
|
return $this->belongsTo(User::class, 'approved_by');
|
|
}
|
|
|
|
// Method untuk approve opname
|
|
public function approve(User $approver)
|
|
{
|
|
if ($this->status !== 'pending') {
|
|
throw new \Exception('Only pending opnames can be approved');
|
|
}
|
|
|
|
$this->status = 'approved';
|
|
$this->approved_by = $approver->id;
|
|
$this->approved_at = now();
|
|
$this->save();
|
|
|
|
return $this;
|
|
}
|
|
|
|
// Method untuk reject opname
|
|
public function reject(User $rejector, string $note)
|
|
{
|
|
if ($this->status !== 'pending') {
|
|
throw new \Exception('Only pending opnames can be rejected');
|
|
}
|
|
|
|
$this->status = 'rejected';
|
|
$this->approved_by = $rejector->id;
|
|
$this->approved_at = now();
|
|
$this->rejection_note = $note;
|
|
$this->save();
|
|
|
|
return $this;
|
|
}
|
|
|
|
// Method untuk submit opname untuk approval
|
|
public function submit()
|
|
{
|
|
if ($this->status !== 'draft') {
|
|
throw new \Exception('Only draft opnames can be submitted');
|
|
}
|
|
|
|
$this->status = 'pending';
|
|
$this->save();
|
|
|
|
return $this;
|
|
}
|
|
}
|