fix(user,trash): fix 500 server error when deleting user with operational history and protect audit integrity
This commit is contained in:
@@ -73,6 +73,7 @@ class TrashController extends Controller
|
|||||||
*/
|
*/
|
||||||
public function forceDelete(string $category, int $id): RedirectResponse
|
public function forceDelete(string $category, int $id): RedirectResponse
|
||||||
{
|
{
|
||||||
|
try {
|
||||||
$success = $this->trashService->forceDeleteItem($category, $id);
|
$success = $this->trashService->forceDeleteItem($category, $id);
|
||||||
|
|
||||||
if (!$success) {
|
if (!$success) {
|
||||||
@@ -91,6 +92,9 @@ class TrashController extends Controller
|
|||||||
);
|
);
|
||||||
|
|
||||||
return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem.");
|
return back()->with('success', "Data '{$label}' berhasil dihapus permanen dari sistem.");
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
return back()->with('error', 'Aksi Ditolak: ' . $e->getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ use App\Services\ImageCompressionService;
|
|||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Illuminate\View\View;
|
use Illuminate\View\View;
|
||||||
@@ -419,8 +420,10 @@ class UserController extends Controller
|
|||||||
$userRole = $user->role ?? '';
|
$userRole = $user->role ?? '';
|
||||||
$userId = $user->id;
|
$userId = $user->id;
|
||||||
|
|
||||||
$user->syncRoles([]);
|
try {
|
||||||
|
DB::transaction(function () use ($user) {
|
||||||
$user->delete();
|
$user->delete();
|
||||||
|
});
|
||||||
|
|
||||||
// Rekam ke Log Riwayat Aktivitas Super Admin
|
// Rekam ke Log Riwayat Aktivitas Super Admin
|
||||||
$roleTitle = $this->getFriendlyRoleName($userRole);
|
$roleTitle = $this->getFriendlyRoleName($userRole);
|
||||||
@@ -435,7 +438,11 @@ class UserController extends Controller
|
|||||||
);
|
);
|
||||||
|
|
||||||
return redirect()->route('admin.users.index')
|
return redirect()->route('admin.users.index')
|
||||||
->with('success', "Akun pengguna [{$name}] berhasil dihapus dari sistem.");
|
->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()) {
|
if ($vehicle->isSupportCategory()) {
|
||||||
// Otomatis buatkan Master Template P2H baru jika belum ada
|
// Otomatis buatkan Master Template P2H baru jika belum ada
|
||||||
$templateCode = $vehicle->unit_type ?: $vehicle->code;
|
$templateCode = $vehicle->code;
|
||||||
$template = P2hTemplate::firstOrCreate(
|
$template = P2hTemplate::firstOrCreate(
|
||||||
['code' => $templateCode],
|
['code' => $templateCode],
|
||||||
[
|
[
|
||||||
'name' => $vehicle->unit_type ?: $vehicle->brand_type,
|
'name' => $vehicle->unit_category ?: ($vehicle->unit_type ?: $vehicle->brand_type),
|
||||||
'description' => "Template form inspeksi P2H resmi untuk {$vehicle->unit_type} (Kode: {$templateCode}).",
|
'description' => "Template form inspeksi P2H resmi untuk " . ($vehicle->unit_category ?: $vehicle->brand_type) . " (Kode: {$templateCode}).",
|
||||||
'is_active' => true,
|
'is_active' => true,
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|||||||
+17
-8
@@ -33,17 +33,26 @@ class User extends Authenticatable
|
|||||||
});
|
});
|
||||||
|
|
||||||
static::deleting(function (User $user) {
|
static::deleting(function (User $user) {
|
||||||
if ($user->employee) {
|
$employee = $user->employee ?: Employee::where('user_id', $user->id)->orWhere('nik', $user->username)->first();
|
||||||
if ($user->employee->activities()->exists() || $user->employee->p2hRecords()->exists()) {
|
$guard = $user->securityGuard ?: SecurityGuard::where('user_id', $user->id)->first();
|
||||||
throw new \Exception("Tidak dapat menghapus user: Karyawan '{$user->name}' memiliki data audit riwayat operasional kendaraan atau inspeksi P2H.");
|
|
||||||
|
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();
|
$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.");
|
||||||
}
|
}
|
||||||
if ($user->securityGuard) {
|
} else {
|
||||||
if ($user->securityGuard->activities()->exists()) {
|
// Soft delete: cukup cascade soft delete data employee & securityGuard jika ada dan belum terhapus
|
||||||
throw new \Exception("Tidak dapat menghapus user: Petugas Satpam '{$user->name}' memiliki riwayat data validasi pos gerbang.");
|
if ($employee && ! $employee->trashed()) {
|
||||||
|
$employee->delete();
|
||||||
|
}
|
||||||
|
if ($guard && ! $guard->trashed()) {
|
||||||
|
$guard->delete();
|
||||||
}
|
}
|
||||||
$user->securityGuard->delete();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -378,6 +378,36 @@ class TrashService
|
|||||||
EmployeeSimper::onlyTrashed()
|
EmployeeSimper::onlyTrashed()
|
||||||
->where('employee_id', $item->id)
|
->where('employee_id', $item->id)
|
||||||
->restore();
|
->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) {
|
if ($item instanceof SimperType) {
|
||||||
@@ -453,6 +483,14 @@ class TrashService
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($item instanceof User) {
|
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);
|
ImageCompressionService::deleteIfExists($item->photo_path ?? null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -474,8 +512,12 @@ class TrashService
|
|||||||
$model = $categories[$category]['model'];
|
$model = $categories[$category]['model'];
|
||||||
$items = $model::onlyTrashed()->get();
|
$items = $model::onlyTrashed()->get();
|
||||||
foreach ($items as $item) {
|
foreach ($items as $item) {
|
||||||
|
try {
|
||||||
$this->forceDeleteItem($category, $item->id);
|
$this->forceDeleteItem($category, $item->id);
|
||||||
$totalDeleted++;
|
$totalDeleted++;
|
||||||
|
} catch (\Throwable) {
|
||||||
|
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return $totalDeleted;
|
return $totalDeleted;
|
||||||
}
|
}
|
||||||
@@ -485,8 +527,12 @@ class TrashService
|
|||||||
$model = $config['model'];
|
$model = $config['model'];
|
||||||
$items = $model::onlyTrashed()->get();
|
$items = $model::onlyTrashed()->get();
|
||||||
foreach ($items as $item) {
|
foreach ($items as $item) {
|
||||||
|
try {
|
||||||
$this->forceDeleteItem($catKey, $item->id);
|
$this->forceDeleteItem($catKey, $item->id);
|
||||||
$totalDeleted++;
|
$totalDeleted++;
|
||||||
|
} catch (\Throwable) {
|
||||||
|
// Abaikan item yang tidak dapat dihapus permanen untuk menjaga integritas audit
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -515,8 +561,12 @@ class TrashService
|
|||||||
$model = $config['model'];
|
$model = $config['model'];
|
||||||
$expiredItems = $model::onlyTrashed()->where('deleted_at', '<=', $cutoff)->get();
|
$expiredItems = $model::onlyTrashed()->where('deleted_at', '<=', $cutoff)->get();
|
||||||
foreach ($expiredItems as $item) {
|
foreach ($expiredItems as $item) {
|
||||||
|
try {
|
||||||
$this->forceDeleteItem($catKey, $item->id);
|
$this->forceDeleteItem($catKey, $item->id);
|
||||||
$prunedCount++;
|
$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',
|
'category' => 'unit_support',
|
||||||
'brand_type' => 'Manitou MT-X 733',
|
'brand_type' => 'Manitou MT-X 733',
|
||||||
'unit_category' => 'Telehandler',
|
'unit_category' => 'Telehandler',
|
||||||
|
'unit_type' => 'Telehandler',
|
||||||
|
'operational_group' => 'HEAVY',
|
||||||
'status' => 'Operation',
|
'status' => 'Operation',
|
||||||
'current_km' => 0,
|
'current_km' => 0,
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -155,6 +155,7 @@ class QmaModuleTest extends TestCase
|
|||||||
'category' => 'unit_support',
|
'category' => 'unit_support',
|
||||||
'brand_type' => 'Caterpillar D6R',
|
'brand_type' => 'Caterpillar D6R',
|
||||||
'unit_category' => 'Bulldozer',
|
'unit_category' => 'Bulldozer',
|
||||||
|
'operational_group' => 'HEAVY',
|
||||||
'unit_type' => 'Track-type Tractor',
|
'unit_type' => 'Track-type Tractor',
|
||||||
'brand' => 'Caterpillar',
|
'brand' => 'Caterpillar',
|
||||||
'model_number' => 'D6R XL',
|
'model_number' => 'D6R XL',
|
||||||
@@ -174,6 +175,7 @@ class QmaModuleTest extends TestCase
|
|||||||
'code' => 'DZ01',
|
'code' => 'DZ01',
|
||||||
'category' => 'unit_support',
|
'category' => 'unit_support',
|
||||||
'unit_category' => 'Bulldozer',
|
'unit_category' => 'Bulldozer',
|
||||||
|
'operational_group' => 'HEAVY',
|
||||||
'silo_document' => 'SILO-2026/01',
|
'silo_document' => 'SILO-2026/01',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -302,7 +302,7 @@ class QmaUnitManagementTest extends TestCase
|
|||||||
$vehicle->refresh();
|
$vehicle->refresh();
|
||||||
$this->assertEquals('inside_site', $vehicle->site_status);
|
$this->assertEquals('inside_site', $vehicle->site_status);
|
||||||
$this->assertEquals($this->gate->name, $vehicle->location);
|
$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);
|
$this->assertStringContainsString('TRX-IN-001', $vehicle->location_note);
|
||||||
|
|
||||||
// Verifikasi riwayat tersimpan otomatis bersumber gate_crossing
|
// Verifikasi riwayat tersimpan otomatis bersumber gate_crossing
|
||||||
@@ -312,7 +312,7 @@ class QmaUnitManagementTest extends TestCase
|
|||||||
'location' => $this->gate->name,
|
'location' => $this->gate->name,
|
||||||
'source' => 'gate_crossing',
|
'source' => 'gate_crossing',
|
||||||
'vehicle_activity_id' => $activity->id,
|
'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();
|
$vehicle->refresh();
|
||||||
$this->assertEquals('outside_site', $vehicle->site_status);
|
$this->assertEquals('outside_site', $vehicle->site_status);
|
||||||
$this->assertEquals('Luar Site - Antar Dokumen ke Kantor Jambi', $vehicle->location);
|
$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
|
// Verifikasi riwayat tersimpan otomatis
|
||||||
$this->assertDatabaseHas('vehicle_location_histories', [
|
$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