>|null */ private ?array $verwendungCache = null; public static function canAccess(): bool { return self::darfPflegen(); } public static function darfPflegen(): bool { return ContentElementResource::editor(); } public function mount(): void { if (! array_key_exists($this->gruppe, $this->gruppen())) { $this->gruppe = 'materialart'; } } public function getSubheading(): string|Htmlable|null { return 'Auswahlwerte für Redaktion, Filter und Picker. Bezeichnungen sind änderbar, Zuordnungen bleiben erhalten; verwendete Werte werden deaktiviert statt gelöscht.'; } public function getMaxContentWidth(): Width|string|null { return Width::Full; } /** * @return array Schlüssel => Bezeichnung */ public function gruppen(): array { $gruppen = ['materialart' => 'Fachliche Materialarten']; $dimensionen = EditorialDimension::query()->where('slug', '!=', EditorialDimension::PILLAR_SLUG)->get() ->sortBy(fn (EditorialDimension $d): string => sprintf('%02d', array_search($d->slug, self::DIMENSION_ORDER, true) === false ? 99 : array_search($d->slug, self::DIMENSION_ORDER, true)).$d->label); foreach ($dimensionen as $dimension) { $gruppen[$dimension->slug] = (string) $dimension->label; } return $gruppen; } public function zeigeGruppe(string $gruppe): void { if (array_key_exists($gruppe, $this->gruppen())) { $this->gruppe = $gruppe; $this->verwendungCache = null; $this->resetTable(); } } public function saeulenUrl(): string { return PillarResource::getUrl('index'); } private function istMaterialart(): bool { return $this->gruppe === 'materialart'; } private function dimension(): ?EditorialDimension { return $this->istMaterialart() ? null : EditorialDimension::query()->where('slug', $this->gruppe)->first(); } // --------------------------------------------------------------------------------------------------------------- // Tabelle // --------------------------------------------------------------------------------------------------------------- public function table(Table $table): Table { $materialart = $this->istMaterialart(); return $table ->query(function (): Builder { if ($this->istMaterialart()) { return EditorialContentKind::query(); } return EditorialDimensionValue::query()->where('editorial_dimension_id', $this->dimension()?->id ?? 0); }) ->defaultSort('sort_order') ->reorderable('sort_order') ->reorderRecordsTriggerAction(fn (Action $action, bool $isReordering): Action => $action ->button() ->label($isReordering ? 'Sortieren beenden' : 'Per Ziehen sortieren')) ->paginated(false) ->searchPlaceholder('Bezeichnung oder Kennung') ->columns(array_values(array_filter([ TextColumn::make('label') ->label('Bezeichnung') ->searchable(['label', 'slug']) ->weight('semibold') ->wrap() ->description(fn (Model $record): string => 'Kennung: '.$record->slug .($record instanceof EditorialContentKind && $record->isSystem() ? ' · vom System verwendet' : '')), $materialart ? TextColumn::make('contexts') ->label('Zulässig für') ->state(fn (EditorialContentKind $record): array => array_values(array_map( fn (string $context): string => EditorialContentKind::CONTEXTS[$context] ?? $context, (array) ($record->contexts ?? []), ))) ->badge() ->color('gray') ->wrap() : null, TextColumn::make('is_active') ->label('Status') ->formatStateUsing(fn (bool $state): string => $state ? 'Aktiv' : 'Inaktiv') ->badge() ->color(fn (bool $state): string => $state ? 'success' : 'gray'), TextColumn::make('verwendung') ->label('Verwendung') ->state(fn (Model $record): string => $this->verwendungText($record)) ->wrap() ->action($this->verwendungAction()->name('verwendungZeigen')), ]))) ->filters([ SelectFilter::make('is_active') ->label('Status') ->options(['1' => 'Aktiv', '0' => 'Inaktiv']), ]) ->recordActions([ Action::make('hoch') ->label('Nach oben') ->icon('heroicon-m-arrow-up') ->iconButton() ->color('gray') ->authorize(fn (): bool => self::darfPflegen()) ->disabled(fn (Model $record): bool => $this->nachbar($record, -1) === null) ->action(fn (Model $record) => $this->verschiebe($record, -1)), Action::make('runter') ->label('Nach unten') ->icon('heroicon-m-arrow-down') ->iconButton() ->color('gray') ->authorize(fn (): bool => self::darfPflegen()) ->disabled(fn (Model $record): bool => $this->nachbar($record, 1) === null) ->action(fn (Model $record) => $this->verschiebe($record, 1)), $this->bearbeitenAction(), ActionGroup::make([ $this->verwendungAction(), $this->umschaltenAction(), $this->loeschenAction(), ])->label('Weitere')->icon('heroicon-m-chevron-down')->button()->size('sm')->color('gray'), ]) ->emptyStateHeading('Noch keine Werte') ->emptyStateDescription('Mit „Wert anlegen“ entsteht der erste Wert dieser Gruppe.'); } protected function getHeaderActions(): array { return [ Action::make('anlegen') ->label('Wert anlegen') ->icon('heroicon-o-plus') ->authorize(fn (): bool => self::darfPflegen()) ->modalHeading(fn (): string => 'Neuer Wert: '.($this->gruppen()[$this->gruppe] ?? '')) ->schema(fn (): array => $this->formular(null)) ->fillForm(fn (): array => ['contexts' => ['medium']]) ->modalSubmitActionLabel('Anlegen') ->action(function (array $data): void { $this->anlegen($data); }), ]; } // --------------------------------------------------------------------------------------------------------------- // Formular, Anlegen, Bearbeiten // --------------------------------------------------------------------------------------------------------------- /** * @return list */ private function formular(?Model $record): array { $felder = [ TextInput::make('label') ->label('Bezeichnung') ->required() ->maxLength(120) ->helperText($record !== null ? 'Die Kennung „'.$record->slug.'“ bleibt; vorhandene Zuordnungen behalten den Wert und zeigen die neue Bezeichnung.' : 'Die Kennung entsteht aus der Bezeichnung und bleibt danach fest.'), ]; if ($this->istMaterialart()) { $system = $record instanceof EditorialContentKind && $record->isSystem(); $felder[] = CheckboxList::make('contexts') ->label('Zulässig für') ->options(EditorialContentKind::CONTEXTS) ->required() ->live() ->columns(['default' => 2, 'md' => 4]) ->disabled($system) ->dehydrated(! $system) ->helperText($system ? 'Diese Materialart verwendet das System; ihre Kontexte bleiben fest.' : 'Nur hier wird die Materialart neu angeboten. Programm und Modul gehören zu den Objektarten Programm und Modul, nicht zu Medien.'); if ($record instanceof EditorialContentKind) { $felder[] = Placeholder::make('konflikt') ->label('Bestehende Zuordnungen') ->visible(fn (Get $get): bool => $this->kontextKonflikte($record, (array) $get('contexts')) !== []) ->content(fn (Get $get): HtmlString => new HtmlString('' .e(implode(' ', $this->kontextKonflikte($record, (array) $get('contexts')))) .' Diese Zuordnungen bleiben erhalten und werden dort als „hier nicht vorgesehen“ gekennzeichnet; neu wählbar ist die Materialart dort nicht mehr.')); $felder[] = Checkbox::make('konflikt_bestaetigt') ->label('Ich habe die bestehenden Zuordnungen geprüft.') ->accepted() ->visible(fn (Get $get): bool => $this->kontextKonflikte($record, (array) $get('contexts')) !== []); } } return $felder; } /** * @return list Meldungen je entferntem Kontext mit Verwendung */ private function kontextKonflikte(EditorialContentKind $kind, array $neu): array { $verwendung = $this->verwendung($kind); $meldungen = []; $zeilen = null; foreach ((array) ($kind->contexts ?? []) as $context) { if (! in_array($context, $neu, true) && ($verwendung[$context] ?? 0) > 0) { $zeilen ??= $this->verwendungListe($kind)['zeilen']; $titel = array_slice(array_column(array_filter($zeilen, fn (array $z): bool => $z['art'] === (EditorialContentKind::CONTEXTS[$context] ?? '')), 'titel'), 0, 5); $meldungen[] = (EditorialContentKind::CONTEXTS[$context] ?? $context).': '.$verwendung[$context].' '.($verwendung[$context] === 1 ? 'Zuordnung' : 'Zuordnungen') .($titel !== [] ? ' („'.implode('“, „', $titel).'“'.($verwendung[$context] > count($titel) ? ' und weitere' : '').')' : '').'.'; } } return $meldungen; } private function bearbeitenAction(): Action { return Action::make('bearbeiten') ->label('Bearbeiten') ->icon('heroicon-o-pencil-square') ->button() ->size('sm') ->color('gray') ->authorize(fn (): bool => self::darfPflegen()) ->modalHeading(fn (Model $record): string => '„'.$record->label.'“ bearbeiten') ->schema(fn (Model $record): array => $this->formular($record)) ->fillForm(fn (Model $record): array => [ 'label' => $record->label, 'contexts' => $record instanceof EditorialContentKind ? (array) ($record->contexts ?? []) : [], ]) ->modalSubmitActionLabel('Speichern') ->action(function (Model $record, array $data): void { $label = trim((string) $data['label']); $this->pruefeBezeichnung($label, $record); $record->label = $label; if ($record instanceof EditorialContentKind && ! $record->isSystem() && isset($data['contexts'])) { $record->contexts = $this->kontexte((array) $data['contexts']); } $record->save(); Notification::make()->success()->title('Gespeichert')->body('Die neue Bezeichnung gilt sofort in Redaktion, Filtern und Picker.')->send(); }); } private function anlegen(array $data): void { $label = trim((string) $data['label']); $this->pruefeBezeichnung($label, null); if ($this->istMaterialart()) { EditorialContentKind::query()->create([ 'label' => $label, 'slug' => $this->freieKennung($label, EditorialContentKind::query()), 'sort_order' => (int) EditorialContentKind::query()->max('sort_order') + 10, 'is_active' => true, 'contexts' => $this->kontexte((array) ($data['contexts'] ?? [])), ]); } else { $dimension = $this->dimension(); abort_if($dimension === null, 404); $werte = EditorialDimensionValue::query()->where('editorial_dimension_id', $dimension->id); EditorialDimensionValue::query()->create([ 'editorial_dimension_id' => $dimension->id, 'label' => $label, 'slug' => $this->freieKennung($label, clone $werte), 'sort_order' => (int) (clone $werte)->max('sort_order') + 10, 'is_active' => true, ]); } $this->verwendungCache = null; Notification::make()->success()->title('Angelegt: „'.$label.'“')->body('Der Wert ist sofort in der passenden Redaktion wählbar.')->send(); } private function pruefeBezeichnung(string $label, ?Model $ausser): void { $query = $this->istMaterialart() ? EditorialContentKind::query() : EditorialDimensionValue::query()->where('editorial_dimension_id', $this->dimension()?->id ?? 0); $doppelt = $query->whereRaw('LOWER(label) = ?', [mb_strtolower($label)]) ->when($ausser !== null, fn (Builder $q) => $q->whereKeyNot($ausser->getKey())) ->exists(); if ($label === '' || $doppelt) { Notification::make()->danger()->title($label === '' ? 'Die Bezeichnung fehlt.' : 'Diese Bezeichnung gibt es in der Gruppe schon.')->send(); throw new Halt; } } /** * @return list */ private function kontexte(array $kontexte): array { $erlaubt = array_keys(EditorialContentKind::CONTEXTS); return array_values(array_filter($erlaubt, fn (string $context): bool => in_array($context, $kontexte, true))); } private function freieKennung(string $label, Builder $query): string { $basis = Str::slug($label) ?: 'wert'; $kennung = $basis; $nummer = 2; while ((clone $query)->where('slug', $kennung)->exists()) { $kennung = $basis.'-'.$nummer++; } return $kennung; } // --------------------------------------------------------------------------------------------------------------- // Aktiv, Löschen, Reihenfolge // --------------------------------------------------------------------------------------------------------------- private function umschaltenAction(): Action { return Action::make('umschalten') ->label(fn (Model $record): string => $record->is_active ? 'Deaktivieren' : 'Reaktivieren') ->icon(fn (Model $record): string => $record->is_active ? 'heroicon-o-eye-slash' : 'heroicon-o-eye') ->authorize(fn (): bool => self::darfPflegen()) ->hidden(fn (Model $record): bool => $record instanceof EditorialContentKind && $record->isSystem()) ->requiresConfirmation() ->modalHeading(fn (Model $record): string => '„'.$record->label.'“ '.($record->is_active ? 'deaktivieren?' : 'reaktivieren?')) ->modalDescription(fn (Model $record): string => $record->is_active ? 'Der Wert wird für neue Zuordnungen nicht mehr angeboten. '.$this->verwendungSatz($record).' Filter finden diese Objekte weiterhin.' : 'Der Wert wird wieder für neue Zuordnungen angeboten.') ->modalSubmitActionLabel(fn (Model $record): string => $record->is_active ? 'Deaktivieren' : 'Reaktivieren') ->action(function (Model $record): void { abort_if($record instanceof EditorialContentKind && $record->isSystem(), 403); $record->is_active = ! $record->is_active; $record->save(); }); } private function loeschenAction(): Action { return Action::make('loeschen') ->label('Löschen') ->icon('heroicon-o-trash') ->color('danger') ->authorize(fn (): bool => self::darfPflegen()) ->visible(fn (Model $record): bool => $this->loeschbar($record)) ->requiresConfirmation() ->modalHeading(fn (Model $record): string => '„'.$record->label.'“ löschen?') ->modalDescription('Der Wert ist nirgends zugeordnet und wird endgültig entfernt.') ->modalSubmitActionLabel('Löschen') ->action(function (Model $record): void { // Erneut prüfen: Zwischenzeitlich entstandene Zuordnungen würden die Datenbank sonst still lösen. if (! $this->loeschbar($record)) { Notification::make()->danger()->title('Nicht gelöscht: Der Wert ist inzwischen zugeordnet. Deaktivieren Sie ihn stattdessen.')->send(); return; } $record->delete(); $this->verwendungCache = null; }); } private function loeschbar(Model $record): bool { if ($record instanceof EditorialContentKind && $record->isSystem()) { return false; } return array_sum($this->verwendung($record, frisch: true)) === 0; } private function nachbar(Model $record, int $richtung): ?Model { $liste = $this->geordnet(); $index = $liste->search(fn (Model $m): bool => $m->is($record)); return $index === false ? null : $liste->get($index + $richtung); } private function verschiebe(Model $record, int $richtung): void { $liste = $this->geordnet()->values(); $index = $liste->search(fn (Model $m): bool => $m->is($record)); if ($index === false || $liste->get($index + $richtung) === null) { return; } $nachbar = $liste->get($index + $richtung); // Nur die beiden Einträge tauschen; neu nummeriert wird nur bei gleicher Reihenfolgezahl. if ((int) $record->sort_order !== (int) $nachbar->sort_order) { DB::transaction(function () use ($record, $nachbar): void { [$a, $b] = [(int) $record->sort_order, (int) $nachbar->sort_order]; $record->sort_order = $b; $record->save(); $nachbar->sort_order = $a; $nachbar->save(); }); return; } $neu = $liste->all(); [$neu[$index], $neu[$index + $richtung]] = [$neu[$index + $richtung], $neu[$index]]; DB::transaction(function () use ($neu): void { foreach (array_values($neu) as $position => $eintrag) { if ((int) $eintrag->sort_order !== ($position + 1) * 10) { $eintrag->sort_order = ($position + 1) * 10; $eintrag->save(); } } }); } /** * @return Collection */ private function geordnet(): Collection { $query = $this->istMaterialart() ? EditorialContentKind::query() : EditorialDimensionValue::query()->where('editorial_dimension_id', $this->dimension()?->id ?? 0); return $query->orderBy('sort_order')->orderBy('id')->get()->values(); } // --------------------------------------------------------------------------------------------------------------- // Verwendung // --------------------------------------------------------------------------------------------------------------- /** * Zuordnungen je Objektkontext. * * @return array */ public function verwendung(Model $record, bool $frisch = false): array { if ($frisch || $this->verwendungCache === null) { $this->verwendungCache = $this->istMaterialart() ? $this->materialartVerwendung() : $this->einordnungVerwendung(); } return $this->verwendungCache[(int) $record->getKey()] ?? []; } private function verwendungText(Model $record): string { $teile = []; foreach ($this->verwendung($record) as $context => $anzahl) { if ($anzahl > 0) { $teile[] = $anzahl.' '.$this->einheit($context, $anzahl); } } return $teile === [] ? 'Nicht verwendet' : implode(' · ', $teile); } private function verwendungSatz(Model $record): string { $text = $this->verwendungText($record); return $text === 'Nicht verwendet' ? 'Er ist derzeit nirgends zugeordnet.' : 'Bestehende Zuordnungen ('.$text.') bleiben erhalten und sichtbar.'; } private function einheit(string $context, int $anzahl): string { return match ($context) { 'medium' => $anzahl === 1 ? 'Medium' : 'Medien', 'modul' => $anzahl === 1 ? 'Modul' : 'Module', 'programm' => $anzahl === 1 ? 'Programm' : 'Programme', 'lizenzartikel' => 'Lizenzartikel', default => $anzahl === 1 ? 'Kombination' : 'Kombinationen', }; } /** * @return array> */ private function materialartVerwendung(): array { $ergebnis = []; foreach (DB::table('content_elements')->whereNotNull('editorial_content_kind_id')->groupBy('editorial_content_kind_id')->selectRaw('editorial_content_kind_id as id, count(*) as anzahl')->get() as $zeile) { $ergebnis[(int) $zeile->id]['medium'] = (int) $zeile->anzahl; } foreach (DB::table('compositions')->whereNotNull('editorial_content_kind_id')->groupBy('editorial_content_kind_id', 'kind')->selectRaw('editorial_content_kind_id as id, kind, count(*) as anzahl')->get() as $zeile) { $context = EditorialVocabulary::compositionContext(CompositionKind::tryFrom((string) $zeile->kind)) ?? 'kombination'; $ergebnis[(int) $zeile->id][$context] = ($ergebnis[(int) $zeile->id][$context] ?? 0) + (int) $zeile->anzahl; } foreach (DB::table('license_articles')->whereNotNull('editorial_content_kind_id')->groupBy('editorial_content_kind_id')->selectRaw('editorial_content_kind_id as id, count(*) as anzahl')->get() as $zeile) { $ergebnis[(int) $zeile->id]['lizenzartikel'] = (int) $zeile->anzahl; } return $ergebnis; } /** * @return array> */ private function einordnungVerwendung(): array { $ergebnis = []; $zeilen = DB::table('identity_dimension_values') ->leftJoin('compositions', function ($join): void { $join->on('compositions.id', '=', 'identity_dimension_values.subject_id') ->where('identity_dimension_values.subject_type', (new Composition)->getMorphClass()); }) ->groupBy('identity_dimension_values.editorial_dimension_value_id', 'identity_dimension_values.subject_type', 'compositions.kind') ->selectRaw('identity_dimension_values.editorial_dimension_value_id as id, identity_dimension_values.subject_type as typ, compositions.kind as kind, count(*) as anzahl') ->get(); foreach ($zeilen as $zeile) { $context = match ($zeile->typ) { (new ContentElement)->getMorphClass() => 'medium', (new LicenseArticle)->getMorphClass() => 'lizenzartikel', default => EditorialVocabulary::compositionContext(CompositionKind::tryFrom((string) $zeile->kind)) ?? 'kombination', }; $ergebnis[(int) $zeile->id][$context] = ($ergebnis[(int) $zeile->id][$context] ?? 0) + (int) $zeile->anzahl; } return $ergebnis; } private function verwendungAction(): Action { return Action::make('verwendung') ->label('Verwendung') ->icon('heroicon-m-list-bullet') ->authorize(fn (): bool => self::darfPflegen()) ->modalHeading(fn (Model $record): string => 'Verwendung von „'.$record->label.'“') ->modalContent(fn (Model $record) => view('filament.stammdaten-verwendung', $this->verwendungListe($record))) ->modalSubmitAction(false) ->modalCancelActionLabel('Schließen'); } /** * Zugeordnete Objekte mit Links in ihre Bearbeitung und gefilterte Bestandslisten. * * @return array{zeilen: list, mehr: int, filter: list} */ public function verwendungListe(Model $record): array { $grenze = 40; $zeilen = []; $filter = []; if ($record instanceof EditorialContentKind) { $medien = ContentElement::query()->where('editorial_content_kind_id', $record->id); $kompositionen = Composition::query()->where('editorial_content_kind_id', $record->id); $artikel = LicenseArticle::query()->where('editorial_content_kind_id', $record->id); if ((clone $medien)->exists()) { $filter[] = ['label' => 'Im Medienmanager filtern', 'url' => ContentElementResource::getUrl('index', ['inhaltsart' => $record->id])]; } } else { $zuordnung = fn (string $klasse) => DB::table('identity_dimension_values') ->where('editorial_dimension_value_id', $record->getKey()) ->where('subject_type', (new $klasse)->getMorphClass()) ->pluck('subject_id'); $medien = ContentElement::query()->whereKey($zuordnung(ContentElement::class)); $kompositionen = Composition::query()->whereKey($zuordnung(Composition::class)); $artikel = LicenseArticle::query()->whereKey($zuordnung(LicenseArticle::class)); if ((clone $medien)->exists()) { $filter[] = ['label' => 'Im Medienmanager filtern', 'url' => ContentElementResource::getUrl('index', ['einordnung' => $record->getKey()])]; } if ((clone $kompositionen)->exists()) { $filter[] = ['label' => 'Programme und Module filtern', 'url' => EditorialDesk::getUrl(['pillar' => $record->getKey()])]; } } $gesamt = (clone $medien)->count() + (clone $kompositionen)->count() + (clone $artikel)->count(); foreach ($medien->orderBy('working_title')->limit($grenze)->get() as $element) { $zeilen[] = ['art' => 'Medium', 'titel' => (string) ($element->display_title ?: $element->working_title), 'url' => ContentElementResource::getUrl('view', ['record' => $element])]; } foreach ($kompositionen->orderBy('designation')->limit($grenze)->get() as $composition) { $context = EditorialVocabulary::compositionContext($composition->kind instanceof CompositionKind ? $composition->kind : CompositionKind::tryFrom((string) $composition->kind)); $zeilen[] = ['art' => EditorialContentKind::CONTEXTS[$context ?? ''] ?? 'Kombination', 'titel' => (string) ($composition->display_title ?: $composition->designation), 'url' => EditorialCatalog::editUrl($composition)]; } foreach ($artikel->orderBy('code')->limit($grenze)->get() as $article) { $zeilen[] = ['art' => 'Lizenzartikel', 'titel' => trim($article->code.' '.($article->display_title ?: $article->working_title)), 'url' => LicenseArticleResource::getUrl('view', ['record' => $article])]; } return ['zeilen' => $zeilen, 'mehr' => max(0, $gesamt - count($zeilen)), 'filter' => $filter]; } }