80 lines
2.7 KiB
PHP
80 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Modules\Users;
|
|
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Validation\Rule;
|
|
use IriksIT\Manager\Models\Group;
|
|
use IriksIT\Manager\Support\AuditTrail;
|
|
use IriksIT\Manager\Support\ModuleRegistry;
|
|
|
|
/** The groups and what each allows. Only for a super admin (the `groups.manage` gate). */
|
|
class GroupController
|
|
{
|
|
public function __construct(private readonly ModuleRegistry $modules) {}
|
|
|
|
public function index(): JsonResponse
|
|
{
|
|
return response()->json([
|
|
'groups' => Group::query()->withCount('users')->orderBy('name')->get()
|
|
->map(fn (Group $group) => [
|
|
'id' => $group->id,
|
|
'name' => $group->name,
|
|
'description' => $group->description,
|
|
'permissions' => $group->allowed(),
|
|
'accounts' => $group->users_count,
|
|
])->values(),
|
|
'catalogue' => $this->modules->catalogue(),
|
|
]);
|
|
}
|
|
|
|
public function store(Request $request): JsonResponse
|
|
{
|
|
$group = Group::create($this->validated($request));
|
|
|
|
return response()->json(['id' => $group->id], 201);
|
|
}
|
|
|
|
public function update(Request $request, string $group): JsonResponse
|
|
{
|
|
$group = Group::query()->findOrFail($group);
|
|
app(AuditTrail::class)->about($group);
|
|
$group->update($this->validated($request, $group));
|
|
|
|
return response()->json(['saved' => true]);
|
|
}
|
|
|
|
/** The accounts in it stay; they lose what only this group allowed. */
|
|
public function destroy(string $group): JsonResponse
|
|
{
|
|
$group = Group::query()->findOrFail($group);
|
|
app(AuditTrail::class)->about($group);
|
|
$group->users()->detach();
|
|
$group->delete();
|
|
|
|
return response()->json(['deleted' => true]);
|
|
}
|
|
|
|
/** @return array{name: string, description: string|null, permissions: list<string>} */
|
|
private function validated(Request $request, ?Group $group = null): array
|
|
{
|
|
$table = config('manager.table_prefix').'groups';
|
|
|
|
$request->validate([
|
|
'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)],
|
|
'description' => ['nullable', 'string', 'max:500'],
|
|
'permissions' => ['array'],
|
|
'permissions.*' => ['string', Rule::in($this->modules->permissionValues())],
|
|
]);
|
|
|
|
$description = $request->string('description')->trim()->toString();
|
|
|
|
return [
|
|
'name' => $request->string('name')->trim()->toString(),
|
|
'description' => $description !== '' ? $description : null,
|
|
'permissions' => $this->modules->complete($request->array('permissions')),
|
|
];
|
|
}
|
|
}
|