feat(trash): implementasi fitur Tong Sampah (Recycle Bin) soft deletes dan retensi otomatis 30/60/90 hari di Super Admin

This commit is contained in:
Ray1111-aa
2026-10-28 09:47:16 +07:00
parent cb9891b1e3
commit 926683fd34
42 changed files with 1603 additions and 26 deletions
@@ -0,0 +1,45 @@
<?php
namespace App\Console\Commands;
use App\Services\TrashService;
use Illuminate\Console\Command;
class PruneTrashCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'trash:prune {--days= : Override periode retensi hari (default sesuai pengaturan sistem)}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Bersihkan data di tong sampah yang telah melewati periode retensi otomatis.';
/**
* Execute the console command.
*/
public function handle(TrashService $trashService): int
{
$daysOption = $this->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;
}
}
@@ -0,0 +1,157 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\AdminActivityLog;
use App\Services\TrashService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class TrashController extends Controller
{
public function __construct(
protected TrashService $trashService
) {}
/**
* Tampilkan halaman daftar data terhapus (Recycle Bin / Tong Sampah).
*/
public function index(Request $request): View
{
$selectedCategory = $request->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}.");
}
}
+2 -1
View File
@@ -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';
+2 -1
View File
@@ -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';
+2 -1
View File
@@ -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',
+2 -1
View File
@@ -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',
+2 -1
View File
@@ -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',
+2 -1
View File
@@ -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',
+2 -1
View File
@@ -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',
+2 -1
View File
@@ -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',
+2 -1
View File
@@ -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';
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SystemSetting extends Model
{
protected $fillable = [
'key',
'value',
];
/**
* Get a setting value by key with optional default fallback.
*/
public static function get(string $key, $default = null)
{
$setting = static::where('key', $key)->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]
);
}
}
+2 -1
View File
@@ -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',
+2 -1
View File
@@ -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',
+2 -1
View File
@@ -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<UserFactory> */
use HasFactory, Notifiable, HasRoles;
use HasFactory, Notifiable, HasRoles, SoftDeletes;
/**
* The "booted" method of the model.
+2 -1
View File
@@ -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',
+2 -1
View File
@@ -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;
+489
View File
@@ -0,0 +1,489 @@
<?php
namespace App\Services;
use App\Models\Employee;
use App\Models\EmployeeSimper;
use App\Models\Gate;
use App\Models\P2hRecord;
use App\Models\P2hRecordItem;
use App\Models\P2hTemplate;
use App\Models\P2hTemplateItem;
use App\Models\SecurityGuard;
use App\Models\SimperType;
use App\Models\SystemSetting;
use App\Models\UnitSupportTimesheet;
use App\Models\UnitTransfer;
use App\Models\User;
use App\Models\Vehicle;
use App\Models\VehicleActivity;
use Carbon\Carbon;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class TrashService
{
public const DEFAULT_RETENTION_DAYS = 30;
/**
* Category definitions and configurations.
*/
public static function getCategoryDefinitions(): array
{
return [
'activities' => [
'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;
}
}
@@ -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) {
@@ -17,6 +17,7 @@ return new class extends Migration
$table->string('name', 100);
$table->boolean('is_active')->default(true);
$table->timestamps();
$table->softDeletes();
});
}
@@ -22,6 +22,7 @@ return new class extends Migration
$table->date('simper_expired_at')->nullable();
$table->string('photo_path')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
@@ -37,6 +37,7 @@ return new class extends Migration
$table->string('kir_document', 150)->nullable();
$table->timestamps();
$table->softDeletes();
});
}
@@ -16,6 +16,7 @@ return new class extends Migration
$table->string('name', 100);
$table->boolean('is_active')->default(true);
$table->timestamps();
$table->softDeletes();
});
}
@@ -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']);
@@ -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']);
});
@@ -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();
@@ -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']);
@@ -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']);
@@ -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']);
});
@@ -0,0 +1,92 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
// 1. Buat tabel system_settings untuk menyimpan konfigurasi sistem (seperti retensi auto-delete sampah)
if (!Schema::hasTable('system_settings')) {
Schema::create('system_settings', function (Blueprint $table) {
$table->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');
}
};
+402
View File
@@ -0,0 +1,402 @@
@extends('layouts.app')
@section('title', 'Tong Sampah Sistem (Recycle Bin) - Super Admin RKM')
@section('content')
<div class="space-y-6">
<!-- Header Halaman (Clean Minimalist) -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pb-2 border-b border-slate-100">
<div>
<h1 class="text-xl font-bold text-slate-900 tracking-tight">
Tong Sampah Sistem (Recycle Bin)
</h1>
<p class="text-xs text-slate-500 mt-0.5">
Pusat pemulihan dan retensi data terhapus untuk seluruh modul operasional sistem RKM-KMH.
</p>
</div>
<div class="flex items-center gap-2.5">
<button type="button"
onclick="openRetentionModal()"
class="px-3.5 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 text-xs font-semibold transition shadow-2xs">
Atur Retensi ({{ $retentionDays > 0 ? $retentionDays . ' Hari' : 'Manual' }})
</button>
<button type="button"
onclick="openEmptyTrashModal()"
class="px-4 py-2 rounded-xl bg-rose-600 hover:bg-rose-700 text-white text-xs font-semibold transition shadow-xs">
Kosongkan Sampah
</button>
</div>
</div>
<!-- Alert Notifikasi Flash -->
@if(session('success'))
<div class="p-3.5 bg-emerald-50 border border-emerald-200 rounded-xl flex items-center justify-between text-emerald-900 text-xs font-medium">
<span>{{ session('success') }}</span>
<button type="button" onclick="this.parentElement.remove()" class="text-emerald-500 hover:text-emerald-700 ml-3 text-sm">&times;</button>
</div>
@endif
@if(session('error'))
<div class="p-3.5 bg-rose-50 border border-rose-200 rounded-xl flex items-center justify-between text-rose-900 text-xs font-medium">
<span>{{ session('error') }}</span>
<button type="button" onclick="this.parentElement.remove()" class="text-rose-500 hover:text-rose-700 ml-3 text-sm">&times;</button>
</div>
@endif
@if($errors->any())
<div class="p-3.5 bg-rose-50 border border-rose-200 rounded-xl text-rose-900 text-xs font-medium">
<ul class="list-disc list-inside space-y-1">
@foreach($errors->all() as $err)
<li>{{ $err }}</li>
@endforeach
</ul>
</div>
@endif
<!-- Ringkasan Metrik (Clean & Tanpa Ikon Berlebihan) -->
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Total Data di Sampah</span>
<div class="flex items-baseline gap-2 mt-1.5">
<span class="text-2xl font-bold text-slate-900">{{ number_format($categoryCounts['all']) }}</span>
<span class="text-xs text-slate-400 font-medium">record</span>
</div>
<span class="text-[10px] text-slate-400 block mt-2">Tersimpan dengan Soft Delete</span>
</div>
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Retensi Otomatis Aktif</span>
<div class="flex items-baseline gap-2 mt-1.5">
<span class="text-2xl font-bold text-indigo-600">
{{ $retentionDays > 0 ? $retentionDays . ' Hari' : 'Nonaktif' }}
</span>
</div>
<span class="text-[10px] text-slate-400 block mt-2">
{{ $retentionDays > 0 ? 'Data kadaluarsa dibersihkan berkala' : 'Pembersihan manual oleh Super Admin' }}
</span>
</div>
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs">
<span class="text-[11px] font-semibold text-slate-400 uppercase tracking-wider block">Kategori Terisi</span>
<div class="flex items-baseline gap-2 mt-1.5">
@php
$nonEmptyCats = 0;
foreach($categories as $cKey => $cConf) {
if (($categoryCounts[$cKey] ?? 0) > 0) $nonEmptyCats++;
}
@endphp
<span class="text-2xl font-bold text-slate-900">{{ $nonEmptyCats }}</span>
<span class="text-xs text-slate-400 font-medium">dari {{ count($categories) }} modul</span>
</div>
<span class="text-[10px] text-slate-400 block mt-2">Memiliki data dalam tong sampah</span>
</div>
</div>
<!-- Filter Tab & Pencarian -->
<div class="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs space-y-4">
<!-- Tab Pills Kategori (Scrollable Horizontal) -->
<div class="flex items-center gap-1.5 overflow-x-auto pb-1 scrollbar-thin">
<a href="{{ route('admin.trash.index', ['category' => 'all', 'q' => $search]) }}"
class="shrink-0 px-3 py-1.5 rounded-xl text-xs font-semibold transition {{ is_null($selectedCategory) ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200' }}">
Semua
<span class="ml-1 text-[10px] {{ is_null($selectedCategory) ? 'bg-indigo-700 text-indigo-100' : 'bg-slate-200 text-slate-600' }} px-1.5 py-0.5 rounded-full">
{{ $categoryCounts['all'] }}
</span>
</a>
@foreach($categories as $key => $conf)
@php
$isActive = $selectedCategory === $key;
$count = $categoryCounts[$key] ?? 0;
@endphp
<a href="{{ route('admin.trash.index', ['category' => $key, 'q' => $search]) }}"
class="shrink-0 px-3 py-1.5 rounded-xl text-xs font-semibold transition {{ $isActive ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200' }}">
{{ $conf['label'] }}
<span class="ml-1 text-[10px] {{ $isActive ? 'bg-indigo-700 text-indigo-100' : 'bg-slate-200 text-slate-600' }} px-1.5 py-0.5 rounded-full">
{{ $count }}
</span>
</a>
@endforeach
</div>
<!-- Form Pencarian Cepat -->
<form method="GET" action="{{ route('admin.trash.index') }}" class="flex items-center gap-2">
@if($selectedCategory)
<input type="hidden" name="category" value="{{ $selectedCategory }}">
@endif
<div class="relative flex-1">
<input type="text"
name="q"
value="{{ $search }}"
placeholder="Cari data terhapus (nama, kode, NIK, nomor transaksi, dsb)..."
class="w-full text-xs rounded-xl border-slate-200 focus:border-indigo-500 focus:ring focus:ring-indigo-200/50 py-2.5 px-3.5">
</div>
<button type="submit"
class="px-4 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-900 text-white text-xs font-semibold transition">
Cari
</button>
@if($search)
<a href="{{ route('admin.trash.index', ['category' => $selectedCategory ?? 'all']) }}"
class="px-3.5 py-2.5 rounded-xl border border-slate-200 hover:bg-slate-50 text-slate-600 text-xs font-semibold transition">
Reset
</a>
@endif
</form>
</div>
<!-- Tabel Data Terhapus -->
<div class="bg-white rounded-2xl border border-slate-200/80 shadow-2xs overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-left border-collapse text-xs">
<thead>
<tr class="border-b border-slate-200/80 bg-slate-50/75 text-slate-500 font-semibold uppercase tracking-wider text-[10px]">
<th class="py-3.5 px-4 w-12 text-center">No</th>
<th class="py-3.5 px-4 w-44">Kategori Modul</th>
<th class="py-3.5 px-4">Identitas / Informasi Data</th>
<th class="py-3.5 px-4 w-44">Waktu Dihapus</th>
<th class="py-3.5 px-4 w-36">Retensi</th>
<th class="py-3.5 px-4 w-48 text-right">Aksi</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100">
@forelse($items as $index => $item)
<tr class="hover:bg-slate-50/50 transition">
<td class="py-3 px-4 text-center text-slate-400 font-medium">
{{ $items->firstItem() + $index }}
</td>
<td class="py-3 px-4">
<span class="inline-block px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-slate-100 text-slate-700">
{{ $item->category_label }}
</span>
</td>
<td class="py-3 px-4">
<div class="font-bold text-slate-900 text-xs">
{{ $item->title }}
</div>
<div class="text-[11px] text-slate-500 mt-0.5">
{{ $item->subtitle }}
</div>
</td>
<td class="py-3 px-4">
<div class="font-medium text-slate-800">
{{ $item->deleted_at_human }}
</div>
<div class="text-[10px] text-slate-400 mt-0.5">
{{ $item->days_in_trash == 0 ? 'Hari ini' : $item->days_in_trash . ' hari lalu' }}
</div>
</td>
<td class="py-3 px-4">
@if(is_null($item->days_remaining))
<span class="inline-block px-2 py-0.5 rounded-md text-[10px] font-semibold bg-slate-100 text-slate-600">
Manual
</span>
@elseif($item->days_remaining > 7)
<span class="inline-block px-2 py-0.5 rounded-md text-[10px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
Sisa {{ $item->days_remaining }} hari
</span>
@elseif($item->days_remaining > 0)
<span class="inline-block px-2 py-0.5 rounded-md text-[10px] font-semibold bg-amber-50 text-amber-700 border border-amber-200">
Sisa {{ $item->days_remaining }} hari
</span>
@else
<span class="inline-block px-2 py-0.5 rounded-md text-[10px] font-semibold bg-rose-50 text-rose-700 border border-rose-200">
Kadaluarsa
</span>
@endif
</td>
<td class="py-3 px-4 text-right">
<div class="flex items-center justify-end gap-1.5">
<!-- Tombol Pulihkan -->
<form method="POST"
action="{{ route('admin.trash.restore', ['category' => $item->category, 'id' => $item->id]) }}"
onsubmit="return confirm('Pulihkan data ini kembali ke sistem aktif?')">
@csrf
<button type="submit"
class="px-2.5 py-1.5 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 text-xs font-semibold transition shadow-2xs">
Pulihkan
</button>
</form>
<!-- Tombol Hapus Permanen -->
<form method="POST"
action="{{ route('admin.trash.force_delete', ['category' => $item->category, 'id' => $item->id]) }}"
onsubmit="return confirm('PERINGATAN: Data akan dihapus secara permanen dari basis data dan tidak dapat dikembalikan lagi. Lanjutkan?')">
@csrf
@method('DELETE')
<button type="submit"
class="px-2.5 py-1.5 rounded-lg border border-rose-200 bg-rose-50 hover:bg-rose-100 text-rose-700 text-xs font-semibold transition">
Hapus Permanen
</button>
</form>
</div>
</td>
</tr>
@empty
<tr>
<td colspan="6" class="py-12 text-center">
<div class="max-w-xs mx-auto text-center space-y-1">
<p class="text-xs font-bold text-slate-700">Tong Sampah Bersih</p>
<p class="text-[11px] text-slate-400">Tidak ada data terhapus pada kategori ini.</p>
</div>
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
@if($items->hasPages())
<div class="p-4 border-t border-slate-100 bg-slate-50/50">
{{ $items->links() }}
</div>
@endif
</div>
</div>
<!-- Modal Atur Retensi Otomatis -->
<div id="retentionModal" class="fixed inset-0 z-50 hidden bg-slate-900/40 backdrop-blur-xs flex items-center justify-center p-4">
<div class="bg-white rounded-2xl max-w-md w-full border border-slate-200 shadow-xl overflow-hidden p-6 space-y-5 animate-in fade-in duration-150">
<div class="flex items-center justify-between">
<h3 class="text-base font-bold text-slate-900">Pengaturan Retensi Otomatis</h3>
<button type="button" onclick="closeRetentionModal()" class="text-slate-400 hover:text-slate-600 text-lg">&times;</button>
</div>
<p class="text-xs text-slate-500 leading-relaxed">
Pilih berapa lama data terhapus disimpan di tong sampah sebelum dibersihkan permanen secara otomatis oleh sistem.
</p>
<form method="POST" action="{{ route('admin.trash.retention') }}" class="space-y-4">
@csrf
<div class="space-y-2.5">
<label class="flex items-center gap-3 p-3 rounded-xl border border-slate-200 hover:bg-slate-50 cursor-pointer">
<input type="radio" name="retention_days" value="30" class="text-indigo-600 focus:ring-indigo-500" {{ $retentionDays == 30 ? 'checked' : '' }}>
<div>
<div class="text-xs font-bold text-slate-800">30 Hari (Default Rekomendasi)</div>
<div class="text-[10px] text-slate-500">Data otomatis dibersihkan 30 hari setelah dihapus</div>
</div>
</label>
<label class="flex items-center gap-3 p-3 rounded-xl border border-slate-200 hover:bg-slate-50 cursor-pointer">
<input type="radio" name="retention_days" value="60" class="text-indigo-600 focus:ring-indigo-500" {{ $retentionDays == 60 ? 'checked' : '' }}>
<div>
<div class="text-xs font-bold text-slate-800">60 Hari (2 Bulan)</div>
<div class="text-[10px] text-slate-500">Periode retensi menengah untuk evaluasi operasional</div>
</div>
</label>
<label class="flex items-center gap-3 p-3 rounded-xl border border-slate-200 hover:bg-slate-50 cursor-pointer">
<input type="radio" name="retention_days" value="90" class="text-indigo-600 focus:ring-indigo-500" {{ $retentionDays == 90 ? 'checked' : '' }}>
<div>
<div class="text-xs font-bold text-slate-800">90 Hari (3 Bulan / Kuartal)</div>
<div class="text-[10px] text-slate-500">Retensi jangka panjang sebelum pembersihan total</div>
</div>
</label>
<label class="flex items-center gap-3 p-3 rounded-xl border border-slate-200 hover:bg-slate-50 cursor-pointer">
<input type="radio" name="retention_days" value="0" class="text-indigo-600 focus:ring-indigo-500" {{ $retentionDays == 0 ? 'checked' : '' }}>
<div>
<div class="text-xs font-bold text-slate-800">Nonaktif (Pembersihan Manual)</div>
<div class="text-[10px] text-slate-500">Data terhapus disimpan selamanya sampai Super Admin menghapus manual</div>
</div>
</label>
</div>
<div class="flex items-center justify-end gap-2.5 pt-2">
<button type="button"
onclick="closeRetentionModal()"
class="px-4 py-2 rounded-xl border border-slate-200 hover:bg-slate-50 text-slate-700 text-xs font-semibold transition">
Batal
</button>
<button type="submit"
class="px-4 py-2 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold transition shadow-xs">
Simpan Pengaturan
</button>
</div>
</form>
</div>
</div>
<!-- Modal Kosongkan Sampah -->
<div id="emptyTrashModal" class="fixed inset-0 z-50 hidden bg-slate-900/40 backdrop-blur-xs flex items-center justify-center p-4">
<div class="bg-white rounded-2xl max-w-md w-full border border-slate-200 shadow-xl overflow-hidden p-6 space-y-5 animate-in fade-in duration-150">
<div class="flex items-center justify-between">
<h3 class="text-base font-bold text-rose-700">Kosongkan Tong Sampah</h3>
<button type="button" onclick="closeEmptyTrashModal()" class="text-slate-400 hover:text-slate-600 text-lg">&times;</button>
</div>
<div class="p-3 bg-rose-50 border border-rose-200 rounded-xl text-xs text-rose-800 leading-relaxed">
<strong>PERHATIAN:</strong> Tindakan ini akan menghapus data terpilih secara permanen dari server. Data yang telah dihapus permanen <strong>TIDAK DAPAT DIKEMBALIKAN</strong> lagi.
</div>
<form method="POST" action="{{ route('admin.trash.empty') }}" class="space-y-4">
@csrf
<div>
<label class="block text-xs font-semibold text-slate-700 mb-1.5">Pilih Cakupan Pembersihan</label>
<select name="category" class="w-full text-xs rounded-xl border-slate-200 py-2.5 px-3">
<option value="all" {{ is_null($selectedCategory) ? 'selected' : '' }}>Seluruh Tong Sampah (Semua Kategori - {{ $categoryCounts['all'] }} data)</option>
@foreach($categories as $key => $conf)
<option value="{{ $key }}" {{ $selectedCategory === $key ? 'selected' : '' }}>
Kategori: {{ $conf['label'] }} ({{ $categoryCounts[$key] ?? 0 }} data)
</option>
@endforeach
</select>
</div>
<div>
<label class="block text-xs font-semibold text-slate-700 mb-1.5">
Ketik <span class="font-mono font-bold text-rose-700">KOSONGKAN</span> untuk konfirmasi:
</label>
<input type="text"
id="confirmText"
name="confirm_text"
oninput="validateEmptyTrashInput(this.value)"
placeholder="KOSONGKAN"
class="w-full text-xs rounded-xl border-slate-200 focus:border-rose-500 focus:ring focus:ring-rose-200/50 py-2.5 px-3 uppercase tracking-wider font-semibold">
</div>
<div class="flex items-center justify-end gap-2.5 pt-2">
<button type="button"
onclick="closeEmptyTrashModal()"
class="px-4 py-2 rounded-xl border border-slate-200 hover:bg-slate-50 text-slate-700 text-xs font-semibold transition">
Batal
</button>
<button type="submit"
id="emptyTrashSubmitBtn"
disabled
class="px-4 py-2 rounded-xl bg-rose-600 hover:bg-rose-700 disabled:opacity-40 disabled:cursor-not-allowed text-white text-xs font-semibold transition shadow-xs">
Kosongkan Sekarang
</button>
</div>
</form>
</div>
</div>
<script>
function openRetentionModal() {
document.getElementById('retentionModal').classList.remove('hidden');
}
function closeRetentionModal() {
document.getElementById('retentionModal').classList.add('hidden');
}
function openEmptyTrashModal() {
document.getElementById('confirmText').value = '';
validateEmptyTrashInput('');
document.getElementById('emptyTrashModal').classList.remove('hidden');
}
function closeEmptyTrashModal() {
document.getElementById('emptyTrashModal').classList.add('hidden');
}
function validateEmptyTrashInput(value) {
const btn = document.getElementById('emptyTrashSubmitBtn');
if (value.trim() === 'KOSONGKAN') {
btn.removeAttribute('disabled');
} else {
btn.setAttribute('disabled', 'disabled');
}
}
</script>
@endsection
+10
View File
@@ -254,6 +254,12 @@
<i class="fa-solid fa-database text-base w-5 text-center"></i>
<span>Backup & Restore</span>
</a>
<a href="{{ route('admin.trash.index') }}"
class="flex items-center space-x-3 px-3.5 py-2.5 text-sm {{ request()->routeIs('admin.trash.*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-trash-can text-base w-5 text-center"></i>
<span>Tong Sampah</span>
</a>
</nav>
</div>
@endif
@@ -640,6 +646,10 @@
<i class="fa-solid fa-database w-5 text-center"></i>
<span>Backup & Restore</span>
</a>
<a href="{{ route('admin.trash.index') }}" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-sm {{ request()->routeIs('admin.trash.*') ? 'sidebar-item-active' : 'sidebar-item-inactive' }}">
<i class="fa-solid fa-trash-can w-5 text-center"></i>
<span>Tong Sampah</span>
</a>
</nav>
</div>
@endif
+8
View File
@@ -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');
});
});
@@ -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', [
@@ -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
+1 -1
View File
@@ -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
@@ -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);
}
+1 -1
View File
@@ -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]);
}
/**
+1 -1
View File
@@ -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]);
}
/**
+1 -1
View File
@@ -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]);
}
/**
+2 -2
View File
@@ -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]);
}
}
}
+313
View File
@@ -0,0 +1,313 @@
<?php
namespace Tests\Feature;
use App\Models\Employee;
use App\Models\Gate;
use App\Models\SystemSetting;
use App\Models\User;
use App\Models\Vehicle;
use App\Models\VehicleActivity;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class TrashAndAutoDeleteTest extends TestCase
{
use RefreshDatabase;
protected User $superAdmin;
protected User $regularUser;
protected Vehicle $vehicle;
protected Employee $driver;
protected Gate $gate;
protected function setUp(): void
{
parent::setUp();
Role::firstOrCreate(['name' => '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,
]);
}
}