diff --git a/app/Console/Commands/PruneTrashCommand.php b/app/Console/Commands/PruneTrashCommand.php new file mode 100644 index 0000000..fb26c9e --- /dev/null +++ b/app/Console/Commands/PruneTrashCommand.php @@ -0,0 +1,45 @@ +option('days'); + $days = $daysOption !== null ? (int) $daysOption : $trashService->getRetentionDays(); + + if ($days <= 0) { + $this->info('Retensi otomatis tong sampah dinonaktifkan (0 hari / mode manual). Tidak ada data yang dihapus.'); + return Command::SUCCESS; + } + + $this->info("Menjalankan pembersihan tong sampah dengan retensi: {$days} hari..."); + + $prunedCount = $trashService->pruneOldTrash($days); + + $this->info("Pembersihan selesai. {$prunedCount} record berhasil dihapus permanen dari sistem."); + + return Command::SUCCESS; + } +} diff --git a/app/Http/Controllers/Admin/TrashController.php b/app/Http/Controllers/Admin/TrashController.php new file mode 100644 index 0000000..8831bc0 --- /dev/null +++ b/app/Http/Controllers/Admin/TrashController.php @@ -0,0 +1,157 @@ +query('category', 'all'); + if ($selectedCategory === 'all') { + $selectedCategory = null; + } + + $search = $request->query('q'); + $page = (int) $request->query('page', 1); + + $categories = TrashService::getCategoryDefinitions(); + $categoryCounts = $this->trashService->getCategoryCounts(); + $retentionDays = $this->trashService->getRetentionDays(); + $items = $this->trashService->getTrashedItems($selectedCategory, $search, 15, $page); + + return view('admin.trash.index', compact( + 'items', + 'categories', + 'categoryCounts', + 'selectedCategory', + 'search', + 'retentionDays' + )); + } + + /** + * Pulihkan data yang terhapus kembali ke sistem. + */ + public function restore(string $category, int $id): RedirectResponse + { + $success = $this->trashService->restoreItem($category, $id); + + if (!$success) { + return back()->with('error', 'Data tidak ditemukan di tong sampah atau gagal dipulihkan.'); + } + + $catDefinitions = TrashService::getCategoryDefinitions(); + $label = $catDefinitions[$category]['label'] ?? $category; + + AdminActivityLog::record( + actionType: 'restore', + module: 'Tong Sampah', + description: "Memulihkan data pada kategori '{$label}' (ID: {$id}).", + targetType: $category, + targetId: $id + ); + + return back()->with('success', "Data '{$label}' berhasil dipulihkan ke sistem aktif."); + } + + /** + * Hapus data secara permanen dari basis data. + */ + public function forceDelete(string $category, int $id): RedirectResponse + { + $success = $this->trashService->forceDeleteItem($category, $id); + + if (!$success) { + return back()->with('error', 'Data tidak ditemukan di tong sampah atau gagal dihapus permanen.'); + } + + $catDefinitions = TrashService::getCategoryDefinitions(); + $label = $catDefinitions[$category]['label'] ?? $category; + + AdminActivityLog::record( + actionType: 'delete', + module: 'Tong Sampah', + description: "Menghapus permanen data pada kategori '{$label}' (ID: {$id}).", + targetType: $category, + targetId: $id + ); + + return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem."); + } + + /** + * Kosongkan seluruh tong sampah atau kategori tertentu. + */ + public function emptyAll(Request $request): RedirectResponse + { + $request->validate([ + 'confirm_text' => ['required', 'in:KOSONGKAN'], + 'category' => ['nullable', 'string'], + ], [ + 'confirm_text.in' => 'Konfirmasi tidak valid. Ketik "KOSONGKAN" dengan huruf kapital untuk melanjutkan.', + ]); + + $category = $request->input('category'); + if ($category === 'all') { + $category = null; + } + + $deletedCount = $this->trashService->emptyTrash($category); + + $catDefinitions = TrashService::getCategoryDefinitions(); + $targetScope = $category && isset($catDefinitions[$category]) + ? "kategori '{$catDefinitions[$category]['label']}'" + : 'seluruh kategori'; + + AdminActivityLog::record( + actionType: 'delete', + module: 'Tong Sampah', + description: "Mengosongkan tong sampah ({$targetScope}) - {$deletedCount} data dihapus permanen.", + targetType: 'RecycleBin', + newValues: ['deleted_count' => $deletedCount, 'scope' => $category ?? 'all'] + ); + + return back()->with('success', "Tong sampah ({$targetScope}) berhasil dikosongkan. Sebanyak {$deletedCount} data telah dihapus permanen."); + } + + /** + * Perbarui durasi retensi otomatis (auto-delete). + */ + public function updateRetention(Request $request): RedirectResponse + { + $validated = $request->validate([ + 'retention_days' => ['required', 'integer', 'in:0,30,60,90'], + ], [ + 'retention_days.in' => 'Pilihan periode retensi tidak valid (hanya 30, 60, 90 hari atau Nonaktif/Manual).', + ]); + + $days = (int) $validated['retention_days']; + $this->trashService->setRetentionDays($days); + + $daysText = $days > 0 ? "{$days} hari" : 'Nonaktif (Pembersihan Manual)'; + + AdminActivityLog::record( + actionType: 'update', + module: 'Tong Sampah', + description: "Mengubah pengaturan retensi otomatis tong sampah menjadi {$daysText}.", + targetType: 'SystemSetting', + newValues: ['trash_retention_days' => $days] + ); + + return back()->with('success', "Pengaturan retensi otomatis berhasil diperbarui ke {$daysText}."); + } +} diff --git a/app/Models/Employee.php b/app/Models/Employee.php index 048cf00..6b0ec60 100644 --- a/app/Models/Employee.php +++ b/app/Models/Employee.php @@ -9,10 +9,11 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\SoftDeletes; class Employee extends Model { - use HasFactory; + use HasFactory, SoftDeletes; public const TYPE_KARYAWAN = 'Karyawan'; public const TYPE_SUKON = 'Sukon'; diff --git a/app/Models/EmployeeSimper.php b/app/Models/EmployeeSimper.php index a46158e..fa5567c 100644 --- a/app/Models/EmployeeSimper.php +++ b/app/Models/EmployeeSimper.php @@ -7,10 +7,11 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\SoftDeletes; class EmployeeSimper extends Model { - use HasFactory; + use HasFactory, SoftDeletes; public const STATUS_ACTIVE = 'active'; public const STATUS_EXPIRED = 'expired'; diff --git a/app/Models/Gate.php b/app/Models/Gate.php index 31ea1c5..ce0552d 100644 --- a/app/Models/Gate.php +++ b/app/Models/Gate.php @@ -5,10 +5,11 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\SoftDeletes; class Gate extends Model { - use HasFactory; + use HasFactory, SoftDeletes; protected $fillable = [ 'code', diff --git a/app/Models/P2hRecord.php b/app/Models/P2hRecord.php index 73ab7bf..d62d7a1 100644 --- a/app/Models/P2hRecord.php +++ b/app/Models/P2hRecord.php @@ -6,10 +6,11 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\SoftDeletes; class P2hRecord extends Model { - use HasFactory; + use HasFactory, SoftDeletes; protected $fillable = [ 'transaction_no', diff --git a/app/Models/P2hRecordItem.php b/app/Models/P2hRecordItem.php index 8686668..f3b2f01 100644 --- a/app/Models/P2hRecordItem.php +++ b/app/Models/P2hRecordItem.php @@ -5,10 +5,11 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\SoftDeletes; class P2hRecordItem extends Model { - use HasFactory; + use HasFactory, SoftDeletes; protected $fillable = [ 'p2h_record_id', diff --git a/app/Models/P2hTemplate.php b/app/Models/P2hTemplate.php index 96fb246..30399f0 100644 --- a/app/Models/P2hTemplate.php +++ b/app/Models/P2hTemplate.php @@ -5,10 +5,11 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\SoftDeletes; class P2hTemplate extends Model { - use HasFactory; + use HasFactory, SoftDeletes; protected $fillable = [ 'code', diff --git a/app/Models/P2hTemplateItem.php b/app/Models/P2hTemplateItem.php index 3c7a031..ec80d1c 100644 --- a/app/Models/P2hTemplateItem.php +++ b/app/Models/P2hTemplateItem.php @@ -5,10 +5,11 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\SoftDeletes; class P2hTemplateItem extends Model { - use HasFactory; + use HasFactory, SoftDeletes; protected $fillable = [ 'template_id', diff --git a/app/Models/SecurityGuard.php b/app/Models/SecurityGuard.php index 419d786..7389892 100644 --- a/app/Models/SecurityGuard.php +++ b/app/Models/SecurityGuard.php @@ -5,10 +5,11 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\SoftDeletes; class SecurityGuard extends Model { - use HasFactory; + use HasFactory, SoftDeletes; protected $fillable = [ 'badge_id', diff --git a/app/Models/SimperType.php b/app/Models/SimperType.php index a407e92..87252b6 100644 --- a/app/Models/SimperType.php +++ b/app/Models/SimperType.php @@ -7,10 +7,11 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\SoftDeletes; class SimperType extends Model { - use HasFactory; + use HasFactory, SoftDeletes; public const SCOPE_LIGHT_VEHICLE = 'light_vehicle'; public const SCOPE_UNIT_SUPPORT_MOBILE = 'unit_support_mobile'; diff --git a/app/Models/SystemSetting.php b/app/Models/SystemSetting.php new file mode 100644 index 0000000..680a999 --- /dev/null +++ b/app/Models/SystemSetting.php @@ -0,0 +1,33 @@ +first(); + return $setting ? $setting->value : $default; + } + + /** + * Set or update a setting by key. + */ + public static function set(string $key, $value): self + { + return static::updateOrCreate( + ['key' => $key], + ['value' => (string) $value] + ); + } +} diff --git a/app/Models/UnitSupportTimesheet.php b/app/Models/UnitSupportTimesheet.php index f537fb1..d811f06 100644 --- a/app/Models/UnitSupportTimesheet.php +++ b/app/Models/UnitSupportTimesheet.php @@ -6,10 +6,11 @@ use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\SoftDeletes; class UnitSupportTimesheet extends Model { - use HasFactory; + use HasFactory, SoftDeletes; protected $fillable = [ 'timesheet_no', diff --git a/app/Models/UnitTransfer.php b/app/Models/UnitTransfer.php index be02d81..c6de6b7 100644 --- a/app/Models/UnitTransfer.php +++ b/app/Models/UnitTransfer.php @@ -6,11 +6,12 @@ use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Storage; class UnitTransfer extends Model { - use HasFactory; + use HasFactory, SoftDeletes; protected $fillable = [ 'transfer_no', diff --git a/app/Models/User.php b/app/Models/User.php index c39d597..e87a920 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -10,12 +10,13 @@ use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; +use Illuminate\Database\Eloquent\SoftDeletes; use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { /** @use HasFactory */ - use HasFactory, Notifiable, HasRoles; + use HasFactory, Notifiable, HasRoles, SoftDeletes; /** * The "booted" method of the model. diff --git a/app/Models/Vehicle.php b/app/Models/Vehicle.php index fe426ff..255bb2f 100644 --- a/app/Models/Vehicle.php +++ b/app/Models/Vehicle.php @@ -8,10 +8,11 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; +use Illuminate\Database\Eloquent\SoftDeletes; class Vehicle extends Model { - use HasFactory; + use HasFactory, SoftDeletes; protected $fillable = [ 'code', diff --git a/app/Models/VehicleActivity.php b/app/Models/VehicleActivity.php index bf4ce0f..60d9678 100644 --- a/app/Models/VehicleActivity.php +++ b/app/Models/VehicleActivity.php @@ -8,10 +8,11 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\SoftDeletes; class VehicleActivity extends Model { - use HasFactory; + use HasFactory, SoftDeletes; public const PENDING_TIMEOUT_HOURS = 5; diff --git a/app/Services/TrashService.php b/app/Services/TrashService.php new file mode 100644 index 0000000..62b6b78 --- /dev/null +++ b/app/Services/TrashService.php @@ -0,0 +1,489 @@ + [ + 'label' => 'Perjalanan Gate', + 'model' => VehicleActivity::class, + 'title_column' => 'transaction_no', + 'with' => ['vehicle', 'driver', 'gate'], + 'subtitle_callback' => function ($item) { + $veh = $item->vehicle()->withTrashed()->first(); + $driver = $item->driver()->withTrashed()->first(); + $vehCode = $veh ? $veh->code : 'Unit #' . $item->vehicle_id; + $driverName = $driver ? $driver->name : 'Driver #' . $item->driver_id; + return "{$vehCode} • {$driverName}"; + }, + 'search_columns' => ['transaction_no', 'purpose'], + ], + 'employees' => [ + 'label' => 'Data Karyawan', + 'model' => Employee::class, + 'title_column' => 'name', + 'with' => [], + 'subtitle_callback' => function ($item) { + $nik = $item->nik ?? '-'; + $pos = $item->position ?? ($item->is_operator ? 'Operator' : 'Karyawan'); + $div = $item->division ? " • {$item->division}" : ''; + return "NIK: {$nik} • {$pos}{$div}"; + }, + 'search_columns' => ['name', 'nik', 'position', 'division', 'unit_kerja'], + ], + 'vehicles' => [ + 'label' => 'Unit Kendaraan & Alat Berat', + 'model' => Vehicle::class, + 'title_column' => 'code', + 'with' => [], + 'subtitle_callback' => function ($item) { + $plate = $item->license_plate ?? $item->model_number ?? '-'; + $cat = $item->unit_category ?? $item->category ?? 'Unit'; + return "No. Plat/Model: {$plate} • Kategori: {$cat}"; + }, + 'search_columns' => ['code', 'license_plate', 'brand_type', 'brand', 'model_number', 'unit_type'], + ], + 'transfers' => [ + 'label' => 'Mobilisasi / Mutasi Unit', + 'model' => UnitTransfer::class, + 'title_column' => 'transfer_no', + 'with' => ['vehicle'], + 'subtitle_callback' => function ($item) { + $veh = $item->vehicle()->withTrashed()->first(); + $vehCode = $veh ? $veh->code : 'Unit #' . $item->vehicle_id; + $route = ($item->from_location ?? '?') . ' ➔ ' . ($item->to_location ?? '?'); + return "{$vehCode} • {$route}"; + }, + 'search_columns' => ['transfer_no', 'from_location', 'to_location', 'description'], + ], + 'timesheets' => [ + 'label' => 'Timesheet Alat Berat', + 'model' => UnitSupportTimesheet::class, + 'title_column' => 'timesheet_no', + 'with' => ['vehicle', 'operator'], + 'subtitle_callback' => function ($item) { + $veh = $item->vehicle()->withTrashed()->first(); + $op = $item->operator()->withTrashed()->first(); + $vehCode = $veh ? $veh->code : 'Unit #' . $item->vehicle_id; + $opName = $op ? $op->name : 'Operator #' . $item->operator_id; + return "{$vehCode} • {$opName} • Shift: " . ($item->shift ?? '-'); + }, + 'search_columns' => ['timesheet_no', 'location', 'task_description'], + ], + 'p2h_records' => [ + 'label' => 'Pemeriksaan P2H', + 'model' => P2hRecord::class, + 'title_column' => 'transaction_no', + 'with' => ['vehicle', 'employee'], + 'subtitle_callback' => function ($item) { + $veh = $item->vehicle()->withTrashed()->first(); + $emp = $item->employee()->withTrashed()->first(); + $vehCode = $veh ? $veh->code : 'Unit #' . $item->vehicle_id; + $empName = $emp ? $emp->name : 'Pemeriksa #' . $item->employee_id; + $cond = $item->summary_condition ? ucfirst($item->summary_condition) : 'Kondisi -'; + return "{$vehCode} • {$empName} • {$cond}"; + }, + 'search_columns' => ['transaction_no', 'general_notes'], + ], + 'users' => [ + 'label' => 'User Akun', + 'model' => User::class, + 'title_column' => 'name', + 'with' => [], + 'subtitle_callback' => function ($item) { + $email = $item->email ?? '-'; + $role = $item->role ?? 'User'; + return "{$email} • Role: {$role}"; + }, + 'search_columns' => ['name', 'email', 'role'], + ], + 'simpers' => [ + 'label' => 'SIMPER Karyawan', + 'model' => EmployeeSimper::class, + 'title_column' => 'simper_number', + 'with' => ['employee', 'simperType'], + 'subtitle_callback' => function ($item) { + $emp = $item->employee()->withTrashed()->first(); + $type = $item->simperType()->withTrashed()->first(); + $empName = $emp ? $emp->name : 'Karyawan #' . $item->employee_id; + $typeName = $type ? $type->name : 'Tipe #' . $item->simper_type_id; + return "{$empName} • Tipe: {$typeName}"; + }, + 'search_columns' => ['simper_number', 'notes'], + ], + 'simper_types' => [ + 'label' => 'Kategori SIMPER', + 'model' => SimperType::class, + 'title_column' => 'name', + 'with' => [], + 'subtitle_callback' => function ($item) { + $code = $item->code ?? '-'; + $scope = $item->scope ?? '-'; + return "Kode: {$code} • Scope: {$scope}"; + }, + 'search_columns' => ['name', 'code', 'scope', 'description'], + ], + 'p2h_templates' => [ + 'label' => 'Template P2H', + 'model' => P2hTemplate::class, + 'title_column' => 'name', + 'with' => [], + 'subtitle_callback' => function ($item) { + $code = $item->code ?? '-'; + return "Kode Template: {$code}"; + }, + 'search_columns' => ['name', 'code', 'description'], + ], + 'gates' => [ + 'label' => 'Pos / Gate', + 'model' => Gate::class, + 'title_column' => 'name', + 'with' => [], + 'subtitle_callback' => function ($item) { + $code = $item->code ?? '-'; + return "Kode Pos: {$code}"; + }, + 'search_columns' => ['name', 'code'], + ], + 'security_guards' => [ + 'label' => 'Petugas Keamanan', + 'model' => SecurityGuard::class, + 'title_column' => 'name', + 'with' => ['gate'], + 'subtitle_callback' => function ($item) { + $badge = $item->badge_id ?? '-'; + $team = $item->team ? "Regu {$item->team}" : '-'; + return "Badge: {$badge} • {$team}"; + }, + 'search_columns' => ['name', 'badge_id'], + ], + ]; + } + + /** + * Get count of trashed items for each category and the total count. + */ + public function getCategoryCounts(): array + { + $categories = self::getCategoryDefinitions(); + $counts = []; + $total = 0; + + foreach ($categories as $key => $config) { + $model = $config['model']; + $count = $model::onlyTrashed()->count(); + $counts[$key] = $count; + $total += $count; + } + + $counts['all'] = $total; + return $counts; + } + + /** + * Get retention period in days. + */ + public function getRetentionDays(): int + { + $val = SystemSetting::get('trash_retention_days', self::DEFAULT_RETENTION_DAYS); + return (int) $val; + } + + /** + * Update retention period in days. + */ + public function setRetentionDays(int $days): void + { + SystemSetting::set('trash_retention_days', $days); + } + + /** + * Get trashed items with optional filtering and pagination. + */ + public function getTrashedItems(?string $category = null, ?string $search = null, int $perPage = 15, int $page = 1): LengthAwarePaginator + { + $retentionDays = $this->getRetentionDays(); + $categories = self::getCategoryDefinitions(); + + if ($category && isset($categories[$category])) { + // Single category query + $config = $categories[$category]; + $model = $config['model']; + $query = $model::onlyTrashed()->with($config['with'] ?? []); + + if ($search) { + $query->where(function ($q) use ($config, $search) { + foreach ($config['search_columns'] as $col) { + $q->orWhere($col, 'like', "%{$search}%"); + } + }); + } + + $total = $query->count(); + $rawItems = $query->latest('deleted_at') + ->forPage($page, $perPage) + ->get(); + + $mapped = $rawItems->map(function ($item) use ($category, $config, $retentionDays) { + return $this->formatTrashedItem($item, $category, $config, $retentionDays); + }); + + return new LengthAwarePaginator( + $mapped, + $total, + $perPage, + $page, + ['path' => request()->url(), 'query' => request()->query()] + ); + } + + // All categories: aggregate items + $collected = collect(); + foreach ($categories as $catKey => $config) { + $model = $config['model']; + $query = $model::onlyTrashed(); + + if ($search) { + $query->where(function ($q) use ($config, $search) { + foreach ($config['search_columns'] as $col) { + $q->orWhere($col, 'like', "%{$search}%"); + } + }); + } + + // Limit to most recent 200 per category to prevent memory exhaustion + $items = $query->latest('deleted_at')->limit(200)->get(); + foreach ($items as $item) { + $collected->push($this->formatTrashedItem($item, $catKey, $config, $retentionDays)); + } + } + + // Sort unified collection by deleted_at descending + $sorted = $collected->sortByDesc('deleted_at_timestamp')->values(); + $total = $sorted->count(); + $sliced = $sorted->slice(($page - 1) * $perPage, $perPage)->values(); + + return new LengthAwarePaginator( + $sliced, + $total, + $perPage, + $page, + ['path' => request()->url(), 'query' => request()->query()] + ); + } + + /** + * Format a model into a standard trashed display object. + */ + protected function formatTrashedItem($item, string $category, array $config, int $retentionDays): object + { + $deletedAt = $item->deleted_at ? Carbon::parse($item->deleted_at) : Carbon::now(); + $daysInTrash = (int) $deletedAt->diffInDays(Carbon::now()); + + $daysRemaining = null; + if ($retentionDays > 0) { + $daysRemaining = max(0, $retentionDays - $daysInTrash); + } + + $titleCol = $config['title_column']; + $title = $item->{$titleCol} ?? ("ID #" . $item->id); + + $subtitle = ''; + if (isset($config['subtitle_callback']) && is_callable($config['subtitle_callback'])) { + try { + $subtitle = call_user_func($config['subtitle_callback'], $item); + } catch (\Throwable $e) { + $subtitle = 'ID: ' . $item->id; + } + } + + return (object) [ + 'id' => $item->id, + 'category' => $category, + 'category_label' => $config['label'], + 'title' => $title, + 'subtitle' => $subtitle, + 'deleted_at' => $deletedAt, + 'deleted_at_timestamp' => $deletedAt->timestamp, + 'deleted_at_human' => $deletedAt->translatedFormat('d M Y, H:i'), + 'days_in_trash' => $daysInTrash, + 'days_remaining' => $daysRemaining, + 'raw_item' => $item, + ]; + } + + /** + * Restore a trashed item. + */ + public function restoreItem(string $category, int $id): bool + { + $categories = self::getCategoryDefinitions(); + if (!isset($categories[$category])) { + return false; + } + + $model = $categories[$category]['model']; + $item = $model::onlyTrashed()->find($id); + + if (!$item) { + return false; + } + + DB::transaction(function () use ($item) { + $item->restore(); + + // Cascade restore children if applicable + if ($item instanceof P2hRecord) { + P2hRecordItem::onlyTrashed() + ->where('p2h_record_id', $item->id) + ->restore(); + } + + if ($item instanceof P2hTemplate) { + P2hTemplateItem::onlyTrashed() + ->where('template_id', $item->id) + ->restore(); + } + + if ($item instanceof Employee) { + EmployeeSimper::onlyTrashed() + ->where('employee_id', $item->id) + ->restore(); + } + }); + + return true; + } + + /** + * Force delete an item permanently. + */ + public function forceDeleteItem(string $category, int $id): bool + { + $categories = self::getCategoryDefinitions(); + if (!isset($categories[$category])) { + return false; + } + + $model = $categories[$category]['model']; + $item = $model::onlyTrashed()->find($id); + + if (!$item) { + return false; + } + + DB::transaction(function () use ($item) { + // Cascade force delete children + if ($item instanceof P2hRecord) { + P2hRecordItem::withTrashed() + ->where('p2h_record_id', $item->id) + ->forceDelete(); + } + + if ($item instanceof P2hTemplate) { + P2hTemplateItem::withTrashed() + ->where('template_id', $item->id) + ->forceDelete(); + } + + if ($item instanceof Employee) { + EmployeeSimper::withTrashed() + ->where('employee_id', $item->id) + ->forceDelete(); + } + + $item->forceDelete(); + }); + + return true; + } + + /** + * Empty trash completely or for a specific category. + */ + public function emptyTrash(?string $category = null): int + { + $categories = self::getCategoryDefinitions(); + $totalDeleted = 0; + + if ($category && isset($categories[$category])) { + $model = $categories[$category]['model']; + $items = $model::onlyTrashed()->get(); + foreach ($items as $item) { + $this->forceDeleteItem($category, $item->id); + $totalDeleted++; + } + return $totalDeleted; + } + + // Empty all + foreach ($categories as $catKey => $config) { + $model = $config['model']; + $items = $model::onlyTrashed()->get(); + foreach ($items as $item) { + $this->forceDeleteItem($catKey, $item->id); + $totalDeleted++; + } + } + + return $totalDeleted; + } + + /** + * Prune trash older than retention threshold. + */ + public function pruneOldTrash(?int $days = null): int + { + if ($days === null) { + $days = $this->getRetentionDays(); + } + + // If retention is 0 or less, auto-pruning is disabled (manual only) + if ($days <= 0) { + return 0; + } + + $cutoff = Carbon::now()->subDays($days); + $categories = self::getCategoryDefinitions(); + $prunedCount = 0; + + foreach ($categories as $catKey => $config) { + $model = $config['model']; + $expiredItems = $model::onlyTrashed()->where('deleted_at', '<=', $cutoff)->get(); + foreach ($expiredItems as $item) { + $this->forceDeleteItem($catKey, $item->id); + $prunedCount++; + } + } + + return $prunedCount; + } +} diff --git a/database/migrations/0001_01_01_000000_create_users_table.php b/database/migrations/0001_01_01_000000_create_users_table.php index 05fb5d9..f6d1726 100644 --- a/database/migrations/0001_01_01_000000_create_users_table.php +++ b/database/migrations/0001_01_01_000000_create_users_table.php @@ -19,6 +19,7 @@ return new class extends Migration $table->string('password'); $table->rememberToken(); $table->timestamps(); + $table->softDeletes(); }); Schema::create('password_reset_tokens', function (Blueprint $table) { diff --git a/database/migrations/2026_10_12_000001_create_gates_table.php b/database/migrations/2026_10_12_000001_create_gates_table.php index 55131f0..10f8bd2 100644 --- a/database/migrations/2026_10_12_000001_create_gates_table.php +++ b/database/migrations/2026_10_12_000001_create_gates_table.php @@ -17,6 +17,7 @@ return new class extends Migration $table->string('name', 100); $table->boolean('is_active')->default(true); $table->timestamps(); + $table->softDeletes(); }); } diff --git a/database/migrations/2026_10_12_000003_create_employees_table.php b/database/migrations/2026_10_12_000003_create_employees_table.php index 2989a09..ae6056b 100644 --- a/database/migrations/2026_10_12_000003_create_employees_table.php +++ b/database/migrations/2026_10_12_000003_create_employees_table.php @@ -22,6 +22,7 @@ return new class extends Migration $table->date('simper_expired_at')->nullable(); $table->string('photo_path')->nullable(); $table->timestamps(); + $table->softDeletes(); }); } diff --git a/database/migrations/2026_10_12_000004_create_vehicles_table.php b/database/migrations/2026_10_12_000004_create_vehicles_table.php index 7578cb7..87d8731 100644 --- a/database/migrations/2026_10_12_000004_create_vehicles_table.php +++ b/database/migrations/2026_10_12_000004_create_vehicles_table.php @@ -37,6 +37,7 @@ return new class extends Migration $table->string('kir_document', 150)->nullable(); $table->timestamps(); + $table->softDeletes(); }); } diff --git a/database/migrations/2026_10_12_000005_create_security_guards_table.php b/database/migrations/2026_10_12_000005_create_security_guards_table.php index 3eecc0b..44ffe85 100644 --- a/database/migrations/2026_10_12_000005_create_security_guards_table.php +++ b/database/migrations/2026_10_12_000005_create_security_guards_table.php @@ -16,6 +16,7 @@ return new class extends Migration $table->string('name', 100); $table->boolean('is_active')->default(true); $table->timestamps(); + $table->softDeletes(); }); } diff --git a/database/migrations/2026_10_12_000006_create_vehicle_activities_table.php b/database/migrations/2026_10_12_000006_create_vehicle_activities_table.php index 5227438..915be19 100644 --- a/database/migrations/2026_10_12_000006_create_vehicle_activities_table.php +++ b/database/migrations/2026_10_12_000006_create_vehicle_activities_table.php @@ -28,6 +28,7 @@ return new class extends Migration $table->text('rejection_note')->nullable(); $table->timestamp('validated_at')->nullable(); $table->timestamps(); + $table->softDeletes(); // Indexes untuk percepatan performa filter log & antrean gerbang $table->index(['gate_id', 'validation_status']); diff --git a/database/migrations/2026_10_15_000001_create_p2h_tables.php b/database/migrations/2026_10_15_000001_create_p2h_tables.php index 0f1451e..078f012 100644 --- a/database/migrations/2026_10_15_000001_create_p2h_tables.php +++ b/database/migrations/2026_10_15_000001_create_p2h_tables.php @@ -20,6 +20,7 @@ return new class extends Migration $table->text('description')->nullable(); $table->boolean('is_active')->default(true); $table->timestamps(); + $table->softDeletes(); }); // 2. Tabel Butir Pertanyaan / Item Cek per Template @@ -31,6 +32,7 @@ return new class extends Migration $table->string('question_type', 50); // choice, datetime, number, text $table->integer('sequence')->default(0); $table->timestamps(); + $table->softDeletes(); $table->index(['template_id', 'sequence']); }); @@ -61,6 +63,7 @@ return new class extends Migration $table->text('validation_notes')->nullable(); $table->dateTime('inspected_at'); $table->timestamps(); + $table->softDeletes(); $table->index(['vehicle_id', 'inspected_at']); $table->index(['employee_id', 'inspected_at']); @@ -79,6 +82,7 @@ return new class extends Migration $table->text('answer_value')->nullable(); $table->text('notes')->nullable(); $table->timestamps(); + $table->softDeletes(); $table->index(['p2h_record_id', 'condition_status']); }); diff --git a/database/migrations/2026_10_19_213000_ensure_employees_for_existing_users.php b/database/migrations/2026_10_19_213000_ensure_employees_for_existing_users.php index 1d3c158..3c1d5ad 100644 --- a/database/migrations/2026_10_19_213000_ensure_employees_for_existing_users.php +++ b/database/migrations/2026_10_19_213000_ensure_employees_for_existing_users.php @@ -12,7 +12,7 @@ return new class extends Migration public function up(): void { // Pastikan seluruh user dengan role employee memiliki profil data master Employee - $users = User::where('role', 'employee') + $users = User::withoutGlobalScopes()->where('role', 'employee') ->orWhereHas('roles', fn ($q) => $q->where('name', 'employee')) ->get(); diff --git a/database/migrations/2026_10_20_000003_create_unit_support_timesheets_table.php b/database/migrations/2026_10_20_000003_create_unit_support_timesheets_table.php index 3c1f67b..1f89a72 100644 --- a/database/migrations/2026_10_20_000003_create_unit_support_timesheets_table.php +++ b/database/migrations/2026_10_20_000003_create_unit_support_timesheets_table.php @@ -34,6 +34,7 @@ return new class extends Migration $table->text('notes')->nullable(); $table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete(); $table->timestamps(); + $table->softDeletes(); // Index performa query & pelaporan $table->index(['date', 'shift']); diff --git a/database/migrations/2026_10_21_000001_create_unit_transfers_table.php b/database/migrations/2026_10_21_000001_create_unit_transfers_table.php index ec77eb8..3735247 100644 --- a/database/migrations/2026_10_21_000001_create_unit_transfers_table.php +++ b/database/migrations/2026_10_21_000001_create_unit_transfers_table.php @@ -38,6 +38,7 @@ return new class extends Migration $table->string('status', 30)->default('completed'); $table->timestamps(); + $table->softDeletes(); // Index $table->index(['vehicle_id', 'transfer_date']); diff --git a/database/migrations/2026_10_25_214800_create_simper_types_and_employee_simpers_tables.php b/database/migrations/2026_10_25_214800_create_simper_types_and_employee_simpers_tables.php index 5c32c23..74d9984 100644 --- a/database/migrations/2026_10_25_214800_create_simper_types_and_employee_simpers_tables.php +++ b/database/migrations/2026_10_25_214800_create_simper_types_and_employee_simpers_tables.php @@ -21,6 +21,7 @@ return new class extends Migration $table->text('description')->nullable(); $table->boolean('is_active')->default(true)->index(); $table->timestamps(); + $table->softDeletes(); }); // 2. Tabel Relasi Multi-SIMPER Personil (Karyawan & Sukon) @@ -33,6 +34,7 @@ return new class extends Migration $table->string('status', 20)->default('active')->index(); $table->text('notes')->nullable(); $table->timestamps(); + $table->softDeletes(); $table->unique(['employee_id', 'simper_type_id']); }); diff --git a/database/migrations/2026_10_28_093000_add_soft_deletes_and_system_settings_table.php b/database/migrations/2026_10_28_093000_add_soft_deletes_and_system_settings_table.php new file mode 100644 index 0000000..1d06abb --- /dev/null +++ b/database/migrations/2026_10_28_093000_add_soft_deletes_and_system_settings_table.php @@ -0,0 +1,92 @@ +id(); + $table->string('key')->unique(); + $table->text('value')->nullable(); + $table->timestamps(); + }); + + // Nilai bawaan retensi otomatis tong sampah: 30 hari + DB::table('system_settings')->insertOrIgnore([ + 'key' => 'trash_retention_days', + 'value' => '30', + 'created_at' => now(), + 'updated_at' => now(), + ]); + } + + // 2. Tambahkan kolom deleted_at (SoftDeletes) ke seluruh tabel operasional dan master + $tables = [ + 'users', + 'employees', + 'employee_simpers', + 'simper_types', + 'vehicles', + 'vehicle_activities', + 'unit_transfers', + 'unit_support_timesheets', + 'p2h_templates', + 'p2h_template_items', + 'p2h_records', + 'p2h_record_items', + 'gates', + 'security_guards', + ]; + + foreach ($tables as $tableName) { + if (Schema::hasTable($tableName) && !Schema::hasColumn($tableName, 'deleted_at')) { + Schema::table($tableName, function (Blueprint $table) { + $table->softDeletes(); + }); + } + } + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + $tables = [ + 'users', + 'employees', + 'employee_simpers', + 'simper_types', + 'vehicles', + 'vehicle_activities', + 'unit_transfers', + 'unit_support_timesheets', + 'p2h_templates', + 'p2h_template_items', + 'p2h_records', + 'p2h_record_items', + 'gates', + 'security_guards', + ]; + + foreach ($tables as $tableName) { + if (Schema::hasTable($tableName) && Schema::hasColumn($tableName, 'deleted_at')) { + Schema::table($tableName, function (Blueprint $table) { + $table->dropSoftDeletes(); + }); + } + } + + Schema::dropIfExists('system_settings'); + } +}; diff --git a/resources/views/admin/trash/index.blade.php b/resources/views/admin/trash/index.blade.php new file mode 100644 index 0000000..6fff152 --- /dev/null +++ b/resources/views/admin/trash/index.blade.php @@ -0,0 +1,402 @@ +@extends('layouts.app') + +@section('title', 'Tong Sampah Sistem (Recycle Bin) - Super Admin RKM') + +@section('content') +
+ +
+
+

+ Tong Sampah Sistem (Recycle Bin) +

+

+ Pusat pemulihan dan retensi data terhapus untuk seluruh modul operasional sistem RKM-KMH. +

+
+
+ + +
+
+ + + @if(session('success')) +
+ {{ session('success') }} + +
+ @endif + + @if(session('error')) +
+ {{ session('error') }} + +
+ @endif + + @if($errors->any()) +
+
    + @foreach($errors->all() as $err) +
  • {{ $err }}
  • + @endforeach +
+
+ @endif + + +
+
+ Total Data di Sampah +
+ {{ number_format($categoryCounts['all']) }} + record +
+ Tersimpan dengan Soft Delete +
+ +
+ Retensi Otomatis Aktif +
+ + {{ $retentionDays > 0 ? $retentionDays . ' Hari' : 'Nonaktif' }} + +
+ + {{ $retentionDays > 0 ? 'Data kadaluarsa dibersihkan berkala' : 'Pembersihan manual oleh Super Admin' }} + +
+ +
+ Kategori Terisi +
+ @php + $nonEmptyCats = 0; + foreach($categories as $cKey => $cConf) { + if (($categoryCounts[$cKey] ?? 0) > 0) $nonEmptyCats++; + } + @endphp + {{ $nonEmptyCats }} + dari {{ count($categories) }} modul +
+ Memiliki data dalam tong sampah +
+
+ + +
+ +
+ + Semua + + {{ $categoryCounts['all'] }} + + + @foreach($categories as $key => $conf) + @php + $isActive = $selectedCategory === $key; + $count = $categoryCounts[$key] ?? 0; + @endphp + + {{ $conf['label'] }} + + {{ $count }} + + + @endforeach +
+ + +
+ @if($selectedCategory) + + @endif +
+ +
+ + @if($search) + + Reset + + @endif +
+
+ + +
+
+ + + + + + + + + + + + + @forelse($items as $index => $item) + + + + + + + + + @empty + + + + @endforelse + +
NoKategori ModulIdentitas / Informasi DataWaktu DihapusRetensiAksi
+ {{ $items->firstItem() + $index }} + + + {{ $item->category_label }} + + +
+ {{ $item->title }} +
+
+ {{ $item->subtitle }} +
+
+
+ {{ $item->deleted_at_human }} +
+
+ {{ $item->days_in_trash == 0 ? 'Hari ini' : $item->days_in_trash . ' hari lalu' }} +
+
+ @if(is_null($item->days_remaining)) + + Manual + + @elseif($item->days_remaining > 7) + + Sisa {{ $item->days_remaining }} hari + + @elseif($item->days_remaining > 0) + + Sisa {{ $item->days_remaining }} hari + + @else + + Kadaluarsa + + @endif + +
+ +
+ @csrf + +
+ + +
+ @csrf + @method('DELETE') + +
+
+
+
+

Tong Sampah Bersih

+

Tidak ada data terhapus pada kategori ini.

+
+
+
+ + @if($items->hasPages()) +
+ {{ $items->links() }} +
+ @endif +
+
+ + + + + + + + +@endsection diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 3c244c4..bc7b1d1 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -254,6 +254,12 @@ Backup & Restore + + + + Tong Sampah + @endif @@ -640,6 +646,10 @@ Backup & Restore + + + Tong Sampah + @endif diff --git a/routes/web.php b/routes/web.php index 070d28a..1b102e9 100644 --- a/routes/web.php +++ b/routes/web.php @@ -4,6 +4,7 @@ use App\Http\Controllers\Admin\AdminActivityLogController; use App\Http\Controllers\Admin\BackupController; use App\Http\Controllers\Admin\DashboardController as AdminDashboardController; use App\Http\Controllers\Admin\RolePermissionController; +use App\Http\Controllers\Admin\TrashController; use App\Http\Controllers\Admin\UserController; use App\Http\Controllers\Auth\LoginController; use App\Http\Controllers\HomeController; @@ -224,5 +225,12 @@ Route::middleware('auth')->group(function () { Route::post('/backups/upload', [BackupController::class, 'upload'])->name('backups.upload'); Route::post('/backups/{filename}/restore', [BackupController::class, 'restore'])->name('backups.restore'); Route::delete('/backups/{filename}', [BackupController::class, 'destroy'])->name('backups.destroy'); + + // Tong Sampah / Recycle Bin & Retensi Otomatis + Route::get('/trash', [TrashController::class, 'index'])->name('trash.index'); + Route::post('/trash/{category}/{id}/restore', [TrashController::class, 'restore'])->name('trash.restore'); + Route::delete('/trash/{category}/{id}/force', [TrashController::class, 'forceDelete'])->name('trash.force_delete'); + Route::post('/trash/empty', [TrashController::class, 'emptyAll'])->name('trash.empty'); + Route::post('/trash/retention', [TrashController::class, 'updateRetention'])->name('trash.retention'); }); }); diff --git a/tests/Feature/ActivityExpirationAndDeletionTest.php b/tests/Feature/ActivityExpirationAndDeletionTest.php index af3e28f..5d93366 100644 --- a/tests/Feature/ActivityExpirationAndDeletionTest.php +++ b/tests/Feature/ActivityExpirationAndDeletionTest.php @@ -228,7 +228,7 @@ class ActivityExpirationAndDeletionTest extends TestCase $response->assertRedirect(); $response->assertSessionHas('success'); - $this->assertDatabaseMissing('vehicle_activities', ['id' => $activity->id]); + $this->assertSoftDeleted('vehicle_activities', ['id' => $activity->id]); // Verifikasi audit log tercatat $this->assertDatabaseHas('admin_activity_logs', [ @@ -289,7 +289,7 @@ class ActivityExpirationAndDeletionTest extends TestCase $response->assertRedirect(); $response->assertSessionHas('success'); - $this->assertDatabaseMissing('vehicle_activities', ['id' => $activity->id]); + $this->assertSoftDeleted('vehicle_activities', ['id' => $activity->id]); // Verifikasi audit log tercatat $this->assertDatabaseHas('admin_activity_logs', [ diff --git a/tests/Feature/HseEmployeeFlexibleUnitKerjaAndModalTest.php b/tests/Feature/HseEmployeeFlexibleUnitKerjaAndModalTest.php index d5c0076..33ef6bf 100644 --- a/tests/Feature/HseEmployeeFlexibleUnitKerjaAndModalTest.php +++ b/tests/Feature/HseEmployeeFlexibleUnitKerjaAndModalTest.php @@ -252,8 +252,8 @@ class HseEmployeeFlexibleUnitKerjaAndModalTest extends TestCase $response->assertSessionHas('success'); $response->assertRedirect(route('hse.employees.index')); - $this->assertDatabaseMissing('employees', ['id' => $employee->id]); - $this->assertDatabaseMissing('users', ['id' => $linkedUser->id]); + $this->assertSoftDeleted('employees', ['id' => $employee->id]); + $this->assertSoftDeleted('users', ['id' => $linkedUser->id]); } public function test_cannot_delete_employee_with_operational_records(): void diff --git a/tests/Feature/P2hInspectionTest.php b/tests/Feature/P2hInspectionTest.php index 93b7886..1bb0f8b 100644 --- a/tests/Feature/P2hInspectionTest.php +++ b/tests/Feature/P2hInspectionTest.php @@ -380,7 +380,7 @@ class P2hInspectionTest extends TestCase // 6. Hapus kategori aset juga menghapus master template yang belum ada transaksi $deleteResponse = $this->actingAs($this->qmaAdmin)->delete('/qma/vehicles/' . $category->id); $deleteResponse->assertSessionHas('success'); - $this->assertDatabaseMissing('p2h_templates', ['id' => $template->id]); + $this->assertSoftDeleted('p2h_templates', ['id' => $template->id]); } public function test_qma_admin_can_edit_p2h_template_question(): void diff --git a/tests/Feature/PhotoUploadAndCompressionTest.php b/tests/Feature/PhotoUploadAndCompressionTest.php index 4d6e132..882ca3d 100644 --- a/tests/Feature/PhotoUploadAndCompressionTest.php +++ b/tests/Feature/PhotoUploadAndCompressionTest.php @@ -138,7 +138,7 @@ class PhotoUploadAndCompressionTest extends TestCase $deleteResponse = $this->actingAs($this->adminQma)->delete(route('qma.vehicles.destroy', $vehicle->id)); $deleteResponse->assertRedirect(); - $this->assertDatabaseMissing('vehicles', ['id' => $vehicle->id]); + $this->assertSoftDeleted('vehicles', ['id' => $vehicle->id]); Storage::disk('public')->assertMissing($photoPath); } diff --git a/tests/Feature/QmaModuleTest.php b/tests/Feature/QmaModuleTest.php index ecd3e33..65a8ed0 100644 --- a/tests/Feature/QmaModuleTest.php +++ b/tests/Feature/QmaModuleTest.php @@ -223,7 +223,7 @@ class QmaModuleTest extends TestCase $response = $this->actingAs($this->qmaAdmin)->delete("/qma/vehicles/{$vehicle->id}"); $response->assertSessionHas('success'); - $this->assertDatabaseMissing('vehicles', ['id' => $vehicle->id]); + $this->assertSoftDeleted('vehicles', ['id' => $vehicle->id]); } /** diff --git a/tests/Feature/QmaSupportTimesheetTest.php b/tests/Feature/QmaSupportTimesheetTest.php index 1dfb011..47c0f36 100644 --- a/tests/Feature/QmaSupportTimesheetTest.php +++ b/tests/Feature/QmaSupportTimesheetTest.php @@ -329,7 +329,7 @@ class QmaSupportTimesheetTest extends TestCase ->delete(route('qma.support_timesheet.destroy', $timesheet->id)); $response->assertRedirect(); - $this->assertDatabaseMissing('unit_support_timesheets', ['id' => $timesheet->id]); + $this->assertSoftDeleted('unit_support_timesheets', ['id' => $timesheet->id]); } /** diff --git a/tests/Feature/QmaUnitTransferTest.php b/tests/Feature/QmaUnitTransferTest.php index 95d9e23..6c291a0 100644 --- a/tests/Feature/QmaUnitTransferTest.php +++ b/tests/Feature/QmaUnitTransferTest.php @@ -326,7 +326,7 @@ class QmaUnitTransferTest extends TestCase $response = $this->actingAs($this->qmaAdmin)->delete(route('qma.unit_transfers.destroy', $transfer->id)); $response->assertRedirect(route('qma.unit_transfers.index')); - $this->assertDatabaseMissing('unit_transfers', ['id' => $transfer->id]); + $this->assertSoftDeleted('unit_transfers', ['id' => $transfer->id]); } /** diff --git a/tests/Feature/SecurityGuardFilterTest.php b/tests/Feature/SecurityGuardFilterTest.php index c19246f..ceb425a 100644 --- a/tests/Feature/SecurityGuardFilterTest.php +++ b/tests/Feature/SecurityGuardFilterTest.php @@ -170,9 +170,9 @@ class SecurityGuardFilterTest extends TestCase $response->assertRedirect(); $response->assertSessionHas('success'); - $this->assertDatabaseMissing('security_guards', ['id' => $guardId]); + $this->assertSoftDeleted('security_guards', ['id' => $guardId]); if ($userId) { - $this->assertDatabaseMissing('users', ['id' => $userId]); + $this->assertSoftDeleted('users', ['id' => $userId]); } } } diff --git a/tests/Feature/TrashAndAutoDeleteTest.php b/tests/Feature/TrashAndAutoDeleteTest.php new file mode 100644 index 0000000..5f944b2 --- /dev/null +++ b/tests/Feature/TrashAndAutoDeleteTest.php @@ -0,0 +1,313 @@ + 'super_admin']); + Role::firstOrCreate(['name' => 'employee']); + + $this->superAdmin = User::factory()->create([ + 'username' => 'superadmin_test', + 'role' => 'super_admin', + ]); + $this->superAdmin->assignRole('super_admin'); + + $this->regularUser = User::factory()->create([ + 'username' => 'employee_test', + 'role' => 'employee', + ]); + $this->regularUser->assignRole('employee'); + + $this->gate = Gate::create([ + 'code' => 'GATE-TRASH-01', + 'name' => 'Gate Utama Trash', + 'is_active' => true, + ]); + + $this->vehicle = Vehicle::create([ + 'code' => 'LV-TRASH-01', + 'category' => 'light_vehicle', + 'brand_type' => 'Toyota Hilux 4x4', + 'license_plate' => 'B 1111 TRH', + 'status' => 'Operation', + 'current_km' => 1000, + ]); + + $this->driver = Employee::create([ + 'nik' => 'DRV-TRASH-01', + 'name' => 'Driver Trash Test', + 'unit_kerja' => 'Umum', + 'division' => 'Operasional', + 'position' => 'Driver', + 'is_operator' => false, + ]); + } + + /** + * 1. Super admin dapat mengakses halaman tong sampah, non-super admin diblokir. + */ + public function test_super_admin_can_access_trash_page_and_others_forbidden(): void + { + $responseSuper = $this->actingAs($this->superAdmin)->get(route('admin.trash.index')); + $responseSuper->assertOk(); + $responseSuper->assertSee('Tong Sampah Sistem (Recycle Bin)'); + + $responseRegular = $this->actingAs($this->regularUser)->get(route('admin.trash.index')); + $responseRegular->assertForbidden(); + } + + /** + * 2. Data yang dihapus masuk ke tong sampah (Soft Delete) dan tampil di UI. + */ + public function test_deleted_records_are_soft_deleted_and_appear_in_trash_ui(): void + { + $activity = VehicleActivity::create([ + 'transaction_no' => 'TRX-TRASH-001', + 'vehicle_id' => $this->vehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'out', + 'previous_km' => 1000, + 'current_km' => 1050, + 'distance' => 50, + 'purpose' => 'Pengantaran Sampel Uji', + 'recorded_at' => Carbon::now(), + 'validation_status' => 'approved', + ]); + + // Hapus activity + $activity->delete(); + + // Pastikan soft deleted + $this->assertSoftDeleted('vehicle_activities', ['id' => $activity->id]); + + // Cek halaman index tong sampah + $response = $this->actingAs($this->superAdmin)->get(route('admin.trash.index')); + $response->assertOk(); + $response->assertSee('TRX-TRASH-001'); + $response->assertSee('LV-TRASH-01'); + + // Cek filter kategori + $responseCat = $this->actingAs($this->superAdmin)->get(route('admin.trash.index', ['category' => 'activities'])); + $responseCat->assertOk(); + $responseCat->assertSee('TRX-TRASH-001'); + } + + /** + * 3. Super admin dapat memulihkan (restore) data dari tong sampah. + */ + public function test_super_admin_can_restore_trashed_item(): void + { + $activity = VehicleActivity::create([ + 'transaction_no' => 'TRX-RESTORE-001', + 'vehicle_id' => $this->vehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'in', + 'previous_km' => 1050, + 'current_km' => 1100, + 'distance' => 50, + 'purpose' => 'Kepulangan Unit', + 'recorded_at' => Carbon::now(), + 'validation_status' => 'approved', + ]); + + $activity->delete(); + $this->assertSoftDeleted('vehicle_activities', ['id' => $activity->id]); + + // Request restore + $response = $this->actingAs($this->superAdmin)->post(route('admin.trash.restore', [ + 'category' => 'activities', + 'id' => $activity->id, + ])); + + $response->assertRedirect(); + $response->assertSessionHas('success'); + + // Data tidak lagi soft-deleted (aktif kembali) + $this->assertDatabaseHas('vehicle_activities', [ + 'id' => $activity->id, + 'deleted_at' => null, + ]); + } + + /** + * 4. Super admin dapat menghapus data secara permanen (force delete). + */ + public function test_super_admin_can_force_delete_trashed_item(): void + { + $activity = VehicleActivity::create([ + 'transaction_no' => 'TRX-FORCE-001', + 'vehicle_id' => $this->vehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'out', + 'previous_km' => 1100, + 'current_km' => 1150, + 'distance' => 50, + 'purpose' => 'Operasional Test', + 'recorded_at' => Carbon::now(), + 'validation_status' => 'approved', + ]); + + $activity->delete(); + $this->assertSoftDeleted('vehicle_activities', ['id' => $activity->id]); + + // Request force delete + $response = $this->actingAs($this->superAdmin)->delete(route('admin.trash.force_delete', [ + 'category' => 'activities', + 'id' => $activity->id, + ])); + + $response->assertRedirect(); + $response->assertSessionHas('success'); + + // Data terhapus permanen dari basis data + $this->assertDatabaseMissing('vehicle_activities', [ + 'id' => $activity->id, + ]); + } + + /** + * 5. Super admin dapat mengosongkan seluruh tong sampah dengan konfirmasi. + */ + public function test_super_admin_can_empty_trash_with_confirmation(): void + { + $activity = VehicleActivity::create([ + 'transaction_no' => 'TRX-EMPTY-001', + 'vehicle_id' => $this->vehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'out', + 'previous_km' => 1150, + 'current_km' => 1200, + 'distance' => 50, + 'purpose' => 'Test Empty', + 'recorded_at' => Carbon::now(), + 'validation_status' => 'approved', + ]); + $activity->delete(); + + // 1. Tanpa konfirmasi yang tepat harus ditolak + $responseFailed = $this->actingAs($this->superAdmin)->post(route('admin.trash.empty'), [ + 'confirm_text' => 'SALAH', + ]); + $responseFailed->assertSessionHasErrors('confirm_text'); + + // 2. Dengan konfirmasi KOSONGKAN + $responseSuccess = $this->actingAs($this->superAdmin)->post(route('admin.trash.empty'), [ + 'confirm_text' => 'KOSONGKAN', + ]); + $responseSuccess->assertRedirect(); + $responseSuccess->assertSessionHas('success'); + + $this->assertDatabaseMissing('vehicle_activities', [ + 'id' => $activity->id, + ]); + } + + /** + * 6. Super admin dapat mengubah durasi retensi otomatis (30, 60, 90, 0 hari). + */ + public function test_super_admin_can_update_retention_days(): void + { + // Set ke 60 hari + $response = $this->actingAs($this->superAdmin)->post(route('admin.trash.retention'), [ + 'retention_days' => 60, + ]); + $response->assertRedirect(); + $response->assertSessionHas('success'); + + $this->assertEquals('60', SystemSetting::get('trash_retention_days')); + + // Coba nilai tidak valid + $responseInvalid = $this->actingAs($this->superAdmin)->post(route('admin.trash.retention'), [ + 'retention_days' => 45, + ]); + $responseInvalid->assertSessionHasErrors('retention_days'); + } + + /** + * 7. Artisan command trash:prune menghapus data yang telah melewati retensi. + */ + public function test_artisan_prune_trash_command_removes_expired_records(): void + { + // Item yang kadaluarsa (dihapus 40 hari yang lalu) + $oldActivity = VehicleActivity::create([ + 'transaction_no' => 'TRX-OLD-PRUNE', + 'vehicle_id' => $this->vehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'out', + 'previous_km' => 1200, + 'current_km' => 1250, + 'distance' => 50, + 'purpose' => 'Aktivitas Kadaluarsa', + 'recorded_at' => Carbon::now()->subDays(40), + 'validation_status' => 'approved', + ]); + $oldActivity->delete(); + // Update deleted_at secara eksplisit ke 40 hari lalu + VehicleActivity::withTrashed()->where('id', $oldActivity->id)->update([ + 'deleted_at' => Carbon::now()->subDays(40), + ]); + + // Item yang masih baru (dihapus 5 hari yang lalu) + $freshActivity = VehicleActivity::create([ + 'transaction_no' => 'TRX-FRESH-PRUNE', + 'vehicle_id' => $this->vehicle->id, + 'driver_id' => $this->driver->id, + 'gate_id' => $this->gate->id, + 'direction' => 'out', + 'previous_km' => 1250, + 'current_km' => 1300, + 'distance' => 50, + 'purpose' => 'Aktivitas Baru', + 'recorded_at' => Carbon::now()->subDays(5), + 'validation_status' => 'approved', + ]); + $freshActivity->delete(); + VehicleActivity::withTrashed()->where('id', $freshActivity->id)->update([ + 'deleted_at' => Carbon::now()->subDays(5), + ]); + + // Jalankan artisan trash:prune dengan retensi 30 hari + $this->artisan('trash:prune', ['--days' => 30]) + ->expectsOutputToContain('Pembersihan selesai') + ->assertExitCode(0); + + // Record yang 40 hari lalu harus terhapus permanen + $this->assertDatabaseMissing('vehicle_activities', [ + 'id' => $oldActivity->id, + ]); + + // Record yang 5 hari lalu harus tetap ada di tong sampah + $this->assertSoftDeleted('vehicle_activities', [ + 'id' => $freshActivity->id, + ]); + } +}