Loheide-eu-mitarbeiterplatt.../app/Filament/Resources/Roles/RoleResource.php
Friederich Loheide b967c16b6d
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Failing after 8m49s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Failing after 8m47s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Failing after 8m40s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Failing after 9m24s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 11m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 12m4s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 10m37s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 45s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m12s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 10m41s
Einfache Ansicht für Klienten (0.57.0)
Rollen-Schalter simple_ui: größere Schrift, Leichte Sprache automatisch,
Startseite mit großen Kacheln; Hinweis in „Was sieht wer?“.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 16:34:14 +00:00

240 lines
13 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Filament\Resources\Roles;
use App\Filament\Resources\Roles\Pages\CreateRole;
use App\Filament\Resources\Roles\Pages\EditRole;
use App\Filament\Resources\Roles\Pages\ListRoles;
use App\Models\Grant;
use App\Models\Role;
use App\Models\User;
use App\Support\Abilities;
use App\Support\Permissions\Permissions;
use App\Support\Permissions\RoleGuard;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use UnitEnum;
class RoleResource extends Resource
{
protected static ?string $model = Role::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedShieldCheck;
protected static string|UnitEnum|null $navigationGroup = 'Benutzer & Rechte';
protected static ?string $modelLabel = 'Rolle';
protected static ?string $pluralModelLabel = 'Rollen';
protected static ?string $slug = 'rollen';
protected static ?int $navigationSort = 2;
protected static ?string $recordTitleAttribute = 'name';
public static function form(Schema $schema): Schema
{
$abilities = app(Abilities::class);
return $schema
->columns(1)
->components([
Section::make('Rolle')
->columns(2)
->schema([
TextInput::make('name')->label('Name')->required()->maxLength(100)->disabled(fn (?Role $record) => $record?->is_system),
Textarea::make('description')->label('Beschreibung')->rows(2)->maxLength(500),
Toggle::make('simple_ui')->label('Einfache Ansicht')->columnSpanFull()
->visible(fn (?Role $record) => ! $record?->isAdministration())
->helperText('Für Personen, die das Portal einfach nutzen sollen (z. B. Klienten): größere Schrift und Knöpfe, Leichte Sprache wo vorhanden, Startseite mit großen Kacheln. Welche Bereiche die Rolle sieht, legen Sie unter „Was sieht wer?“ fest.'),
]),
Section::make('Globale Rechte')
->description('Gelten im ganzen Portal. Rechte mit „im Portal“ werden in der Redaktion ausgeübt und öffnen nicht das Backend.')
->visible(fn (?Role $record) => ! $record?->isAdministration())
->schema([
CheckboxList::make('global_abilities')
->hiddenLabel()
->columns(2)
->options(fn () => collect($abilities->global())->map(fn (array $a) => $a['label'])->all())
->descriptions(fn () => collect($abilities->global())->map(fn (array $a) => $a['group'].($a['portal'] ? ' · im Portal' : ' · Backend'))->all())
->bulkToggleable()
// Nur Rechte eintragen, die man selbst besitzt
->disableOptionWhen(fn (string $value) => ! RoleGuard::canGrant(auth()->user(), $value))
->rule(fn (?Role $record) => function (string $attribute, mixed $value, \Closure $fail) use ($record) {
$before = $record?->grants()->whereNull('resource_type')->pluck('ability')->all() ?? [];
foreach (array_merge(array_diff((array) $value, $before), array_diff($before, (array) $value)) as $ability) {
if (! RoleGuard::canGrant(auth()->user(), (string) $ability)) {
$fail('Sie können nur Rechte vergeben oder entziehen, die Sie selbst haben.');
return;
}
}
})
->afterStateHydrated(fn (CheckboxList $component, ?Role $record) => $component->state(
$record?->grants()->whereNull('resource_type')->pluck('ability')->all() ?? []
))
->saveRelationshipsUsing(function (Role $record, ?array $state) {
$record->grants()->whereNull('resource_type')->where('ability', '!=', '*')->delete();
foreach (array_unique($state ?? []) as $ability) {
$record->grants()->create(['ability' => $ability]);
}
})
->dehydrated(false),
]),
Section::make('Rechte für einzelne Objekte')
->description('Zum Beispiel: Beiträge schreiben nur in der Kategorie „MAV-Info“.')
->visible(fn (?Role $record) => ! $record?->isAdministration() && $abilities->resourceTypes() !== [])
->schema([
Repeater::make('object_grants')
->hiddenLabel()
->columns(3)
->addActionLabel('Recht hinzufügen')
->defaultItems(0)
->schema([
Select::make('ability')
->label('Recht')
->required()
->live()
->options(fn () => collect($abilities->all())
->filter(fn (array $a) => $a['resource'] !== null)
->map(fn (array $a) => $a['group'].': '.$a['label'].($a['portal'] ? ' (im Portal)' : ''))
->all()),
Select::make('resource_ids')
->label('Für')
->multiple()
->required()
->options(function (Get $get) use ($abilities) {
$type = $abilities->all()[$get('ability')]['resource'] ?? null;
$options = $type ? ($abilities->resourceTypes()[$type]['options'])() : [];
return ['*' => 'Alle'] + $options;
}),
Toggle::make('include_children')
->label('Inkl. Unterseiten')
->inline(false)
->default(true)
->visible(fn (Get $get) => $abilities->isHierarchical($abilities->all()[$get('ability')]['resource'] ?? null)),
])
->afterStateHydrated(fn (Repeater $component, ?Role $record) => $component->state(
$record?->grants()->whereNotNull('resource_type')->get()
->groupBy(fn (Grant $g) => $g->ability.'|'.(int) $g->include_children)
->map(fn ($grants) => [
'ability' => $grants->first()->ability,
'resource_ids' => $grants->map(fn (Grant $g) => $g->resource_id === null ? '*' : (string) $g->resource_id)->values()->all(),
'include_children' => (bool) $grants->first()->include_children,
])->values()->all() ?? []
))
->saveRelationshipsUsing(function (Role $record, ?array $state) use ($abilities) {
$record->grants()->whereNotNull('resource_type')->delete();
foreach ($state ?? [] as $item) {
$type = $abilities->all()[$item['ability'] ?? '']['resource'] ?? null;
if (! $type) {
continue;
}
$ids = in_array('*', (array) $item['resource_ids'], true) ? [null] : array_map('intval', (array) $item['resource_ids']);
$inherit = $abilities->isHierarchical($type) && ($item['include_children'] ?? false);
foreach (array_unique($ids) as $id) {
$record->grants()->create(['ability' => $item['ability'], 'resource_type' => $type, 'resource_id' => $id, 'include_children' => $inherit && $id !== null]);
}
}
})
->dehydrated(false),
]),
Section::make('Mitglieder')
->description('Manuell zugewiesene Personen. Personen aus Identity-Provider-Gruppen kommen automatisch dazu.')
->schema([
Select::make('members')
->hiddenLabel()
->multiple()
->searchable()
->getSearchResultsUsing(fn (string $search) => User::query()
->where(fn ($q) => $q->where('name', 'like', "%{$search}%")->orWhere('email', 'like', "%{$search}%"))
->orderBy('name')->limit(50)->pluck('name', 'id')->all())
->getOptionLabelsUsing(fn (array $values) => User::query()->whereIn('id', $values)->pluck('name', 'id')->all())
->afterStateHydrated(fn (Select $component, ?Role $record) => $component->state(
$record?->users()->wherePivot('source', 'manual')->pluck('users.id')->all() ?? []
))
->rule(fn (?Role $record) => function (string $attribute, mixed $value, \Closure $fail) use ($record) {
$before = $record?->users()->wherePivot('source', 'manual')->pluck('users.id')->all() ?? [];
if ($record && array_diff(array_map('intval', (array) $value), $before) && ! RoleGuard::canAssign(auth()->user(), $record)) {
$fail('Diese Rolle enthält Rechte, die Sie selbst nicht haben – Sie können keine Personen hinzufügen.');
}
if ($record?->isAdministration() && ! in_array(auth()->id(), array_map('intval', (array) $value), true)) {
$fail('Sie können sich nicht selbst aus der Rolle „Administration“ entfernen.');
}
})
->saveRelationshipsUsing(function (Role $record, ?array $state) {
$ids = array_map('intval', $state ?? []);
$current = $record->users()->wherePivot('source', 'manual')->pluck('users.id')->all();
foreach (array_diff($current, $ids) as $userId) {
$record->users()->wherePivot('source', 'manual')->detach($userId);
}
foreach (array_diff($ids, $current) as $userId) {
$record->users()->attach($userId, ['source' => 'manual', 'created_at' => now()]);
}
Permissions::flush();
})
->dehydrated(false),
]),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('name')
->modifyQueryUsing(fn ($query) => $query->withCount(['users', 'grants']))
->columns([
TextColumn::make('name')->label('Name')->searchable()->weight('medium')
->description(fn (Role $record) => $record->description),
IconColumn::make('is_system')->label('System')->boolean()->trueIcon(Heroicon::LockClosed)->falseIcon(false),
TextColumn::make('users_count')->label('Mitglieder'),
TextColumn::make('grants_count')->label('Rechte')
->formatStateUsing(fn (Role $record, $state) => $record->isAdministration() ? 'alle' : $state),
])
->recordActions([
EditAction::make(),
DeleteAction::make()->visible(fn (Role $record) => ! $record->is_system),
]);
}
public static function getPages(): array
{
return [
'index' => ListRoles::route('/'),
'create' => CreateRole::route('/neu'),
'edit' => EditRole::route('/{record}/bearbeiten'),
];
}
}