feat: restrict payroll index visibility to current user for Admin role

This commit is contained in:
Yoga Pangestu 2026-04-30 15:04:25 +07:00
parent ad6b9e9618
commit 002b6fa468
2 changed files with 64 additions and 0 deletions

View File

@ -24,10 +24,16 @@ public function index(): Response
return Inertia::render('admin/finance/payroll/index', [
'payrolls' => Payroll::with(['user.profile', 'adjustments'])
->where('period_month', '!=', $currentMonth)
->when(auth()->user()->hasRole('Admin'), function ($query) {
$query->where('user_id', auth()->id());
})
->latest()
->get(),
'currentMonthPayrolls' => Payroll::with(['user.profile', 'adjustments'])
->where('period_month', $currentMonth)
->when(auth()->user()->hasRole('Admin'), function ($query) {
$query->where('user_id', auth()->id());
})
->get(),
]);
}

View File

@ -2,7 +2,9 @@
use App\Enums\SalaryAdjustmentType;
use App\Models\Payroll;
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Spatie\Permission\Models\Role;
use function Pest\Laravel\actingAs;
use function Pest\Laravel\assertDatabaseHas;
@ -54,6 +56,62 @@
);
});
it('filters payrolls for Admin role to only see their own records', function () {
Role::findOrCreate('Admin');
$admin = createAuthorizedUser(['View:Payroll']);
$admin->assignRole('Admin');
$otherUser = User::factory()->create();
$currentMonth = now()->format('Y-m');
// Payroll for admin
$adminPayroll = Payroll::factory()->create([
'user_id' => $admin->id,
'period_month' => $currentMonth,
]);
// Payroll for other user
Payroll::factory()->create([
'user_id' => $otherUser->id,
'period_month' => $currentMonth,
]);
actingAs($admin)
->get(route('payroll.index'))
->assertOk()
->assertInertia(fn ($page) => $page
->component('admin/finance/payroll/index')
->has('currentMonthPayrolls', 1)
->where('currentMonthPayrolls.0.id', $adminPayroll->id)
);
});
it('shows all payrolls for users without Admin role', function () {
$user = createAuthorizedUser(['View:Payroll']);
// No Admin role assigned
$otherUser = User::factory()->create();
$currentMonth = now()->format('Y-m');
Payroll::factory()->create([
'user_id' => $user->id,
'period_month' => $currentMonth,
]);
Payroll::factory()->create([
'user_id' => $otherUser->id,
'period_month' => $currentMonth,
]);
actingAs($user)
->get(route('payroll.index'))
->assertOk()
->assertInertia(fn ($page) => $page
->component('admin/finance/payroll/index')
->has('currentMonthPayrolls', 2)
);
});
it('can generate payroll', function () {
// Mocking artisan call is tricky if we want to check side effects,
// but here we check the response and session.