74 lines
2.2 KiB
PHP
74 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Admin\Settings;
|
|
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Spatie\Permission\Models\Permission;
|
|
use Spatie\Permission\Models\Role;
|
|
|
|
class RoleService
|
|
{
|
|
public function paginated(int $perPage = 25, string $search = '', string $sort = 'created_at', string $direction = 'desc', array $filters = []): LengthAwarePaginator
|
|
{
|
|
return Role::query()
|
|
->select(['id', 'name'])
|
|
->withCount('permissions')
|
|
->when($search, fn ($q) => $q->where('name', 'like', "%{$search}%"))
|
|
->orderBy($sort, $direction)
|
|
->paginate($perPage);
|
|
}
|
|
|
|
public function store(array $data): Role
|
|
{
|
|
return DB::transaction(function () use ($data) {
|
|
$role = Role::create(['name' => $data['name']]);
|
|
$role->syncPermissions($data['permissions']);
|
|
|
|
return $role;
|
|
});
|
|
}
|
|
|
|
public function update(Role $role, array $data): Role
|
|
{
|
|
DB::transaction(function () use ($role, $data) {
|
|
$role->update(['name' => $data['name']]);
|
|
$role->syncPermissions($data['permissions']);
|
|
});
|
|
|
|
return $role->fresh('permissions');
|
|
}
|
|
|
|
public function destroy(Role $role): bool
|
|
{
|
|
return $role->delete();
|
|
}
|
|
|
|
public function getPermissionsByModule(): array
|
|
{
|
|
return Permission::all()
|
|
->groupBy(fn ($p) => explode('.', $p->name)[0])
|
|
->map(fn ($group) => $group->pluck('name')->map(fn ($name) => explode('.', $name, 2)[1])->values()->toArray())
|
|
->toArray();
|
|
}
|
|
|
|
public function getForEmployee(): Collection
|
|
{
|
|
$query = Role::where('name', '!=', 'Developer');
|
|
|
|
$user = auth()->user();
|
|
|
|
if ($user->hasAnyRole(['admin-toko', 'direktur'])) {
|
|
$query->where('name', '!=', 'admin-bahan-baku');
|
|
}
|
|
|
|
if (! $user->hasAnyRole(['developer', 'owner', 'direktur', 'admin-toko'])) {
|
|
$userRoles = $user->roles->pluck('name');
|
|
$query->whereIn('name', $userRoles);
|
|
}
|
|
|
|
return $query->get(['id', 'name']);
|
|
}
|
|
}
|