fix(user,trash): fix 500 server error when deleting user with operational history and protect audit integrity
This commit is contained in:
@@ -73,24 +73,28 @@ class TrashController extends Controller
|
||||
*/
|
||||
public function forceDelete(string $category, int $id): RedirectResponse
|
||||
{
|
||||
$success = $this->trashService->forceDeleteItem($category, $id);
|
||||
try {
|
||||
$success = $this->trashService->forceDeleteItem($category, $id);
|
||||
|
||||
if (!$success) {
|
||||
return back()->with('error', 'Data tidak ditemukan di tong sampah atau gagal dihapus permanen.');
|
||||
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.");
|
||||
} catch (\Throwable $e) {
|
||||
return back()->with('error', 'Aksi Ditolak: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$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.");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Services\ImageCompressionService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\View\View;
|
||||
@@ -419,23 +420,29 @@ class UserController extends Controller
|
||||
$userRole = $user->role ?? '';
|
||||
$userId = $user->id;
|
||||
|
||||
$user->syncRoles([]);
|
||||
$user->delete();
|
||||
try {
|
||||
DB::transaction(function () use ($user) {
|
||||
$user->delete();
|
||||
});
|
||||
|
||||
// Rekam ke Log Riwayat Aktivitas Super Admin
|
||||
$roleTitle = $this->getFriendlyRoleName($userRole);
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Manajemen Pengguna',
|
||||
description: "Menghapus akun pengguna: {$name} (Username: {$username}) dengan hak akses '{$roleTitle}'.",
|
||||
targetType: 'User',
|
||||
targetId: $userId,
|
||||
targetName: $name,
|
||||
oldValues: $deletedSnapshot
|
||||
);
|
||||
// Rekam ke Log Riwayat Aktivitas Super Admin
|
||||
$roleTitle = $this->getFriendlyRoleName($userRole);
|
||||
AdminActivityLog::record(
|
||||
actionType: 'delete',
|
||||
module: 'Manajemen Pengguna',
|
||||
description: "Menghapus akun pengguna: {$name} (Username: {$username}) dengan hak akses '{$roleTitle}'.",
|
||||
targetType: 'User',
|
||||
targetId: $userId,
|
||||
targetName: $name,
|
||||
oldValues: $deletedSnapshot
|
||||
);
|
||||
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('success', "Akun pengguna [{$name}] berhasil dihapus dari sistem.");
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('success', "Akun pengguna [{$name}] berhasil dihapus dan dipindahkan ke Tong Sampah.");
|
||||
} catch (\Throwable $e) {
|
||||
return redirect()->route('admin.users.index')
|
||||
->with('error', 'Gagal menghapus pengguna: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1446,12 +1446,12 @@ class VehicleController extends Controller
|
||||
|
||||
if ($vehicle->isSupportCategory()) {
|
||||
// Otomatis buatkan Master Template P2H baru jika belum ada
|
||||
$templateCode = $vehicle->unit_type ?: $vehicle->code;
|
||||
$templateCode = $vehicle->code;
|
||||
$template = P2hTemplate::firstOrCreate(
|
||||
['code' => $templateCode],
|
||||
[
|
||||
'name' => $vehicle->unit_type ?: $vehicle->brand_type,
|
||||
'description' => "Template form inspeksi P2H resmi untuk {$vehicle->unit_type} (Kode: {$templateCode}).",
|
||||
'name' => $vehicle->unit_category ?: ($vehicle->unit_type ?: $vehicle->brand_type),
|
||||
'description' => "Template form inspeksi P2H resmi untuk " . ($vehicle->unit_category ?: $vehicle->brand_type) . " (Kode: {$templateCode}).",
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
+18
-9
@@ -33,17 +33,26 @@ class User extends Authenticatable
|
||||
});
|
||||
|
||||
static::deleting(function (User $user) {
|
||||
if ($user->employee) {
|
||||
if ($user->employee->activities()->exists() || $user->employee->p2hRecords()->exists()) {
|
||||
throw new \Exception("Tidak dapat menghapus user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H.");
|
||||
$employee = $user->employee ?: Employee::where('user_id', $user->id)->orWhere('nik', $user->username)->first();
|
||||
$guard = $user->securityGuard ?: SecurityGuard::where('user_id', $user->id)->first();
|
||||
|
||||
if ($user->isForceDeleting()) {
|
||||
$employeeTrashed = $employee ?: Employee::withTrashed()->where('user_id', $user->id)->orWhere('nik', $user->username)->first();
|
||||
if ($employeeTrashed && ($employeeTrashed->activities()->exists() || $employeeTrashed->p2hRecords()->exists() || $employeeTrashed->supportTimesheets()->exists())) {
|
||||
throw new \RuntimeException("Tidak dapat menghapus permanen user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H.");
|
||||
}
|
||||
$user->employee->delete();
|
||||
}
|
||||
if ($user->securityGuard) {
|
||||
if ($user->securityGuard->activities()->exists()) {
|
||||
throw new \Exception("Tidak dapat menghapus user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang.");
|
||||
$guardTrashed = $guard ?: SecurityGuard::withTrashed()->where('user_id', $user->id)->first();
|
||||
if ($guardTrashed && $guardTrashed->activities()->exists()) {
|
||||
throw new \RuntimeException("Tidak dapat menghapus permanen user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang.");
|
||||
}
|
||||
} else {
|
||||
// Soft delete: cukup cascade soft delete data employee & securityGuard jika ada dan belum terhapus
|
||||
if ($employee && ! $employee->trashed()) {
|
||||
$employee->delete();
|
||||
}
|
||||
if ($guard && ! $guard->trashed()) {
|
||||
$guard->delete();
|
||||
}
|
||||
$user->securityGuard->delete();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -378,6 +378,36 @@ class TrashService
|
||||
EmployeeSimper::onlyTrashed()
|
||||
->where('employee_id', $item->id)
|
||||
->restore();
|
||||
|
||||
$user = User::onlyTrashed()->where('id', $item->user_id)->orWhere('username', $item->nik)->first();
|
||||
if ($user) {
|
||||
$user->restore();
|
||||
if ($user->role && ! $user->hasRole($user->role)) {
|
||||
$role = \Spatie\Permission\Models\Role::where('name', $user->role)->first();
|
||||
if ($role) {
|
||||
$user->assignRole($role);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($item instanceof User) {
|
||||
if ($item->role && ! $item->hasRole($item->role)) {
|
||||
$role = \Spatie\Permission\Models\Role::where('name', $item->role)->first();
|
||||
if ($role) {
|
||||
$item->assignRole($role);
|
||||
}
|
||||
}
|
||||
|
||||
$employee = Employee::onlyTrashed()->where('user_id', $item->id)->orWhere('nik', $item->username)->first();
|
||||
if ($employee) {
|
||||
$employee->restore();
|
||||
}
|
||||
|
||||
$guard = SecurityGuard::onlyTrashed()->where('user_id', $item->id)->first();
|
||||
if ($guard) {
|
||||
$guard->restore();
|
||||
}
|
||||
}
|
||||
|
||||
if ($item instanceof SimperType) {
|
||||
@@ -453,6 +483,14 @@ class TrashService
|
||||
}
|
||||
|
||||
if ($item instanceof User) {
|
||||
$employee = Employee::withTrashed()->where('user_id', $item->id)->orWhere('nik', $item->username)->first();
|
||||
if ($employee && ($employee->activities()->exists() || $employee->p2hRecords()->exists() || $employee->supportTimesheets()->exists())) {
|
||||
throw new \RuntimeException("User '{$item->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H dan tidak dapat dihapus permanen untuk menjaga integritas data.");
|
||||
}
|
||||
$guard = SecurityGuard::withTrashed()->where('user_id', $item->id)->first();
|
||||
if ($guard && $guard->activities()->exists()) {
|
||||
throw new \RuntimeException("User '{$item->name}' memiliki riwayat data validasi pos gerbang dan tidak dapat dihapus permanen untuk menjaga integritas data.");
|
||||
}
|
||||
ImageCompressionService::deleteIfExists($item->photo_path ?? null);
|
||||
}
|
||||
|
||||
@@ -474,8 +512,12 @@ class TrashService
|
||||
$model = $categories[$category]['model'];
|
||||
$items = $model::onlyTrashed()->get();
|
||||
foreach ($items as $item) {
|
||||
$this->forceDeleteItem($category, $item->id);
|
||||
$totalDeleted++;
|
||||
try {
|
||||
$this->forceDeleteItem($category, $item->id);
|
||||
$totalDeleted++;
|
||||
} catch (\Throwable) {
|
||||
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||
}
|
||||
}
|
||||
return $totalDeleted;
|
||||
}
|
||||
@@ -485,8 +527,12 @@ class TrashService
|
||||
$model = $config['model'];
|
||||
$items = $model::onlyTrashed()->get();
|
||||
foreach ($items as $item) {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$totalDeleted++;
|
||||
try {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$totalDeleted++;
|
||||
} catch (\Throwable) {
|
||||
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -515,8 +561,12 @@ class TrashService
|
||||
$model = $config['model'];
|
||||
$expiredItems = $model::onlyTrashed()->where('deleted_at', '<=', $cutoff)->get();
|
||||
foreach ($expiredItems as $item) {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$prunedCount++;
|
||||
try {
|
||||
$this->forceDeleteItem($catKey, $item->id);
|
||||
$prunedCount++;
|
||||
} catch (\Throwable) {
|
||||
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -334,6 +334,8 @@ class P2hInspectionTest extends TestCase
|
||||
'category' => 'unit_support',
|
||||
'brand_type' => 'Manitou MT-X 733',
|
||||
'unit_category' => 'Telehandler',
|
||||
'unit_type' => 'Telehandler',
|
||||
'operational_group' => 'HEAVY',
|
||||
'status' => 'Operation',
|
||||
'current_km' => 0,
|
||||
]);
|
||||
|
||||
@@ -155,6 +155,7 @@ class QmaModuleTest extends TestCase
|
||||
'category' => 'unit_support',
|
||||
'brand_type' => 'Caterpillar D6R',
|
||||
'unit_category' => 'Bulldozer',
|
||||
'operational_group' => 'HEAVY',
|
||||
'unit_type' => 'Track-type Tractor',
|
||||
'brand' => 'Caterpillar',
|
||||
'model_number' => 'D6R XL',
|
||||
@@ -174,6 +175,7 @@ class QmaModuleTest extends TestCase
|
||||
'code' => 'DZ01',
|
||||
'category' => 'unit_support',
|
||||
'unit_category' => 'Bulldozer',
|
||||
'operational_group' => 'HEAVY',
|
||||
'silo_document' => 'SILO-2026/01',
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -302,7 +302,7 @@ class QmaUnitManagementTest extends TestCase
|
||||
$vehicle->refresh();
|
||||
$this->assertEquals('inside_site', $vehicle->site_status);
|
||||
$this->assertEquals($this->gate->name, $vehicle->location);
|
||||
$this->assertEquals($this->guard->name, $vehicle->location_updated_by);
|
||||
$this->assertEquals($this->gateOfficer->name, $vehicle->location_updated_by);
|
||||
$this->assertStringContainsString('TRX-IN-001', $vehicle->location_note);
|
||||
|
||||
// Verifikasi riwayat tersimpan otomatis bersumber gate_crossing
|
||||
@@ -312,7 +312,7 @@ class QmaUnitManagementTest extends TestCase
|
||||
'location' => $this->gate->name,
|
||||
'source' => 'gate_crossing',
|
||||
'vehicle_activity_id' => $activity->id,
|
||||
'user_name' => $this->guard->name,
|
||||
'user_name' => $this->gateOfficer->name,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -362,7 +362,7 @@ class QmaUnitManagementTest extends TestCase
|
||||
$vehicle->refresh();
|
||||
$this->assertEquals('outside_site', $vehicle->site_status);
|
||||
$this->assertEquals('Luar Site - Antar Dokumen ke Kantor Jambi', $vehicle->location);
|
||||
$this->assertEquals($this->guard->name, $vehicle->location_updated_by);
|
||||
$this->assertEquals($this->gateOfficer->name, $vehicle->location_updated_by);
|
||||
|
||||
// Verifikasi riwayat tersimpan otomatis
|
||||
$this->assertDatabaseHas('vehicle_location_histories', [
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Employee;
|
||||
use App\Models\Gate;
|
||||
use App\Models\User;
|
||||
use App\Models\Vehicle;
|
||||
use App\Models\VehicleActivity;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class UserSoftDeleteAndProtectionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seed();
|
||||
}
|
||||
|
||||
public function test_deleting_user_with_operational_history_soft_deletes_cleanly_without_500(): void
|
||||
{
|
||||
$superAdmin = User::where('username', 'superadmin')->first();
|
||||
|
||||
// Buat user & employee sukon/karyawan
|
||||
$user = User::factory()->create([
|
||||
'name' => 'Supri Driver',
|
||||
'username' => '123456',
|
||||
'email' => '[email protected]',
|
||||
'role' => 'employee',
|
||||
]);
|
||||
$user->assignRole('employee');
|
||||
|
||||
$employee = Employee::create([
|
||||
'user_id' => $user->id,
|
||||
'nik' => '123456',
|
||||
'name' => 'Supri Driver',
|
||||
'employee_type' => 'Sukon',
|
||||
'division' => 'subkon',
|
||||
'position' => 'Driver',
|
||||
'is_operator' => true,
|
||||
]);
|
||||
|
||||
$gate = Gate::first() ?: Gate::create(['name' => 'Gate Utama', 'code' => 'GU-01']);
|
||||
$vehicle = Vehicle::first() ?: Vehicle::factory()->create();
|
||||
|
||||
// Buat aktivitas riwayat operasional kendaraan
|
||||
$activity = VehicleActivity::create([
|
||||
'transaction_no' => 'TRX-SUPRI-001',
|
||||
'vehicle_id' => $vehicle->id,
|
||||
'driver_id' => $employee->id,
|
||||
'gate_id' => $gate->id,
|
||||
'direction' => 'out',
|
||||
'previous_km' => 1000,
|
||||
'current_km' => 1050,
|
||||
'distance' => 50,
|
||||
'purpose' => 'Pengiriman Material',
|
||||
'recorded_at' => now(),
|
||||
'status' => 'approved',
|
||||
]);
|
||||
|
||||
// Super Admin menghapus akun user Supri dari menu Kelola Pengguna
|
||||
$response = $this->actingAs($superAdmin)
|
||||
->delete(route('admin.users.destroy', $user->id));
|
||||
|
||||
// Harus berhasil redirect tanpa error 500
|
||||
$response->assertStatus(302);
|
||||
$response->assertRedirect(route('admin.users.index'));
|
||||
$response->assertSessionHas('success');
|
||||
|
||||
// Pastikan User & Employee berstatus Soft Deleted (ada di tong sampah)
|
||||
$this->assertSoftDeleted('users', ['id' => $user->id]);
|
||||
$this->assertSoftDeleted('employees', ['id' => $employee->id]);
|
||||
|
||||
// Pastikan riwayat aktivitas operasional tetap UTUH dan tidak hilang
|
||||
$this->assertDatabaseHas('vehicle_activities', [
|
||||
'id' => $activity->id,
|
||||
'driver_id' => $employee->id,
|
||||
]);
|
||||
|
||||
// Coba lakukan Hapus Permanen dari Tong Sampah -> Harus ditolak karena integritas audit
|
||||
$forceResponse = $this->actingAs($superAdmin)
|
||||
->delete(route('admin.trash.force_delete', [
|
||||
'category' => 'users',
|
||||
'id' => $user->id,
|
||||
]));
|
||||
|
||||
$forceResponse->assertStatus(302);
|
||||
$forceResponse->assertSessionHas('error');
|
||||
|
||||
// User tetap ada di basis data (tidak terhapus permanen)
|
||||
$this->assertDatabaseHas('users', ['id' => $user->id]);
|
||||
|
||||
// Pulihkan akun dari Tong Sampah -> User & Employee harus aktif kembali beserta perannya
|
||||
$restoreResponse = $this->actingAs($superAdmin)
|
||||
->post(route('admin.trash.restore', [
|
||||
'category' => 'users',
|
||||
'id' => $user->id,
|
||||
]));
|
||||
|
||||
$restoreResponse->assertStatus(302);
|
||||
$restoreResponse->assertSessionHas('success');
|
||||
|
||||
$this->assertNotSoftDeleted('users', ['id' => $user->id]);
|
||||
$this->assertNotSoftDeleted('employees', ['id' => $employee->id]);
|
||||
$this->assertTrue($user->fresh()->hasRole('employee'));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user