diff --git a/app/Models/Permohonan.php b/app/Models/Permohonan.php index 1dd7bdd..60c9303 100644 --- a/app/Models/Permohonan.php +++ b/app/Models/Permohonan.php @@ -3,6 +3,7 @@ namespace Modules\Lpj\Models; use Modules\Lpj\Database\Factories\PermohonanFactory; +use Modules\Lpj\Services\PermohonanHistoryService; use Modules\Usermanagement\Models\User; class Permohonan extends Base @@ -38,8 +39,66 @@ class Permohonan extends Base 'registrasi_at', 'jenis_penilaian_id', 'region_id', + 'attachment' ]; + protected static function boot() + { + parent::boot(); + + static::creating(function ($permohonan) { + static::handleFileUpload($permohonan); + }); + + static::updating(function ($permohonan) { + static::handleFileUpload($permohonan); + }); + + static::created(function ($permohonan) { + static::createHistory($permohonan, 'created'); + }); + + static::updated(function ($permohonan) { + static::createHistory($permohonan, 'updated'); + }); + } + + protected static function handleFileUpload($permohonan) + { + if (request()->hasFile('attachment')) { + $file = request()->file('attachment'); + $fileName = time() . '_' . $file->getClientOriginalName(); + $filePath = $file->storeAs('permohonan_attachments', $fileName, 'public'); + + // Delete old file if it exists + if ($permohonan->attachment) { + Storage::disk('public')->delete($permohonan->attachment); + } + + $permohonan->attachment = $filePath; + } + } + + protected static function createHistory($permohonan, $action) + { + $historyService = app(PermohonanHistoryService::class); + + $status = $permohonan->status; + $keterangan = request()->input('keterangan'); // Get keterangan from request + $beforeRequest = $action === 'updated' ? $permohonan->getOriginal() : []; + $afterRequest = $permohonan->toArray(); + $file = $permohonan->attachment ? Storage::disk('public')->path($permohonan->attachment) : null; + + $historyService->createHistory( + $permohonan, + $status, + $keterangan, + $beforeRequest, + $afterRequest, + $file + ); + } + public function user() { return $this->belongsTo(User::class);