Files
LarsandClaude Opus 5.5 f774d43647
CI Feature / test (push) Successful in 1m12s
Deploy Test / test (push) Successful in 1m7s
Deploy Test / deploy (push) Successful in 23s
Führe die zentrale Pflege redaktioneller Stammdaten ein
FACH-56 bis FACH-58: Arbeitsplatz „Redaktionelle Stammdaten“ für fachliche
Materialarten, Altersbereich und Zielgruppe, Einsatzbereiche und
Verwendungszwecke (bestehende Tabellen; Säulen bleiben in ihrer Verwaltung).

- Migration (nur Ergänzungen): aktiv/inaktiv für Materialarten und Werte,
  Reihenfolge der Werte, zulässige Objektkontexte der Materialarten, einmalig
  aus dem Bestand abgeleitet; jede vorhandene Zuordnung bleibt zulässig.
- EditorialVocabulary als eine Regelquelle für Redaktion (Medium, Modul,
  Programm, Lizenzartikel), Medien- und Kompositionsfilter, Picker und
  Mitgliederbibliothek: neu wählbar nur aktive, kontextgerechte Werte;
  vorhandene inaktive Zuordnungen sichtbar und beim Speichern erhalten;
  serverseitige Prüfung der Materialart.
- Kennung fest, Bezeichnung pflegbar; verwendete Werte nur deaktivierbar;
  Systemkennungen (programm, modul, traineranleitung) geschützt.
- „Inhaltsart“ heißt durchgängig „Fachliche Materialart“; der Picker trennt
  Medienart und fachliche Materialart und filtert danach.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:18:03 +01:00

1084 lines
42 KiB
PHP

