Loheide-eu-mitarbeiterplatt.../app/Filament/Resources/Roles/RoleResource.php
Friederich Loheide 9ddc35a62c
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m30s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m28s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m31s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m36s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 1m45s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 1m44s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 1m35s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 1m38s
CI / Build-Artefakte aktuell (pull_request) Successful in 54s
Rollen, Rechte und Zielgruppen
- Rollen mit globalen Rechten und Rechten für einzelne Objekte (z. B. „Beiträge
  schreiben in Kategorie MAV-Info“); Rollen sind additiv, Zuweisungen merken
  sich ihre Herkunft (manuell oder später Identity-Provider-Gruppe)
- Systemrolle „Administration“ ersetzt users.is_admin (Migration übernimmt
  bestehende Administratoren); nicht löschbar, man kann sie sich nicht selbst entziehen
- Rechte je Person vorberechnet und gecacht, Versionszähler invalidiert bei Änderungen
- Gate-Anbindung: registrierte Rechte entscheidet das Rechtesystem, Objektregeln
  die Policies; Admin-Seiten und Plugin-Ressourcen hinter passenden Rechten
- Redaktion nach Kategorie: Schreiben und Veröffentlichen getrennt, Liste im
  Admin auf eigene Kategorien beschränkt, ohne Veröffentlichungsrecht bleibt
  ein Beitrag Entwurf
- Zielgruppen (Rolle/Abteilung/Standort) für Kategorien und Termine als
  indizierte SQL-Bedingung in Listen, Detailseiten, Kacheln und .ics-Export
- Admin: Rollen-Verwaltung, „Rechte prüfen“, Redaktion und Sichtbarkeit direkt
  an Kategorie bzw. Termin
- Kern-Ressourcen explizit registriert, damit nach Updates liegengebliebene
  alte Dateien nicht doppelt geladen werden
- docs/PLUGINS.md für Plugin-Entwicklung; Demo-Rolle „MAV“

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 07:18:37 +00:00

208 lines
10 KiB
PHP

<?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 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\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),
]),
Section::make('Globale Rechte')
->description('Gelten im ganzen Portal.')
->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'])->all())
->bulkToggleable()
->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(2)
->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'])
->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;
}),
])
->afterStateHydrated(fn (Repeater $component, ?Role $record) => $component->state(
$record?->grants()->whereNotNull('resource_type')->get()
->groupBy('ability')
->map(fn ($grants, $ability) => [
'ability' => $ability,
'resource_ids' => $grants->map(fn (Grant $g) => $g->resource_id === null ? '*' : (string) $g->resource_id)->values()->all(),
])->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']);
foreach (array_unique($ids) as $id) {
$record->grants()->create(['ability' => $item['ability'], 'resource_type' => $type, 'resource_id' => $id]);
}
}
})
->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) {
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'),
];
}
}