53 lines
1.7 KiB
PHP
53 lines
1.7 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Observers;
|
||
|
|
|
||
|
|
use App\Models\Activity;
|
||
|
|
use App\Models\ActivityLog;
|
||
|
|
use Illuminate\Support\Facades\Auth;
|
||
|
|
|
||
|
|
class ActivityObserver
|
||
|
|
{
|
||
|
|
public function updated(Activity $activity): void
|
||
|
|
{
|
||
|
|
if ($activity->wasChanged('status')) {
|
||
|
|
$old = $activity->getOriginal('status');
|
||
|
|
$new = $activity->status;
|
||
|
|
|
||
|
|
// Validasi workflow: draft→pending, pending→approved/rejected
|
||
|
|
$allowed = [
|
||
|
|
'draft' => ['pending'],
|
||
|
|
'pending' => ['approved', 'rejected'],
|
||
|
|
];
|
||
|
|
|
||
|
|
if (isset($allowed[$old]) && ! in_array($new, $allowed[$old])) {
|
||
|
|
throw new \Exception("Transisi status dari {$old} ke {$new} tidak diizinkan.");
|
||
|
|
}
|
||
|
|
|
||
|
|
// Wajib isi executed_at & execution_notes jika sudah approved dan mau ditandai selesai
|
||
|
|
if ($new === 'approved' && $activity->wasChanged('executed_at') && empty($activity->execution_notes)) {
|
||
|
|
throw new \Exception('Catatan pelaksanaan wajib diisi.');
|
||
|
|
}
|
||
|
|
|
||
|
|
ActivityLog::create([
|
||
|
|
'user_id' => Auth::id(),
|
||
|
|
'action' => 'status_changed',
|
||
|
|
'model_type' => Activity::class,
|
||
|
|
'model_id' => $activity->id,
|
||
|
|
'description' => "Status kegiatan '{$activity->title}' diubah dari {$old} menjadi {$new}",
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public function created(Activity $activity): void
|
||
|
|
{
|
||
|
|
ActivityLog::create([
|
||
|
|
'user_id' => Auth::id(),
|
||
|
|
'action' => 'created',
|
||
|
|
'model_type' => Activity::class,
|
||
|
|
'model_id' => $activity->id,
|
||
|
|
'description' => "Kegiatan baru dibuat: {$activity->title}",
|
||
|
|
]);
|
||
|
|
}
|
||
|
|
}
|