<?php
namespace App\Filament\Resources\ContentElements\Pages;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\EditorialVocabulary;
use App\Domain\Catalog\IdentityChange;
use App\Domain\Catalog\IdentityDimension;
use App\Domain\Catalog\IdentityDimensionValue;
use App\Domain\Catalog\IdentityProfile;
use App\Domain\Catalog\Pillar;
use App\Domain\Catalog\PillarService;
use App\Domain\Cms\Catalog\PublicMaterialReader;
use App\Domain\Cms\WebsiteImageUsage;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Media\ThumbnailRef;
use App\Domain\Media\WebsiteMedia;
use App\Domain\Media\WebsiteRelease;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Support\CatalogReading;
use App\Filament\Support\EditorialCatalog;
use App\Filament\Support\ElementRevision;
use App\Filament\Support\ManagesEditorialSurface;
use App\Filament\Support\MediaLibrary;
use App\Filament\Support\ReportsDomainRules;
use App\Http\Controllers\ContentPreviewController;
use App\Jobs\DeriveThumbnail;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\View;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Collection;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Livewire\WithFileUploads;
class ViewContentElement extends ViewRecord
{
use ManagesEditorialSurface;
use ReportsDomainRules;
use WithFileUploads;
protected static string $resource = ContentElementResource::class;
public ?int $fassung = null;
public string $frameSecond = '';
public string $bodyDraft = '';
public string $thumbnailAlt = '';
public string $pictureFeedback = '';
/** Rückmeldung zur ausgewählten Fassung, direkt im Detailbereich. */
public string $fassungFeedback = '';
public bool $fassungFeedbackError = false;
/** Gewählte Quelle für ein neues Vorschaubild: film oder upload. */
public string $bildQuelle = '';
public mixed $previewUpload = null;
public string $bereich = 'inhalt';
public string $workingTitle = '';
public string $displayTitle = '';
public string $teaser = '';
public string $summary = '';
public string $searchTerms = '';
public string $descriptionText = '';
public string $usageNote = '';
public string $licenseNote = '';
public string $websiteCredit = '';
public string $websiteAlt = '';
public string $websiteFeedback = '';
public int|string|null $kindId = null;
/** @var list<int|string> */
public array $pillarIds = [];
/** @var list<int|string> */
public array $dimensionIds = [];
public string $editorialFeedback = '';
public int $versionsBeforeSave = 0;
public string $previewWidth = '640';
public string $previewSurface = 'website';
public string $pickerContext = 'modul';
public string $pickerLayout = 'kacheln';
public function mount(int|string $record): void
{
parent::mount($record);
$requested = request()->integer('fassung');
if ($requested > 0) {
$this->fassung = $requested;
}
$bereich = (string) request()->query('bereich', 'inhalt');
$this->bereich = $this->normalBereich($bereich);
$this->thumbnailAlt = (string) ($this->getRecord()->thumbnail_alt ?? '');
$this->bildQuelle = $this->getRecord()->output_class === 'film' ? 'film' : 'upload';
$this->fillEditorial();
// Die gezeigte Fassung wird festgehalten. Sonst wechselte die Anzeige still auf eine andere Fassung, sobald
// eine Freigabe oder neue Fassung die Vorgabe „neueste freigegebene“ ändert, während das Textfeld noch den
// Wortlaut der bisherigen enthält. Eine fremde oder ungültige Angabe in der Adresse wird dabei ersetzt.
$this->fassung = $this->shownVersion()?->id;
$this->syncBodyDraft();
if (in_array($bereich, ['praesentation', 'redaktion'], true) && $this->canEditEditorial()) {
$this->openRedaktion($bereich === 'praesentation' ? 'medien' : 'texte');
}
}
public function updatedBereich(string $value): void
{
$this->bereich = $this->normalBereich($value);
}
/**
* Bereiche des Medieneditors. Fassungen und Inhalt bilden einen Bereich (Fassungen links, ausgewählte Fassung rechts);
* „fassungen“ bleibt als Adresse gültig. Die früheren Werte „beschreibung“ und „praesentation“ führen zur
* Website-Ansicht, weil Texte und Präsentationsmedien in der gemeinsamen Redaktion bearbeitet werden.
*/
public function normalBereich(string $value): string
{
return match ($value) {
'inhalt', 'vorschaubild', 'verwendung', 'vorschau', 'website' => $value,
'fassungen' => 'inhalt',
'beschreibung', 'praesentation', 'redaktion' => 'website',
default => 'inhalt',
};
}
public function getTitle(): string|Htmlable
{
return (string) $this->getRecord()->working_title;
}
public function getMaxContentWidth(): Width|string|null
{
return Width::Full;
}
public function infolist(Schema $schema): Schema
{
return $schema->components([
View::make('filament.media.viewer')->viewData(fn (): array => $this->viewerData())->columnSpanFull(),
])->columns(1);
}
/**
* Wählt eine Fassung. Ein geänderter, noch nicht gespeicherter Text geht dabei nicht stillschweigend verloren.
*/
public function showVersion(int $version): void
{
abort_unless($this->ownedVersion($version) instanceof ContentElementVersion, 404);
$this->bereich = 'inhalt';
if ($this->shownVersion()?->id === $version) {
return;
}
if ($this->textUnsaved()) {
$this->askConfirmation('showVersion', $version);
return;
}
$this->selectVersion($version);
}
/**
* Der Text der gezeigten Fassung weicht vom gespeicherten Stand ab.
*/
public function textUnsaved(): bool
{
$shown = $this->shownVersion();
return $shown instanceof ContentElementVersion
&& $this->getRecord()->output_class === 'text'
&& $shown->status !== ContentVersionStatus::Gesperrt
&& trim($this->bodyDraft) !== trim((string) $shown->body);
}
public function discardShownText(): void
{
$this->syncBodyDraft();
$this->fassungFeedback = '';
}
private function selectVersion(int $version): void
{
$this->fassung = $version;
$this->fassungFeedback = '';
$this->syncBodyDraft();
}
public function saveShownText(): void
{
$shown = $this->shownVersion();
if (! ContentElementResource::editor() || ! $shown instanceof ContentElementVersion || $shown->element?->output_class !== 'text') {
return;
}
if (! $this->textUnsaved()) {
$this->fassungFeedback = 'Der Text ist unverändert. Es gibt nichts zu speichern.';
$this->fassungFeedbackError = false;
return;
}
try {
$saved = app(ContentService::class)->reviseElementContent($shown, $this->bodyDraft);
} catch (DomainRuleException $exception) {
$this->fassungFeedback = $exception->getMessage();
$this->fassungFeedbackError = true;
return;
}
// Eine freigegebene Fassung bleibt unverändert; die Auswahl folgt der neu angelegten Fassung.
$this->fassungFeedback = $saved->id !== $shown->id
? 'Fassung '.$saved->number.' ist angelegt. Fassung '.$shown->number.' bleibt erhalten.'
: 'Der Text ist in Fassung '.$saved->number.' gespeichert. Es entsteht keine neue Fassung.';
$this->fassungFeedbackError = false;
$this->fassung = $saved->id;
$this->getRecord()->unsetRelation('versions');
$this->syncBodyDraft();
}
public function adoptFrame(): void
{
abort_unless(ContentElementResource::editor(), 403);
/** @var ContentElement $element */
$element = $this->getRecord();
$shown = $this->shownVersion();
if (! $shown instanceof ContentElementVersion || $element->output_class !== 'film') {
$this->pictureFeedback = 'Für dieses Medium gibt es keine Filmstelle.';
return;
}
if (! is_numeric($this->frameSecond) || trim($this->frameSecond) === '') {
$this->pictureFeedback = 'Wähle zuerst eine Zeitposition.';
return;
}
$seconds = (float) $this->frameSecond;
if ($seconds < 0 || $seconds > 7200) {
$this->pictureFeedback = 'Die Zeitposition liegt außerhalb des Films.';
return;
}
$this->keepAlt($element);
$element->thumbnail_error = null;
$element->save();
DeriveThumbnail::dispatch('element', $element->id, null, null, $shown->id, $seconds);
$element->refresh();
$this->pictureFeedback = $element->thumbnail_error
?: 'Das Vorschaubild ist gespeichert. Die Fassung bleibt unverändert.';
}
public function storePreview(): void
{
abort_unless(ContentElementResource::editor(), 403);
if (! $this->previewUpload instanceof TemporaryUploadedFile) {
$this->pictureFeedback = 'Wähle zuerst eine Bilddatei.';
return;
}
$extension = strtolower($this->previewUpload->getClientOriginalExtension());
if (! in_array($extension, ['png', 'jpg', 'jpeg', 'webp'], true)) {
$this->pictureFeedback = 'Das Vorschaubild muss eine Bilddatei sein.';
return;
}
$path = $this->previewUpload->storeAs(
'vorschau',
'karte-'.bin2hex(random_bytes(4)).'.'.$extension,
'cms_incoming',
);
$this->previewUpload = null;
if (! is_string($path)) {
$this->pictureFeedback = 'Das Vorschaubild wurde nicht übernommen.';
return;
}
$this->savePreviewImage($path);
}
public function savePreviewImage(string $path): void
{
abort_unless(ContentElementResource::editor(), 403);
/** @var ContentElement $element */
$element = $this->getRecord();
$this->keepAlt($element);
$element->thumbnail_error = null;
$element->save();
DeriveThumbnail::dispatch('element', $element->id, $path);
$element->refresh();
$this->pictureFeedback = $element->thumbnail_error
?: 'Das Vorschaubild ist gespeichert. Die Fassung bleibt unverändert.';
}
public function useOwnImage(): void
{
abort_unless(ContentElementResource::editor(), 403);
/** @var ContentElement $element */
$element = $this->getRecord();
if ($element->output_class !== 'bild') {
$this->pictureFeedback = 'Die Datei dieses Mediums ist kein Bild. Lade ein Vorschaubild hoch.';
return;
}
$this->keepAlt($element);
$element->thumbnail_error = null;
$element->save();
DeriveThumbnail::dispatch('element', $element->id);
$element->refresh();
$this->pictureFeedback = $element->thumbnail_error
?: 'Das Vorschaubild ist gespeichert. Die Fassung bleibt unverändert.';
}
public function framePreviewUrl(): ?string
{
$shown = $this->shownVersion();
if (! $shown instanceof ContentElementVersion || ! is_numeric($this->frameSecond) || trim($this->frameSecond) === '') {
return null;
}
return route('editorial.frame', [
'version' => $shown->id,
'sekunde' => $this->frameSecond,
]);
}
public function deactivateAction(): Action
{
return Action::make('deactivate')
->label('Deaktivieren')
->modalHeading(fn (array $arguments): string => 'Fassung '.($this->ownedVersion((int) ($arguments['version'] ?? 0))?->number ?? '').' deaktivieren')
->modalDescription('Die Fassung bleibt hier einsehbar. Sie wird nicht mehr ausgeliefert und kann nicht in eine neue Übung oder einen neuen Kurs übernommen werden.')
->modalSubmitActionLabel('Deaktivieren')
->visible(fn (): bool => ContentElementResource::editor())
->schema([
Textarea::make('reason')->label('Begründung')->required(),
])
->action(function (array $data, array $arguments): void {
abort_unless(ContentElementResource::editor(), 403);
$this->report(function () use ($data, $arguments): void {
$version = $this->ownedVersion((int) ($arguments['version'] ?? 0));
abort_unless($version instanceof ContentElementVersion, 404);
app(ContentService::class)->block($version, (string) $data['reason']);
}, 'Die Fassung ist deaktiviert.');
$this->getRecord()->unsetRelation('versions');
});
}
protected function getHeaderActions(): array
{
return [];
}
public function releaseVersionAction(): Action
{
return Action::make('releaseVersion')
->label('Fassung freigeben')
->modalHeading(function (array $arguments): string {
$versionId = (int) ($arguments['version'] ?? 0);
$version = $versionId > 0
? $this->ownedVersion($versionId)
: $this->getRecord()->versions()->where('status', ContentVersionStatus::Entwurf)->orderByDesc('number')->first();
return $version instanceof ContentElementVersion ? 'Fassung '.$version->number.' freigeben' : 'Fassung freigeben';
})
->modalDescription('Diese Fassung wird freigegeben. Sie erscheint dadurch nicht in der Mitgliederbibliothek, nicht auf der Website und nicht in einem Angebot. Eine deaktivierte Fassung bleibt unverändert.')
->modalSubmitActionLabel('Freigeben')
->visible(function (): bool {
/** @var ContentElement $element */
$element = $this->getRecord();
return ContentElementResource::editor()
&& $element->versions()->where('status', ContentVersionStatus::Entwurf)->exists();
})
->action(function (array $arguments): void {
abort_unless(ContentElementResource::editor(), 403);
$this->report(function () use ($arguments): string {
/** @var ContentElement $element */
$element = $this->getRecord();
$versionId = (int) ($arguments['version'] ?? 0);
$version = $versionId > 0
? $this->ownedVersion($versionId)
: $element->versions()->where('status', ContentVersionStatus::Entwurf)->orderByDesc('number')->first();
abort_unless($version instanceof ContentElementVersion, 404);
$released = app(ContentService::class)->releaseElementVersion($version);
return 'Fassung '.$released->number.' ist freigegeben.';
}, 'Die Fassung ist freigegeben.');
$this->getRecord()->unsetRelation('versions');
});
}
public function reviseAction(): Action
{
return Action::make('revise')
->label('Neue Fassung anlegen')
->modalHeading('Neue Fassung anlegen')
->modalDescription('Für eine neue Datei oder einen geänderten Lehrtext. Die bisherigen Fassungen bleiben unverändert. Redaktion, Vorschaubild und Website-Angaben gehören nicht zur Fassung.')
->modalSubmitActionLabel('Fassung anlegen')
->visible(fn (): bool => ContentElementResource::editor())
->schema(fn (): array => ElementRevision::fields($this->getRecord()))
->action(function (array $data): void {
// Vor dem Anlegen prüfen: danach gäbe es eine andere neueste Fassung.
$textOffen = $this->textUnsaved();
$this->report(function () use ($data): string {
/** @var ContentElement $element */
$element = $this->getRecord();
return ElementRevision::publish($element, $data);
}, 'Die neue Fassung ist angelegt.');
$this->getRecord()->unsetRelation('versions');
// Die neue Fassung wird gezeigt, sofern dabei kein offener Text verloren geht.
if (! $textOffen) {
$neueste = $this->getRecord()->versions()->orderByDesc('number')->value('id');
$this->fassung = $neueste !== null ? (int) $neueste : $this->fassung;
$this->fassungFeedback = '';
$this->syncBodyDraft();
}
});
}
/**
* Löschen bleibt Medien ohne Fassung vorbehalten. Bisher nur im separaten Formular, jetzt unter „Weitere Aktionen“.
*/
public function deleteAction(): Action
{
return Action::make('delete')
->label('Medium löschen')
->color('danger')
->requiresConfirmation()
->modalHeading('Medium löschen')
->modalDescription('Das Medium hat keine Fassung und wird endgültig gelöscht. Zuordnungen als Präsentationsmedium entfallen.')
->modalSubmitActionLabel('Löschen')
->visible(fn (): bool => ContentElementResource::editor() && $this->getRecord()->versions()->doesntExist())
->action(function (): void {
abort_unless(ContentElementResource::editor() && $this->getRecord()->versions()->doesntExist(), 403);
$this->getRecord()->delete();
$this->redirect(ContentElementResource::getUrl('index'));
});
}
public function openThumbnailPicker(): void
{
abort_unless(ContentElementResource::editor(), 403);
$this->resetPicker('vorschaubild');
$this->pickerKind = 'bild';
}
protected function adoptThumbnailFromPicker(string $target): void
{
$this->pickerSelected = $target;
$this->adoptLibraryImage();
$this->pickerSelected = '';
}
/**
* @return array{aktion: string, argument: int|string|null, titel: string, text: string, label: string, gefahr: bool}|null
*/
protected function extraConfirmation(string $aktion, int|string|null $argument): ?array
{
$gezeigt = $this->shownVersion();
return match ($aktion) {
'withdrawWebsite' => ['aktion' => $aktion, 'argument' => null, 'titel' => 'Website-Freigabe zurücknehmen?', 'text' => 'Das Medium verschwindet sofort von allen öffentlichen Seiten. Zuordnungen und Fassungen bleiben erhalten.', 'label' => 'Freigabe zurücknehmen', 'gefahr' => true],
'showVersion' => ['aktion' => $aktion, 'argument' => $argument, 'titel' => 'Ungespeicherten Text verwerfen?', 'text' => 'Der geänderte Text von Fassung '.($gezeigt?->number ?? '').' ist noch nicht gespeichert und geht beim Wechsel verloren. Gespeicherte Fassungen bleiben unverändert.', 'label' => 'Verwerfen und wechseln', 'gefahr' => true],
default => null,
};
}
protected function runExtraConfirmation(string $aktion, int|string|null $argument): void
{
match ($aktion) {
'withdrawWebsite' => $this->withdrawWebsite(),
'showVersion' => $this->ownedVersion((int) $argument) instanceof ContentElementVersion ? $this->selectVersion((int) $argument) : null,
default => null,
};
}
public function hasDraftVersion(): bool
{
/** @var ContentElement $element */
$element = $this->getRecord();
return $element->versions()->where('status', ContentVersionStatus::Entwurf)->exists();
}
/**
* @return array{element: ContentElement, versions: Collection<int, ContentElementVersion>, shown: ?ContentElementVersion, fileUrl: ?string, pending: bool, pillars: list<string>, usage: list<string>, canRevise: bool}
*/
private function viewerData(): array
{
/** @var ContentElement $element */
$element = $this->getRecord();
$versions = $element->versions()->orderByDesc('number')->get();
$shown = $versions->firstWhere('id', $this->fassung)
?? $versions->first(fn (ContentElementVersion $version): bool => $version->status === ContentVersionStatus::Bereit)
?? $versions->first();
$preview = app(ContentPreviewController::class);
$committed = $shown instanceof ContentElementVersion && app(ContentService::class)->isCommitted($shown);
return [
'element' => $element,
'versions' => $versions,
'shown' => $shown,
'fileUrl' => $shown === null ? null : $preview->fileUrl($shown),
'pending' => $shown !== null && $preview->isPending($shown),
'pillars' => $element->pillars->pluck('name')->all(),
'usage' => app(CatalogReading::class)->elementUsage($element),
'canRevise' => ContentElementResource::editor(),
'canEditBody' => ContentElementResource::editor()
&& $shown instanceof ContentElementVersion
&& $element->output_class === 'text'
&& $shown->status !== ContentVersionStatus::Gesperrt,
'bodyCommitted' => $committed,
'pictureUrl' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
'pictureCaption' => $this->pictureCaption($element),
];
}
private function syncBodyDraft(): void
{
$this->bodyDraft = (string) ($this->shownVersion()?->body ?? '');
}
private function shownVersion(): ?ContentElementVersion
{
/** @var ContentElement $element */
$element = $this->getRecord();
$versions = $element->versions()->orderByDesc('number')->get();
return $versions->firstWhere('id', $this->fassung)
?? $versions->first(fn (ContentElementVersion $version): bool => $version->status === ContentVersionStatus::Bereit)
?? $versions->first();
}
private function keepAlt(ContentElement $element): void
{
$alt = trim($this->thumbnailAlt);
if ($alt === '') {
return;
}
$element->thumbnail_alt = $alt;
}
private function pictureCaption(ContentElement $element): string
{
$source = $element->thumbnail_source;
if (! is_string($source) || $source === '') {
return '';
}
if (preg_match('/^frame:\d+@([\d.]+)$/', $source, $match) === 1) {
return 'Vorschaubild aus dem Film bei '.$match[1].' Sekunden.';
}
return match ($source) {
'eigen' => 'Eigenes Vorschaubild.',
'datei' => 'Vorschaubild aus der Datei des Mediums.',
'bestand' => 'Vorschaubild aus einem Bild im Bestand. Es ist damit nicht für die Website freigegeben.',
default => '',
};
}
private function ownedVersion(int $id): ?ContentElementVersion
{
/** @var ContentElement $element */
$element = $this->getRecord();
return $element->versions()->whereKey($id)->first();
}
/**
* Speichert die Redaktion: Texte, Einordnung, Präsentationsmedien und Abweichungen. Datei und Fassungen bleiben.
*/
public function saveEditorial(): void
{
$this->saveRedaktion();
}
protected function saveRedaktionTexte(): bool
{
abort_unless(ContentElementResource::editor(), 403);
/** @var ContentElement $element */
$element = $this->getRecord();
$title = trim($this->workingTitle);
if ($title === '') {
$this->deskFeedback = 'Der Arbeitstitel fehlt. Er bezeichnet das Medium in der Verwaltung.';
$this->redaktionFehlerFeld = 'workingTitle';
return false;
}
$kindError = app(EditorialVocabulary::class)->kindError(
'medium',
filled($this->kindId) ? (int) $this->kindId : null,
$element->editorial_content_kind_id !== null ? (int) $element->editorial_content_kind_id : null,
);
if ($kindError !== null) {
$this->deskFeedback = $kindError;
$this->redaktionFehlerFeld = 'kindId';
return false;
}
$this->versionsBeforeSave = $element->versions()->count();
app(IdentityProfile::class)->fill($element, [
'working_title' => $title,
'display_title' => $this->displayTitle,
'teaser' => $this->teaser,
'summary' => $this->summary,
'search_terms' => $this->searchTerms,
'description' => $this->descriptionText,
'usage_note' => $this->usageNote,
'license_note' => $this->licenseNote,
'website_credit' => $this->websiteCredit,
'website_alt' => $this->websiteAlt,
'editorial_content_kind_id' => filled($this->kindId) ? (int) $this->kindId : null,
], auth()->user());
app(PillarService::class)->assign($element, array_map(intval(...), $this->pillarIds));
app(IdentityDimension::class)->replaceOffered($element, array_map(intval(...), $this->dimensionIds));
$element->refresh();
$this->fillEditorial();
return true;
}
protected function redaktionSavedMessage(): string
{
/** @var ContentElement $element */
$element = $this->getRecord();
$this->editorialFeedback = $element->versions()->count() === $this->versionsBeforeSave
? 'Gespeichert. Es gibt keine neue Fassung.'
: 'Gespeichert. Prüfe die Fassungen, ihre Zahl hat sich geändert.';
return $this->editorialFeedback.' Datei, Inhaltsfassung und Website-Freigabe bleiben unverändert.';
}
protected function resetRedaktionTexte(): void
{
$this->fillEditorial();
}
public function einordnungUnsaved(): bool
{
/** @var ContentElement $element */
$element = $this->getRecord()->fresh() ?? $this->getRecord();
$kind = filled($this->kindId) ? (int) $this->kindId : null;
$storedKind = $element->editorial_content_kind_id !== null ? (int) $element->editorial_content_kind_id : null;
if ($kind !== $storedKind) {
return true;
}
$pillars = $element->pillars()->pluck('pillars.id')->map(fn ($id): int => (int) $id)->all();
$currentPillars = array_map(intval(...), $this->pillarIds);
sort($pillars);
sort($currentPillars);
if ($pillars !== $currentPillars) {
return true;
}
$stored = IdentityDimensionValue::query()
->where('subject_type', $element->getMorphClass())
->where('subject_id', $element->getKey())
->where('origin', 'direkt')
->pluck('editorial_dimension_value_id')
->map(fn ($id): int => (int) $id)
->all();
$current = array_map(intval(...), $this->dimensionIds);
sort($stored);
sort($current);
return $stored !== $current;
}
/**
* @return array{art: string, fuer: string, liste: string, zurueck: string, typ: ?string, umfang: string}
*/
public function redaktionKopf(): array
{
/** @var ContentElement $element */
$element = $this->getRecord();
return [
'art' => 'Medium',
'fuer' => 'das Medium',
'liste' => 'Medien',
'zurueck' => 'Zurück zur Medienbearbeitung',
'typ' => $element->editorialContentKind?->label ?? PublicMaterialReader::outputLabel((string) $element->output_class),
'umfang' => '„Redaktion speichern“ sichert Texte, Präsentationsmedien und Einordnung dieses Mediums. Verwendende Ansichten übernehmen die Angaben. Datei, Inhaltsfassung und Website-Freigabe bleiben unverändert.',
];
}
public function redaktionTitel(): string
{
$title = trim($this->displayTitle) !== '' ? trim($this->displayTitle) : trim($this->workingTitle);
return $title !== '' ? $title : (string) $this->getRecord()->working_title;
}
/**
* @return list<array<string, mixed>>
*/
public function redaktionFelder(): array
{
/** @var ContentElement $element */
$element = $this->getRecord();
$stored = fn (string $column): string => (string) ($element->getAttribute($column) ?? '');
return [
['id' => 'arbeitstitel', 'label' => 'Arbeitstitel', 'model' => 'workingTitle', 'kind' => 'text', 'stored' => $stored('working_title'), 'required' => true, 'hilfe' => 'Bezeichnung in der Verwaltung. Pflichtangabe.'],
['id' => 'anzeigename', 'label' => 'Anzeigename', 'model' => 'displayTitle', 'kind' => 'text', 'stored' => $stored('display_title'), 'hilfe' => 'Erscheint auf Karten und in der Bibliothek. Leer zeigt den Arbeitstitel.'],
['id' => 'teaser', 'label' => 'Teaser', 'model' => 'teaser', 'kind' => 'textarea', 'rows' => 2, 'stored' => $stored('teaser')],
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'textarea', 'rows' => 3, 'stored' => $stored('summary'), 'hilfe' => 'Erscheint auf Website- und Bibliothekskarten.'],
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'descriptionText', 'kind' => 'textarea', 'rows' => 8, 'stored' => $stored('description'), 'hilfe' => 'Bleibt in der Verwaltung und in Detailansichten. Kein Lehrtext.'],
['id' => 'suche', 'label' => 'Suchbegriffe', 'model' => 'searchTerms', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('search_terms'), 'placeholder' => 'Begriffe, durch Komma getrennt'],
['id' => 'einsatz', 'label' => 'Hinweise für den Einsatz', 'model' => 'usageNote', 'kind' => 'textarea', 'rows' => 3, 'gruppe' => 'weitere', 'stored' => $stored('usage_note')],
['id' => 'lizenz', 'label' => 'Interner Lizenzvermerk', 'model' => 'licenseNote', 'kind' => 'textarea', 'rows' => 3, 'gruppe' => 'weitere', 'stored' => $stored('license_note'), 'hilfe' => 'Nur intern sichtbar.'],
['id' => 'quelle', 'label' => 'Quellenzeile für die Website', 'model' => 'websiteCredit', 'kind' => 'textarea', 'rows' => 2, 'gruppe' => 'weitere', 'stored' => $stored('website_credit')],
['id' => 'alt', 'label' => 'Alternativtext für die Website', 'model' => 'websiteAlt', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('website_alt'), 'hilfe' => 'Beschreibt das Bild für Menschen, die es nicht sehen.'],
];
}
/**
* @return array{model: string, options: array<int|string, string>, hilfe: string}
*/
public function einordnungArt(): array
{
return [
'model' => 'kindId',
'options' => app(EditorialVocabulary::class)->kindOptions('medium', $this->getRecord()->editorial_content_kind_id !== null ? (int) $this->getRecord()->editorial_content_kind_id : null),
'hilfe' => 'Fachliche Materialart, unabhängig von der technischen Medienart.',
];
}
/**
* @return list<array{legend: string, model: string, values: list<array{id: int, label: string}>}>
*/
public function einordnungGruppen(): array
{
$groups = [[
'legend' => 'Fachliche Säulen',
'model' => 'pillarIds',
'values' => Pillar::query()->orderBy('name')->get(['id', 'name'])
->map(fn (Pillar $pillar): array => ['id' => (int) $pillar->id, 'label' => (string) $pillar->name])->all(),
]];
foreach (app(EditorialVocabulary::class)->dimensionGroups($this->getRecord(), IdentityDimensionValue::query()
->where('subject_type', $this->getRecord()->getMorphClass())
->where('subject_id', $this->getRecord()->getKey())
->pluck('editorial_dimension_value_id')->map(fn ($id): int => (int) $id)->all()) as $dimension) {
$groups[] = [
'legend' => $dimension['label'],
'model' => 'dimensionIds',
'values' => $dimension['values'],
];
}
return array_values(array_filter($groups, fn (array $group): bool => $group['values'] !== []));
}
/**
* @return array{view: string, stand: string}
*/
public function redaktionAusgabe(): ?array
{
return [
'view' => 'filament.media.preview-frame',
'stand' => 'Arbeitstitel, Anzeigename und Kurzbeschreibung zeigen deine aktuellen Eingaben, auch ungespeicherte. Bild und übrige Angaben zeigen den gespeicherten Stand.',
];
}
/**
* Gibt das Medium für die Website frei. Quellenzeile und Alternativtext gelten im gespeicherten Stand der Redaktion;
* offene Eingaben in der Redaktion werden dabei weder gespeichert noch zurückgesetzt.
*/
public function releaseForWebsite(): void
{
abort_unless(ContentElementResource::editor(), 403);
/** @var ContentElement $element */
$element = $this->getRecord();
$this->websiteFeedback = app(WebsiteRelease::class)->release($element, auth()->user());
$element->refresh();
}
public function withdrawWebsite(): void
{
abort_unless(ContentElementResource::editor(), 403);
/** @var ContentElement $element */
$element = $this->getRecord();
$this->websiteFeedback = app(WebsiteRelease::class)->withdraw($element, auth()->user());
$element->refresh();
}
public function saveThumbnailAlt(): void
{
abort_unless(ContentElementResource::editor(), 403);
/** @var ContentElement $element */
$element = $this->getRecord();
app(IdentityProfile::class)->fill($element, ['thumbnail_alt' => trim($this->thumbnailAlt)], auth()->user());
$element->refresh();
$this->thumbnailAlt = (string) ($element->thumbnail_alt ?? '');
$this->pictureFeedback = 'Der Alternativtext des Vorschaubilds ist gespeichert. Die Fassung bleibt unverändert.';
}
/**
* Website-Seiten, die dieses Medium als Bild verwenden (CMS-Widgets und Abschnittshintergründe).
*
* @return list<array{path: string, published: bool, draft: bool}>
*/
public function websitePages(): array
{
/** @var ContentElement $element */
$element = $this->getRecord();
return app(WebsiteImageUsage::class)->pages($element);
}
public function websiteIsPublic(): bool
{
/** @var ContentElement $element */
$element = $this->getRecord();
return app(WebsiteMedia::class)->present($element->fresh()) !== null;
}
public function adoptLibraryImage(): void
{
abort_unless(ContentElementResource::editor(), 403);
/** @var ContentElement $element */
$element = $this->getRecord();
$detail = $this->selectionDetail();
$sourceId = (int) ($detail['element_id'] ?? 0);
$source = $sourceId > 0 ? ContentElement::query()->find($sourceId) : null;
$path = $source?->thumbnail_path;
if (! $source instanceof ContentElement || $source->output_class !== 'bild' || ! is_string($path) || ! str_starts_with($path, 'vorschau/') || str_contains($path, '..')) {
$this->pictureFeedback = 'Dieses Bild hat noch kein übernehmbares Vorschaubild.';
return;
}
$versions = $element->versions()->count();
app(IdentityProfile::class)->fill($element, [
'thumbnail_path' => $path,
'thumbnail_alt' => filled($source->thumbnail_alt) ? $source->thumbnail_alt : $source->working_title,
'thumbnail_source' => 'bestand',
'thumbnail_error' => null,
], auth()->user());
$element->refresh();
$this->thumbnailAlt = (string) ($element->thumbnail_alt ?? '');
$this->pictureFeedback = $element->versions()->count() === $versions
? 'Vorschaubild übernommen. Es gibt keine neue Fassung. Für die Website ist es damit nicht freigegeben.'
: 'Vorschaubild übernommen. Prüfe die Fassungen.';
}
/**
* @return array{items: list<array<string, mixed>>, more: bool}
*/
public function selection(): array
{
return app(EditorialCatalog::class)->browse(
$this->pickerQuery,
$this->pickerContext === 'bild' ? 'bild' : 'alle',
'',
0,
elementsOnly: $this->pickerContext !== 'modul',
);
}
/**
* @return array<string, mixed>|null
*/
public function selectionDetail(): ?array
{
if ($this->pickerSelected === '') {
return null;
}
$row = app(EditorialCatalog::class)->rowForTarget($this->pickerSelected, 0, allowDraft: true);
if ($row === null || ! isset($row['element_id'])) {
return $row;
}
$element = ContentElement::query()->with('editorialContentKind')->find((int) $row['element_id']);
if ($element instanceof ContentElement) {
$row['visibility'] = app(PublicMaterialReader::class)->visibilityNote($element);
}
return $row;
}
public function previewHtml(): string
{
/** @var ContentElement $element */
$element = $this->getRecord();
$draft = [
'working_title' => $this->workingTitle,
'display_title' => $this->displayTitle,
'summary' => $this->summary,
'thumbnail_alt' => $this->thumbnailAlt,
];
if ($this->previewSurface === 'bibliothek') {
$title = trim($this->displayTitle) !== '' ? trim($this->displayTitle) : trim($this->workingTitle);
return view('member.partials.card', [
'href' => '#vorschau',
'card' => [
'title' => $title !== '' ? $title : $element->working_title,
'summary' => trim($this->summary) !== '' ? trim($this->summary) : null,
'kind' => PublicMaterialReader::outputLabel((string) $element->output_class),
'coverage' => 'offen',
'image' => trim($this->thumbnailAlt) !== '' ? trim($this->thumbnailAlt) : $title,
'image_url' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
'error' => 'Vorschau der Kartenform. Ob jemand sie öffnen darf, entscheidet die Lizenz.',
],
])->render();
}
$subject = app(PublicMaterialReader::class)->subject($element->id, true, $draft);
if ($subject === null) {
return '<p class="preview-note">Für dieses Medium liegt noch keine anzeigbare Fassung vor. Die Karte erscheint deshalb auch in der Vorschau nicht.</p>';
}
return view('widgets.premium_card', [
'subject' => $subject,
'context' => RenderContext::preview(),
'cardStyle' => $subject->style ?? 'media',
'imageUrl' => null,
'alt' => '',
'focus' => ['x' => 50, 'y' => 45],
'format' => 'landscape',
'fit' => 'cover',
'headingTag' => 'h3',
'show' => ['summary' => true, 'kind' => true, 'meta' => true, 'action' => true],
'actionLabel' => 'Ansehen',
'note' => null,
'stacked' => $this->previewWidth === '390',
])->render();
}
/**
* @return list<array{field: string, after: string, when: string}>
*/
public function editorialHistory(): array
{
/** @var ContentElement $element */
$element = $this->getRecord();
$labels = [
'working_title' => 'Arbeitstitel',
'display_title' => 'Anzeigename',
'teaser' => 'Teaser',
'description' => 'Beschreibung',
'summary' => 'Kurzbeschreibung',
'search_terms' => 'Suchbegriffe',
'usage_note' => 'Einsatzhinweis',
'license_note' => 'Interner Lizenzvermerk',
'website_credit' => 'Quellenzeile',
'website_alt' => 'Alternativtext der Website',
'website_released_at' => 'Website-Freigabe',
'thumbnail_alt' => 'Alternativtext',
'thumbnail_path' => 'Vorschaubild',
'thumbnail_source' => 'Herkunft des Vorschaubilds',
'editorial_content_kind_id' => 'Fachliche Materialart',
];
return IdentityChange::query()
->where('subject_type', $element->getMorphClass())
->where('subject_id', $element->id)
->latest('occurred_at')
->limit(8)
->get()
->map(fn (IdentityChange $change): array => [
'field' => $labels[$change->field] ?? $change->field,
'after' => is_scalar($change->after) ? (string) $change->after : '',
'when' => $change->occurred_at?->timezone(config('app.timezone'))->format('d.m.Y H:i') ?? '',
])
->all();
}
/**
* @return array<string, mixed>
*/
public function usageCard(): array
{
/** @var ContentElement $element */
$element = $this->getRecord();
return app(MediaLibrary::class)->cardFor($element, ContentElementResource::editor());
}
private function fillEditorial(): void
{
/** @var ContentElement $element */
$element = $this->getRecord();
$this->workingTitle = (string) $element->working_title;
$this->displayTitle = (string) ($element->display_title ?? '');
$this->teaser = (string) ($element->teaser ?? '');
$this->summary = (string) ($element->summary ?? '');
$this->searchTerms = (string) ($element->search_terms ?? '');
$this->descriptionText = (string) ($element->description ?? '');
$this->usageNote = (string) ($element->usage_note ?? '');
$this->licenseNote = (string) ($element->license_note ?? '');
$this->websiteCredit = (string) ($element->website_credit ?? '');
$this->websiteAlt = (string) ($element->website_alt ?? '');
$this->kindId = $element->editorial_content_kind_id;
$this->pillarIds = $element->pillars()->pluck('pillars.id')->all();
$this->dimensionIds = IdentityDimensionValue::query()
->where('subject_type', $element->getMorphClass())
->where('subject_id', $element->id)
->where('origin', 'direkt')
->pluck('editorial_dimension_value_id')
->all();
}
}