From 02c04a43460f76b4b77b9aba2709979019b24af1 Mon Sep 17 00:00:00 2001 From: Daeng Deni Mardaeni Date: Thu, 14 Nov 2024 03:14:26 +0700 Subject: [PATCH] Tambah fungsi unggah lampiran dan riwayat permohonan Menambahkan fungsi untuk mengunggah lampiran saat membuat dan memperbarui permohonan, serta mencatat riwayat perubahan permohonan dengan menggunakan PermohonanHistoryService. Fitur ini memastikan file lampiran tersimpan dengan benar dan perubahan terhadap permohonan terdokumentasi. --- app/Models/Permohonan.php | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) 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);