Files
persegi/app/Observers/CashRecordObserver.php
T

76 lines
2.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Observers;
use App\Models\ActivityLog;
use App\Models\Approval;
use App\Models\CashRecord;
use App\Models\Vote;
use App\Services\NotificationService;
use Illuminate\Support\Facades\Auth;
class CashRecordObserver
{
public function created(CashRecord $record): void
{
ActivityLog::create([
'user_id' => Auth::id(),
'action' => 'created',
'model_type' => CashRecord::class,
'model_id' => $record->id,
'description' => "Transaksi kas baru: {$record->description} sebesar Rp " . number_format($record->amount, 0, ',', '.'),
]);
// Threshold: 500rb2jt → buat approval ketua + notif
if ($record->amount >= 500_000 && $record->amount <= 2_000_000) {
Approval::firstOrCreate(
['model_type' => CashRecord::class, 'model_id' => $record->id],
['required_approvals' => 1, 'status' => 'pending']
);
NotificationService::toRole('ketua',
'Transaksi Kas Butuh Persetujuan',
"Transaksi \"{$record->description}\" senilai Rp " . number_format($record->amount, 0, ',', '.') . " menunggu persetujuan Anda.",
'warning',
route('filament.admin.resources.cash-records.index')
);
}
// Threshold: > 2jt → buat voting (VoteObserver akan notif semua user)
if ($record->amount > 2_000_000) {
Vote::create([
'title' => "Persetujuan Transaksi: {$record->description}",
'description' => "Transaksi senilai Rp " . number_format($record->amount, 0, ',', '.') . " memerlukan persetujuan voting.",
'type' => 'finance',
'related_id' => $record->id,
'related_type' => CashRecord::class,
'status' => 'open',
'deadline' => now()->addDays(3),
'created_by' => Auth::id() ?? $record->created_by,
]);
}
}
public function updated(CashRecord $record): void
{
if ($record->wasChanged('verified_by') && $record->verified_by !== null) {
ActivityLog::create([
'user_id' => Auth::id(),
'action' => 'verified',
'model_type' => CashRecord::class,
'model_id' => $record->id,
'description' => "Transaksi kas diverifikasi: {$record->description}",
]);
}
}
public function deleting(CashRecord $record): void
{
if ($record->verified_at !== null) {
throw new \Illuminate\Auth\Access\AuthorizationException(
'Transaksi yang sudah diverifikasi tidak dapat dihapus.'
);
}
}
}