Files
laraundfelix/app/Filament/Resources/Compositions/Pages/EditComposition.php
T
LarsandClaude Opus 5.5 105d27f9c9
CI Feature / test (push) Successful in 1m2s
Deploy Test / test (push) Successful in 56s
Deploy Test / deploy (push) Successful in 26s
Halte Aufklappen an der Quelle fest und nenne die in der Bibliothek sichtbare Fassung richtig.
Aufgeklappte Module bleiben beim Verschieben aufgeklappt. Der Hinweis zur
Mitgliederbibliothek widersprach den Fassungsangaben, wenn eine ältere
Fassung sichtbar war.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 06:34:48 +01:00

2204 lines
73 KiB
PHP

<?php
namespace App\Filament\Resources\Compositions\Pages;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionDisplayRelease;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\CompositionRelease;
use App\Domain\Catalog\CompositionStructureReader;
use App\Domain\Catalog\CompositionVersion;
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\EditorialDimension;
use App\Domain\Catalog\EditorialWorkingDraft;
use App\Domain\Catalog\IdentityDimension;
use App\Domain\Catalog\IdentityDimensionValue;
use App\Domain\Catalog\IdentityProfile;
use App\Domain\Catalog\StructureNode;
use App\Domain\Cms\Catalog\PublicCatalogReader;
use App\Domain\Cms\Widgets\RenderContext;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Support\EditorialCatalog;
use App\Filament\Support\ManagesEditorialSurface;
use App\Filament\Support\MediumForm;
use App\Filament\Support\WidgetEditor;
use App\Http\Controllers\ContentPreviewController;
use App\Jobs\DeriveCompositionFrame;
use App\Jobs\DeriveThumbnail;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Enums\Width;
use Filament\Support\Exceptions\Halt;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Model;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Livewire\WithFileUploads;
abstract class EditComposition extends EditRecord
{
use ManagesEditorialSurface;
use WithFileUploads;
protected string $view = 'filament.editorial.edit';
public string $designation = '';
public string $displayTitle = '';
public string $teaser = '';
public string $summary = '';
public string $searchTerms = '';
public string $description = '';
public string $learningGoal = '';
public string $durationMinutes = '';
public string $materialNote = '';
public string $revisionNote = '';
public string $search = '';
public string $catalogScope = 'medien';
public bool $listCatalog = false;
public ?int $selected = null;
public string $roleDraft = '';
public string $noteDraft = '';
public string $imageCaptionText = '';
public ?string $thumbnailSource = null;
/** @var list<array{version_id: int, title: string, label: string, file_url: ?string}> */
public array $frameFilmChoices = [];
public string $panel = 'angaben';
public bool $textOpen = false;
public bool $releaseArmed = false;
public bool $releaseConsent = false;
public bool $returnAfterRelease = false;
public string $returnUrl = '';
public ?int $templateNumber = null;
public string $feedback = '';
public string $newTextTitle = '';
public string $newTextBody = '';
public string $partTitle = '';
public string $partBody = '';
public string $newModuleName = '';
public mixed $previewUpload = null;
public ?string $thumbnailPath = null;
public string $thumbnailAlt = '';
public ?string $thumbnailError = null;
/** Bereich des Aufbauarbeitsplatzes: aufbau, angaben oder verlauf. */
public string $aufbauTab = 'aufbau';
/** Ansicht der ausgewählten Verwendung: stelle, quelle oder vorschau. */
public string $detailTab = 'stelle';
/** @var list<string> aufgeklappte Bestandteile (Ziel der Verwendung), unabhängig von ihrer Position */
public array $expanded = [];
public string $imageMode = 'film';
public ?int $frameVersionId = null;
public string $frameSecond = '';
/** @var list<array<string, string|null>> */
public array $members = [];
/** @var list<int|string> */
public array $dimensionIds = [];
public function mount(int|string $record): void
{
parent::mount($record);
$this->loadEditor();
$this->selectFirstPart();
$this->returnUrl = $this->safeReturn(request()->query('zurueck'));
$adopt = request()->query('uebernehmen');
// Ausdrücklich gewählte Rückkehr „Zurück und einbinden“: frisch geladen, daher keine anderen offenen Eingaben.
if (is_string($adopt) && $this->includePart($adopt, true) && $this->persistDraft()) {
$title = (string) ($this->members[array_key_last($this->members)]['title'] ?? 'Der Bestandteil');
$this->feedback = $title.' ist in den Aufbau übernommen. Der Entwurf ist gespeichert; es entsteht keine neue Fassung.';
}
$flashed = session('redaktion');
if (is_string($flashed) && $flashed !== '' && $this->feedback === '') {
$this->feedback = $flashed;
}
}
public function getTitle(): string|Htmlable
{
$title = trim((string) $this->getRecord()->display_title) !== '' ? (string) $this->getRecord()->display_title : (string) $this->getRecord()->designation;
return $title !== '' ? $title : $this->hostLabel();
}
public function getMaxContentWidth(): Width|string|null
{
return Width::Full;
}
protected function mutateFormDataBeforeFill(array $data): array
{
return [];
}
protected function getHeaderActions(): array
{
return [];
}
public function displayReleaseAction(): Action
{
return Action::make('displayRelease')
->label('In Mitgliederbibliothek anzeigen')
->requiresConfirmation()
->modalHeading('In der Mitgliederbibliothek anzeigen')
->modalDescription('Sichtbar wird die zuletzt übernommene Fassung. Das ist keine Website-Veröffentlichung und kein aktives Angebot. Eine frühere Fassung bleibt unverändert. Ungespeicherte Änderungen am Aufbau sind nicht Teil dieser Freigabe.')
->visible(function (): bool {
$version = $this->currentReadyVersion();
return $version !== null && ! app(CompositionDisplayRelease::class)->isReleased($version);
})
->action(function (): void {
$this->releaseDisplay();
});
}
public function displayRevokeAction(): Action
{
return Action::make('displayRevoke')
->label('Aus Mitgliederbibliothek ausblenden')
->color('danger')
->requiresConfirmation()
->modalHeading('Aus der Mitgliederbibliothek ausblenden')
->modalDescription('Die Fassung verschwindet aus der Mitgliederbibliothek. Der fachliche Inhalt bleibt gespeichert. Website und Angebot sind davon unabhängig.')
->visible(function (): bool {
$version = $this->currentReadyVersion();
return $version !== null && app(CompositionDisplayRelease::class)->isReleased($version);
})
->action(function (): void {
$version = $this->currentReadyVersion();
$actor = $this->actor();
abort_unless($version !== null && $actor instanceof User, 403);
app(CompositionDisplayRelease::class)->revoke($version, $actor);
$this->feedback = 'Die Fassung ist aus der Mitgliederbibliothek ausgeblendet. Der Inhalt bleibt gespeichert.';
});
}
public function isInLibrary(): bool
{
$version = $this->currentReadyVersion();
return $version !== null && app(CompositionDisplayRelease::class)->isReleased($version);
}
public function hostKind(): CompositionKind
{
/** @var Composition $composition */
$composition = $this->getRecord();
$kind = $composition->kind;
return $kind instanceof CompositionKind ? $kind : CompositionKind::from((string) $kind);
}
public function hostLabel(): string
{
return $this->hostKind()->deskLabel();
}
public function isProgram(): bool
{
return $this->hostKind() === CompositionKind::Kurs;
}
public function selfUrl(): string
{
return $this->safeReturn(static::getResource()::getUrl('edit', ['record' => $this->getRecord()]));
}
public function previewUrl(): ?string
{
/** @var Composition $composition */
$composition = $this->getRecord();
if (is_array($composition->working_draft) && $composition->working_draft !== []) {
return route('editorial.draft-preview', ['composition' => $composition]);
}
$version = $this->currentReadyVersion();
if ($version === null) {
return null;
}
return route('editorial.preview', ['composition' => $composition, 'version' => $version]);
}
public function previewUrlFor(int $versionId): ?string
{
$version = $this->ownedVersion($versionId);
if ($version === null || $version->status !== ContentVersionStatus::Bereit) {
return null;
}
return route('editorial.preview', ['composition' => $this->getRecord(), 'version' => $version]);
}
/**
* @return list<array<string, string|null>>
*/
public function hits(): array
{
if (trim($this->search) === '' && ! $this->listCatalog) {
return [];
}
return app(EditorialCatalog::class)->search(
$this->search,
$this->catalogScope,
(int) $this->getRecord()->getKey(),
);
}
public function openPicker(): void
{
$this->commitRoleDraft();
$this->textOpen = false;
$this->resetPicker('aufbau');
$this->pickerKind = 'alle';
}
/**
* Schließt die Dialoge des Aufbaus, ohne deren offene Eingaben zu verwerfen.
*/
protected function redaktionWillOpen(): void
{
$this->commitRoleDraft();
$this->textOpen = false;
$this->releaseArmed = false;
}
protected function saveRedaktionTexte(): bool
{
$this->guardEditorial();
if (trim($this->designation) === '') {
$this->deskFeedback = 'Der Name fehlt. Er bezeichnet den Eintrag in der Verwaltung.';
$this->redaktionFehlerFeld = 'designation';
return false;
}
return $this->persistRedaktion();
}
protected function redaktionSavedMessage(): string
{
$this->feedback = 'Die Redaktion ist gespeichert. Aufbau, Lernziel, Zeit und Fassungen bleiben unverändert.';
return $this->feedback;
}
protected function resetRedaktionTexte(): void
{
$this->fillRedaktion();
}
/**
* @return array{art: string, fuer: string, liste: string, zurueck: string, typ: ?string, umfang: string}
*/
public function redaktionKopf(): array
{
$program = $this->isProgram();
return [
'art' => $this->hostLabel(),
'fuer' => $program ? 'das Programm' : 'das Modul',
'liste' => $program ? 'Programme' : 'Module',
'zurueck' => 'Zurück zum Aufbau',
'typ' => null,
'umfang' => '„Redaktion speichern“ sichert Name, Texte, Präsentationsmedien und Einordnung. Aufbau, Lernziel, Zeit und Fassungen bleiben unverändert; offene Änderungen am Aufbau bleiben offen.',
];
}
public function redaktionTitel(): string
{
$title = trim($this->displayTitle) !== '' ? trim($this->displayTitle) : trim($this->designation);
return $title !== '' ? $title : $this->hostLabel();
}
/**
* @return list<array<string, mixed>>
*/
public function redaktionFelder(): array
{
/** @var Composition $record */
$record = $this->getRecord();
$stored = fn (string $column): string => (string) ($record->getAttribute($column) ?? '');
return [
['id' => 'name', 'label' => 'Name in der Verwaltung', 'model' => 'designation', 'kind' => 'text', 'stored' => $stored('designation'), 'required' => true, 'hilfe' => 'Pflichtangabe. Erscheint in Listen der Verwaltung.'],
['id' => 'titel', 'label' => 'Titel', 'model' => 'displayTitle', 'kind' => 'text', 'stored' => $stored('display_title'), 'hilfe' => 'Erscheint auf Karten und in der Bibliothek. Leer zeigt den Namen.'],
['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')],
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'description', 'kind' => 'textarea', 'rows' => 8, 'stored' => $stored('description'), 'hilfe' => 'Beschreibt das Angebot. Kein Lehrtext und kein Lernziel.'],
['id' => 'suche', 'label' => 'Suchbegriffe', 'model' => 'searchTerms', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('search_terms'), 'placeholder' => 'Begriffe, durch Komma getrennt'],
];
}
public function redaktionTexteHinweis(): string
{
return 'Lernziel, Zeit und Material gehören zum fachlichen Stand. Sie stehen im Aufbau unter „Didaktik und Katalogbild“ und entstehen mit der nächsten Fassung.';
}
/**
* @return list<array{legend: string, model: string, values: list<array{id: int, label: string}>}>
*/
public function einordnungGruppen(): array
{
return array_map(fn (array $group): array => [
'legend' => $group['label'],
'model' => 'dimensionIds',
'values' => $group['values'],
], $this->dimensionGroups());
}
/**
* @return array{html: string, stand: string}|null
*/
public function redaktionAusgabe(): ?array
{
$subject = app(PublicCatalogReader::class)->subject($this->getRecord()->getKey(), true);
if ($subject === null) {
return null;
}
$card = view('widgets.premium_card', [
'subject' => $subject,
'context' => RenderContext::preview(),
'cardStyle' => $subject->style ?? 'program',
'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' => false,
])->render();
return [
'html' => view('filament.cms.widget-live-preview', [
'html' => $card,
'stylesheets' => WidgetEditor::previewStylesheets(),
'width' => 640,
'bodyClass' => '',
'caption' => 'Website-Karte bei 640 px, wie im öffentlichen Auftritt.',
])->render(),
'stand' => $this->redaktionOffen()
? 'Gezeigt wird der gespeicherte Stand. Deine ungespeicherten Änderungen erscheinen erst nach „Redaktion speichern“.'
: 'Gezeigt wird der gespeicherte Stand der Redaktion.',
];
}
protected function pickerExceptId(): int
{
return (int) $this->getRecord()->getKey();
}
public function einordnungUnsaved(): bool
{
/** @var Composition $record */
$record = $this->getRecord()->fresh() ?? $this->getRecord();
$stored = IdentityDimensionValue::query()
->where('subject_type', $record->getMorphClass())
->where('subject_id', $record->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;
}
public function openText(): void
{
$this->feedback = '';
$this->pickerOpen = false;
$this->textOpen = true;
}
public function cancelText(): void
{
$this->textOpen = false;
$this->newTextTitle = '';
$this->newTextBody = '';
}
public function saveDraft(): void
{
$this->commitRoleDraft();
$minutes = $this->minutes($this->durationMinutes);
if ($minutes === false) {
$this->feedback = 'Der Zeitbedarf ist eine Zahl von Minuten oder bleibt leer.';
return;
}
/** @var Composition $record */
$record = $this->getRecord();
app(EditorialWorkingDraft::class)->write($record, $this->payload());
$this->feedback = 'Der Entwurf ist gespeichert. Es entsteht keine neue Fassung.';
}
public function armRelease(): void
{
$this->commitRoleDraft();
if ($this->members === []) {
$this->releaseArmed = false;
$this->feedback = 'Eine Fassung braucht mindestens einen Bestandteil. Anzeige und Entwurf kannst du schon speichern.';
return;
}
if (! $this->needsRevision()) {
$this->releaseArmed = false;
$this->feedback = 'Die freigegebene Fassung ist unverändert. Es entsteht keine neue Fassung.';
return;
}
$this->releaseConsent = false;
$this->releaseArmed = true;
}
public function cancelRelease(): void
{
$this->releaseArmed = false;
$this->releaseConsent = false;
$this->returnAfterRelease = false;
}
/**
* @return array<string, mixed>
*/
public function releaseReview(): array
{
/** @var Composition $composition */
$composition = $this->getRecord();
$review = app(CompositionRelease::class)->review($composition, $this->members);
foreach ($review['blocked'] as $index => $item) {
$review['blocked'][$index]['edit_url'] = $this->releaseEditUrl($item['edit'] ?? null);
}
return $review;
}
public function releaseFollowUp(): string
{
$version = $this->currentReadyVersion();
if ($version === null) {
return '';
}
/** @var Composition $composition */
$composition = $this->getRecord();
$releases = app(CompositionDisplayRelease::class);
$shown = $releases->highestReleasedVersion($composition);
$library = match (true) {
$releases->isReleased($version) => 'In der Mitgliederbibliothek ist Fassung '.$version->number.' sichtbar.',
$shown !== null => 'In der Mitgliederbibliothek ist Fassung '.$shown->number.' sichtbar, die neuere Fassung '.$version->number.' noch nicht. „In Mitgliederbibliothek anzeigen“ zeigt Fassung '.$version->number.'. Das veröffentlicht weder die Website noch ein Angebot.',
default => 'In der Mitgliederbibliothek ist noch keine Fassung sichtbar. „In Mitgliederbibliothek anzeigen“ wählt die letzte freigegebene Fassung. Das veröffentlicht weder die Website noch ein Angebot.',
};
$draft = is_array($composition->working_draft) && $composition->working_draft !== []
? ' Es gibt einen gespeicherten Entwurf neben der freigegebenen Fassung.'
: ' Es gibt keinen offenen Entwurf. Änderungen hältst du mit „Entwurf speichern“ fest.';
return $library.$draft;
}
protected function selectFirstPart(): void
{
if ($this->members !== [] && ($this->selected === null || ! isset($this->members[$this->selected]))) {
$this->selected = 0;
$this->syncRoleDraft();
}
}
public function discardDraft(): void
{
/** @var Composition $record */
$record = $this->getRecord();
app(EditorialWorkingDraft::class)->clear($record);
$this->releaseArmed = false;
$this->loadAufbau();
$this->selected = null;
$this->selectFirstPart();
$this->feedback = 'Der Entwurf ist verworfen. Eine freigegebene Fassung bleibt unverändert. Offene Eingaben der Redaktion bleiben erhalten.';
}
public function editorStatus(): string
{
$current = $this->fingerprint($this->payload());
$stored = $this->storedPayload();
$ready = $this->fingerprint($this->readyPayload());
$version = $this->currentReadyVersion();
$display = $version === null
? ''
: (app(CompositionDisplayRelease::class)->isReleased($version)
? ' Sie ist in der Mitgliederbibliothek sichtbar.'
: ' Sie ist nicht in der Mitgliederbibliothek.');
$unsaved = $stored === null
? $current !== $ready
: $current !== $this->fingerprint($stored);
if ($unsaved) {
return 'Es gibt ungespeicherte Änderungen. Speichern hält den Entwurf fest und legt keine Fassung an.';
}
if ($stored !== null && $this->fingerprint($stored) !== $ready) {
return $version === null
? 'Der Entwurf ist gespeichert. Noch keine freigegebene Fassung.'
: 'Der Entwurf ist gespeichert. Fassung '.$version->number.' bleibt unverändert.'.$display;
}
if ($version === null) {
return 'Noch keine freigegebene Fassung. Speichern hält einen Entwurf fest.';
}
return 'Fassung '.$version->number.' ist der letzte freigegebene Stand.'.$display.' Kein offener Entwurf.';
}
public function includeNeedsRelease(): bool
{
return $this->needsRevision();
}
public function moveTo(int $from, int $to): void
{
$this->commitRoleDraft();
$count = count($this->members);
if (! isset($this->members[$from]) || $to < 0 || $to >= $count) {
$this->feedback = 'An dieser Stelle kann der Bestandteil nicht abgelegt werden. Die Reihenfolge gilt nur innerhalb dieses Aufbaus.';
return;
}
if ($from === $to) {
$this->feedback = 'Der Bestandteil bleibt an seiner Stelle.';
return;
}
$selectedTarget = $this->selected !== null ? ($this->members[$this->selected]['target'] ?? null) : null;
$item = $this->members[$from];
array_splice($this->members, $from, 1);
array_splice($this->members, $to, 0, [$item]);
$this->members = array_values($this->members);
$this->selected = null;
foreach ($this->members as $index => $member) {
if ($selectedTarget !== null && ($member['target'] ?? null) === $selectedTarget) {
$this->selected = $index;
break;
}
}
$this->syncRoleDraft();
$this->feedback = $item['title'].' steht jetzt an Stelle '.($to + 1).'. Gespeichert ist das erst mit „Entwurf speichern“.';
}
/**
* @return list<array{id: int, number: int, text: string, current: bool}>
*/
public function versionChoices(): array
{
/** @var Composition $composition */
$composition = $this->getRecord();
$release = app(CompositionDisplayRelease::class);
$latest = $this->currentReadyVersion();
$rows = [];
foreach ($composition->versions()->orderByDesc('number')->get() as $version) {
if ($version->status !== ContentVersionStatus::Bereit) {
continue;
}
$released = $release->isReleased($version);
$rows[] = [
'id' => $version->id,
'number' => $version->number,
'text' => 'Fassung '.$version->number.($released ? ', in der Mitgliederbibliothek' : ', nicht in der Mitgliederbibliothek'),
'current' => $latest !== null && $latest->id === $version->id,
];
}
return $rows;
}
/**
* @return list<string>
*/
public function usageLines(): array
{
$version = $this->currentReadyVersion();
if ($version === null) {
return [];
}
return app(EditorialCatalog::class)->usage($version);
}
/**
* @return list<array{label: string, values: list<array{id: int, label: string}>}>
*/
public function dimensionGroups(): array
{
$groups = [];
foreach (EditorialDimension::forSubject($this->getRecord()) as $dimension) {
$values = [];
foreach ($dimension->values as $value) {
$values[] = ['id' => $value->id, 'label' => $value->label];
}
if ($values !== []) {
$groups[] = ['label' => $dimension->label, 'values' => $values];
}
}
return $groups;
}
/**
* @return list<array{target: string, label: string}>
*/
public function selectedAlternatives(): array
{
$member = $this->selectedMember();
if ($member === null) {
return [];
}
return app(EditorialCatalog::class)->alternatives(
(string) ($member['identity'] ?? ''),
(int) $this->getRecord()->getKey(),
);
}
public function childrenOf(string $target): string
{
if (preg_match('/^composition-draft:(\d+)$/', $target, $match) === 1) {
$composition = Composition::query()->find($match[1]);
$draft = $composition instanceof Composition && is_array($composition->working_draft) ? $composition->working_draft : [];
$lines = [];
foreach ($draft['members'] ?? [] as $member) {
if (! is_array($member)) {
continue;
}
$row = app(EditorialCatalog::class)->rowForTarget((string) ($member['target'] ?? ''), (int) $this->getRecord()->getKey(), allowSelf: true, allowDraft: true, allowBlocked: true);
$lines[] = trim((string) ($member['role'] ?? '')).': '.($row['title'] ?? 'Bestandteil');
}
return implode(' · ', $lines);
}
if (preg_match('/^composition:(\d+)$/', $target, $match) !== 1) {
return '';
}
$version = CompositionVersion::query()->find($match[1]);
if (! $version instanceof CompositionVersion) {
return '';
}
$lines = [];
$this->childLines(app(CompositionStructureReader::class)->tree($version), $lines);
return implode(' · ', $lines);
}
/**
* @param list<StructureNode> $nodes
* @param list<string> $lines
*/
protected function childLines(array $nodes, array &$lines): void
{
foreach ($nodes as $node) {
$lines[] = $node->role.': '.$node->title;
$this->childLines($node->children, $lines);
}
}
public function publishHint(): string
{
if ($this->members === []) {
return 'Eine Fassung braucht mindestens einen Bestandteil. Anzeige und Kurzbeschreibung kannst du schon speichern. Ein Film ist dafür nicht nötig.';
}
if (! $this->needsRevision()) {
return 'Lernziel, Zeit, Material und Aufbau sind unverändert. Es entsteht keine neue Fassung.';
}
return 'Freigeben legt eine neue unveränderliche Fassung an. Speichern schreibt nur den Entwurf und lässt freigegebene Fassungen unverändert.';
}
public function selectPart(int $index): void
{
if (! isset($this->members[$index])) {
return;
}
$this->commitRoleDraft();
$this->selected = $index;
$this->panel = 'bestandteil';
$this->aufbauTab = 'aufbau';
$this->syncRoleDraft();
}
/**
* Früherer Einstieg „Bestandteil bearbeiten“: wählt die Verwendung im Detailbereich.
*/
public function openPart(int $index): void
{
$this->selectPart($index);
$this->detailTab = 'stelle';
}
public function toggleExpanded(int $index): void
{
$target = (string) ($this->members[$index]['target'] ?? '');
if ($target === '') {
return;
}
$this->expanded = in_array($target, $this->expanded, true)
? array_values(array_diff($this->expanded, [$target]))
: [...$this->expanded, $target];
}
public function showAufbauTab(string $tab): void
{
$this->commitRoleDraft();
if (in_array($tab, ['aufbau', 'angaben', 'verlauf'], true)) {
$this->aufbauTab = $tab;
}
}
public function updatedNoteDraft(): void
{
$this->commitRoleDraft();
}
public function updatedMembers(): void
{
$this->syncRoleDraft();
}
/**
* Inhalt der referenzierten Komposition zur Ansicht (eine Ebene).
*
* @return list<array{title: string, kind: string, image: ?string, tone: string, role: string}>
*/
public function childrenRows(string $target): array
{
$catalog = app(EditorialCatalog::class);
$exceptId = (int) $this->getRecord()->getKey();
$rows = [];
if (preg_match('/^composition-draft:(\d+)$/', $target, $match) === 1) {
$composition = Composition::query()->find($match[1]);
$draft = $composition instanceof Composition && is_array($composition->working_draft) ? $composition->working_draft : [];
foreach ($draft['members'] ?? [] as $member) {
if (! is_array($member)) {
continue;
}
$row = $catalog->rowForTarget((string) ($member['target'] ?? ''), $exceptId, allowSelf: true, allowDraft: true, allowBlocked: true);
$rows[] = [
'title' => (string) ($row['title'] ?? 'Bestandteil'),
'kind' => (string) ($row['kind'] ?? ''),
'image' => $row['image'] ?? null,
'tone' => (string) ($row['tone'] ?? 'text'),
'role' => trim((string) ($member['role'] ?? '')),
];
}
return $rows;
}
if (preg_match('/^composition:(\d+)$/', $target, $match) !== 1) {
return [];
}
$version = CompositionVersion::query()->find($match[1]);
if (! $version instanceof CompositionVersion) {
return [];
}
foreach (app(CompositionStructureReader::class)->tree($version) as $node) {
$childTarget = $node->contentElementVersionId !== null
? 'element:'.$node->contentElementVersionId
: ($node->compositionVersionId !== null ? 'composition:'.$node->compositionVersionId : '');
$row = $childTarget !== '' ? $catalog->rowForTarget($childTarget, $exceptId, allowSelf: true, allowDraft: true, allowBlocked: true) : null;
$rows[] = [
'title' => $node->title,
'kind' => (string) ($row['kind'] ?? $node->editorialKindLabel ?? $node->technicalKindLabel ?? ''),
'image' => $row['image'] ?? null,
'tone' => (string) ($row['tone'] ?? 'text'),
'role' => $node->role,
];
}
return $rows;
}
public function addPart(string $target): void
{
$this->includePart($target, true);
}
private function includePart(string $target, bool $allowDraft): bool
{
if (preg_match('/^(element:\d+|composition:\d+|composition-draft:\d+)$/', $target) !== 1) {
$this->feedback = 'Dieser Bestandteil ist nicht verfügbar.';
return false;
}
foreach ($this->members as $index => $member) {
if (($member['target'] ?? '') === $target) {
$this->selected = $index;
$this->panel = 'bestandteil';
$this->feedback = 'Diese Fassung ist schon enthalten.';
return false;
}
}
$row = app(EditorialCatalog::class)->rowForTarget($target, (int) $this->getRecord()->getKey(), allowDraft: $allowDraft);
if ($row === null) {
$this->feedback = 'Diese Fassung ist nicht bereit oder gehört zu diesem Eintrag.';
return false;
}
$row['role'] = app(EditorialCatalog::class)->defaultRole((string) $row['kind']);
$row['note'] = '';
$this->members[] = $row;
$this->members = array_values($this->members);
$this->selected = array_key_last($this->members);
$this->panel = 'bestandteil';
$this->syncRoleDraft();
$this->search = '';
$this->pickerOpen = false;
$this->pickerSelected = '';
$this->detailTab = 'stelle';
$this->feedback = $row['title'].' steht jetzt an Stelle '.count($this->members).' im Aufbau. Es wird nur verwiesen, nichts kopiert. Gespeichert wird mit „Entwurf speichern“.';
return true;
}
public function removePart(int $index): void
{
if (! isset($this->members[$index])) {
return;
}
$title = (string) ($this->members[$index]['title'] ?? 'Der Bestandteil');
unset($this->members[$index]);
$this->members = array_values($this->members);
$this->selected = $this->members === [] ? null : min($index, count($this->members) - 1);
$this->syncRoleDraft();
$this->feedback = '„'.$title.'“ ist aus diesem Aufbau genommen. Das Quellobjekt bleibt im Bestand. Gespeichert ist das erst mit „Entwurf speichern“; eine freigegebene Fassung bleibt unverändert.';
}
/**
* @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
{
if ($aktion !== 'removePart' || ! isset($this->members[(int) $argument])) {
return null;
}
$title = (string) ($this->members[(int) $argument]['title'] ?? 'Bestandteil');
return [
'aktion' => $aktion,
'argument' => (int) $argument,
'titel' => '„'.$title.'“ aus diesem Aufbau entfernen?',
'text' => 'Nur diese Verwendung wird entfernt. Das Medium oder Modul bleibt im Bestand und in anderen Aufbauten. Gespeichert wird das mit „Entwurf speichern“.',
'label' => 'Aus dem Aufbau entfernen',
'gefahr' => true,
];
}
protected function runExtraConfirmation(string $aktion, int|string|null $argument): void
{
if ($aktion === 'removePart') {
$this->removePart((int) $argument);
}
}
public function movePart(int $index, int $direction): void
{
$this->commitRoleDraft();
$target = $index + $direction;
if (! isset($this->members[$index], $this->members[$target])) {
return;
}
$current = $this->members[$index];
$this->members[$index] = $this->members[$target];
$this->members[$target] = $current;
$this->members = array_values($this->members);
$this->selected = $target;
$this->syncRoleDraft();
}
public function useVersion(int $index, string $target): void
{
if (! isset($this->members[$index])) {
return;
}
$row = app(EditorialCatalog::class)->rowForTarget($target, (int) $this->getRecord()->getKey(), allowSelf: true);
if ($row === null || ($row['identity'] ?? '') !== ($this->members[$index]['identity'] ?? '')) {
$this->feedback = 'Diese Fassung passt nicht zu dem ausgewählten Bestandteil.';
return;
}
$this->commitRoleDraft();
$row['role'] = $this->members[$index]['role'] ?? $row['kind'];
$row['note'] = $this->members[$index]['note'] ?? '';
$this->members[$index] = $row;
$this->syncRoleDraft();
$this->feedback = $row['version_label'].' ist für diese Stelle ausgewählt. Der Entwurf speichert das. Eine freigegebene Fassung bleibt unverändert.';
}
public function loadTemplate(int $versionId): void
{
$version = $this->ownedVersion($versionId);
if ($version === null || $version->status !== ContentVersionStatus::Bereit) {
$this->feedback = 'Diese Fassung kann nicht als Vorlage geladen werden.';
return;
}
$this->applyVersion($version);
$this->templateNumber = $version->number;
$this->feedback = 'Fassung '.$version->number.' ist als Arbeitsstand geladen. Die geladene Fassung bleibt unverändert.';
}
public function addText(): void
{
$title = trim($this->newTextTitle);
$body = trim($this->newTextBody);
if ($title === '' || $body === '') {
$this->feedback = 'Der Text braucht einen Titel und einen Inhalt.';
return;
}
try {
$service = app(ContentService::class);
$element = $service->createElement('text', 'text', $title);
$version = $service->draftElementVersion($element, $body);
} catch (DomainRuleException $exception) {
$this->feedback = $exception->getMessage();
return;
}
$this->newTextTitle = '';
$this->newTextBody = '';
$this->textOpen = false;
if (! $this->includePart('element:'.$version->id, true)) {
return;
}
$this->feedback = $title.' ist angelegt und in den Aufbau übernommen. Der Text bleibt bearbeitbar, solange diese Fassung nicht freigegeben und verwendet wird. Es entsteht keine neue Fassung dieses Eintrags.';
}
/**
* Schließt erst den Picker und öffnet danach den Dialog, damit beide nicht übereinander liegen.
*/
public function startCreateMedium(): void
{
$this->closePicker();
$this->js("\$wire.mountAction('createMedium')");
}
private function revealMediumForm(): void
{
$this->pickerOpen = false;
$this->textOpen = false;
}
public function createMediumAction(): Action
{
return Action::make('createMedium')
->label('Medium anlegen')
->modalHeading('Medium anlegen')
->modalDescription('Dieselbe Maske gilt im Medienbestand, im Modul und im Programm. Der Upload zeigt seinen Fortschritt. Beschreibung, Hinweise und Vorschaubild trägst du danach in dieser Maske ein.')
->modalSubmitActionLabel('Anlegen und übernehmen')
->modalWidth(Width::Large)
->beforeFormFilled(fn () => $this->revealMediumForm())
->schema(fn (): array => MediumForm::fields(creating: true))
->action(function (array $data): void {
try {
$element = MediumForm::create($data, hold: true);
} catch (DomainRuleException $exception) {
Notification::make()->title($exception->getMessage())->danger()->send();
throw new Halt;
}
$version = $element->versions()->orderByDesc('number')->first();
if (! $version instanceof ContentElementVersion || ! $this->includePart('element:'.$version->id, true)) {
return;
}
$this->feedback = $element->working_title.' ist angelegt und in den Aufbau übernommen. Die Datei liegt bei den Medien. Beschreibung und Vorschaubild sind gespeichert.';
});
}
public function startModule(): void
{
$name = trim($this->newModuleName);
if ($name === '') {
$this->feedback = 'Das neue Modul braucht einen Namen.';
return;
}
$composition = app(EditorialCatalog::class)->create($name, CompositionKind::Uebung);
$this->newModuleName = '';
$url = EditorialCatalog::editUrl($composition).'?zurueck='.urlencode($this->selfUrl());
$this->redirect($url, navigate: false);
}
public function saveDisplay(): void
{
if (! $this->persistRedaktion()) {
return;
}
$this->feedback = 'Die Anzeige ist gespeichert. Die Fassung bleibt unverändert.';
}
/**
* Früherer Dialog „Didaktik und Katalogbild“: öffnet den Bereich „Angaben“.
*/
public function openModule(): void
{
$this->commitRoleDraft();
$this->aufbauTab = 'angaben';
$this->frameFilmChoices = $this->frameFilms();
if ($this->frameFilmChoices !== [] && $this->frameVersionId === null) {
$this->frameVersionId = $this->frameFilmChoices[0]['version_id'];
}
if ($this->frameFilmChoices === [] && $this->imageMode === 'film') {
$this->imageMode = 'upload';
}
}
public function openCatalogImagePicker(): void
{
$this->guardEditorial();
$this->resetPicker('vorschaubild');
$this->pickerKind = 'bild';
}
protected function adoptThumbnailFromPicker(string $target): void
{
$elementId = $this->elementIdOf($target);
if ($elementId !== null) {
$this->adoptPicture($elementId);
}
}
/**
* Übernimmt Alternativtext und gewähltes Katalogbild (Filmstelle oder Upload) sofort.
* Didaktik und Aufbau speichert „Entwurf speichern“; Texte und Einordnung die Redaktion.
*/
public function saveCatalogImage(): void
{
/** @var Composition $record */
$record = $this->getRecord();
app(IdentityProfile::class)->fill($record, ['thumbnail_alt' => trim($this->thumbnailAlt)], $this->actor());
$record->refresh();
$image = $this->applyChosenImage();
if ($image === false) {
return;
}
$this->previewUpload = null;
$this->feedback = trim('Das Katalogbild ist übernommen. Es entsteht keine neue Fassung.'.($image === '' ? '' : ' '.$image));
}
/**
* Speichert den Wortlaut eines Textbausteins an seiner Quelle. Wird die Fassung schon verwendet, entsteht eine neue
* Fassung; der Aufbau verweist dann im Arbeitsstand darauf und speichert das mit „Entwurf speichern“.
*/
public function saveSourceText(): void
{
$this->commitRoleDraft();
$note = $this->writePartText();
if ($note === false || $note === '') {
if ($note === '') {
$this->feedback = 'Der Text ist unverändert.';
}
return;
}
$this->syncRoleDraft();
$this->feedback = $note.' Die Zuordnung im Aufbau speichert „Entwurf speichern“.';
}
/**
* @return list<array{version_id: int, title: string, label: string, file_url: ?string}>
*/
public function frameFilms(): array
{
$preview = app(ContentPreviewController::class);
$films = [];
foreach ($this->members as $member) {
if (preg_match('/^element:(\d+)$/', (string) ($member['target'] ?? ''), $match) !== 1) {
continue;
}
$version = ContentElementVersion::query()->with('element')->find($match[1]);
if (! $version instanceof ContentElementVersion || $version->element?->output_class !== 'film') {
continue;
}
$films[] = [
'version_id' => $version->id,
'title' => (string) ($member['title'] ?? $version->element->working_title),
'label' => 'Fassung '.$version->number,
'file_url' => $preview->fileUrl($version),
];
}
return $films;
}
public function framePreviewUrl(): ?string
{
if ($this->frameVersionId === null || ! is_numeric($this->frameSecond) || trim($this->frameSecond) === '') {
return null;
}
return route('editorial.frame', [
'version' => $this->frameVersionId,
'sekunde' => $this->frameSecond,
]);
}
public function imageCaption(): ?string
{
return $this->imageCaptionText !== '' ? $this->imageCaptionText : null;
}
protected function captionFor(mixed $source): string
{
if (! is_string($source) || $source === '') {
return '';
}
if (preg_match('/^frame:(\d+)@([\d.]+)$/', $source, $match) === 1) {
$title = null;
foreach ($this->members as $member) {
if (($member['target'] ?? '') === 'element:'.$match[1]) {
$title = $member['title'] ?? null;
break;
}
}
if ($title === null) {
$version = ContentElementVersion::query()->with('element')->find($match[1]);
$title = $version?->element?->working_title;
}
return 'Titelbild aus '.($title ?: 'dem Film').' bei '.$match[2].' Sekunden.';
}
if ($source === 'eigen') {
return 'Eigenes Titelbild.';
}
if (str_starts_with($source, 'element:')) {
return 'Titelbild aus einem vorhandenen Bild.';
}
return '';
}
protected function rememberCaption(Composition $record): void
{
$this->thumbnailSource = $record->thumbnail_source;
$this->imageCaptionText = $this->captionFor($record->thumbnail_source);
}
public function savePreview(): void
{
if (! $this->previewUpload instanceof TemporaryUploadedFile) {
$this->feedback = 'Wähle zuerst eine Bilddatei.';
return;
}
$extension = strtolower($this->previewUpload->getClientOriginalExtension());
if (! in_array($extension, ['png', 'jpg', 'jpeg', 'webp'], true)) {
$this->feedback = '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->feedback = 'Das Vorschaubild wurde nicht übernommen.';
return;
}
$this->storePreview($path);
}
public function savePreviewImage(string $storedPath): void
{
$this->storePreview($storedPath);
}
public function adoptPicture(int $elementId): void
{
$element = ContentElement::query()->find($elementId);
$path = $element?->thumbnail_path;
if (! $element instanceof ContentElement || ! is_string($path) || ! str_starts_with($path, 'vorschau/') || str_contains($path, '..')) {
$this->feedback = 'Für dieses Medium liegt noch kein Vorschaubild vor.';
return;
}
/** @var Composition $record */
$record = $this->getRecord();
$before = $record->versions()->count();
DeriveThumbnail::dispatch('komposition', $record->id, null, $element->id);
$record->refresh();
$this->thumbnailPath = $record->thumbnail_path;
$this->thumbnailError = $record->thumbnail_error;
$this->rememberCaption($record);
$this->feedback = $this->previewFeedback($record, $before);
}
private function writePartText(): string|false
{
$index = $this->selected;
$member = $this->selectedMember();
if ($index === null || $member === null || ($member['output'] ?? '') !== 'text') {
return '';
}
$title = trim($this->partTitle);
$body = trim($this->partBody);
if ($title === '' || $body === '') {
$this->feedback = 'Der Text braucht einen Titel und einen Inhalt.';
return false;
}
if (preg_match('/^element:(\d+)$/', (string) ($member['target'] ?? ''), $match) !== 1) {
return '';
}
$version = ContentElementVersion::query()->with('element')->find($match[1]);
if (! $version instanceof ContentElementVersion || $version->element === null) {
$this->feedback = 'Dieser Text ist nicht mehr vorhanden.';
return false;
}
$changed = $title !== (string) ($member['title'] ?? '') || $body !== trim((string) $version->body);
if (! $changed) {
return '';
}
try {
$service = app(ContentService::class);
$service->describe($version->element, $title, $version->element->description);
$updated = $service->reviseElementContent($version, $body);
} catch (DomainRuleException $exception) {
$this->feedback = $exception->getMessage();
return false;
}
if ($updated->id === $version->id) {
$this->members[$index]['title'] = $title;
$this->members[$index]['body'] = $body;
return 'Der Text ist in derselben Fassung geändert. Eine neue Fassung entsteht, sobald diese Fassung freigegeben und verwendet wird.';
}
$row = app(EditorialCatalog::class)->rowForTarget(
'element:'.$updated->id,
(int) $this->getRecord()->getKey(),
allowSelf: true,
allowDraft: true,
);
if ($row === null) {
$this->feedback = 'Die neue Fassung ließ sich nicht in den Aufbau übernehmen.';
return false;
}
$row['role'] = (string) ($this->members[$index]['role'] ?? $row['kind']);
$row['note'] = (string) ($this->members[$index]['note'] ?? '');
$this->members[$index] = $row;
return 'Die Änderung liegt in einer neuen Fassung. Die bisherige Fassung bleibt in den freigegebenen Aufbauten.';
}
/**
* @param array{type: string, id: int}|null $edit
*/
private function releaseEditUrl(?array $edit): ?string
{
if ($edit === null) {
return null;
}
if ($edit['type'] === 'element') {
$element = ContentElement::query()->find($edit['id']);
return $element instanceof ContentElement
? ContentElementResource::getUrl('view', ['record' => $element])
: null;
}
$composition = Composition::query()->find($edit['id']);
return $composition instanceof Composition ? EditorialCatalog::editUrl($composition) : null;
}
/**
* @return array{url: ?string, note: ?string, own: bool}
*/
public function coverPicture(): array
{
/** @var Composition $composition */
$composition = $this->getRecord();
return app(EditorialCatalog::class)->cover($composition, $this->members);
}
/**
* @return list<array{id: int, title: string, image: string}>
*/
public function filmChoices(): array
{
$films = app(EditorialCatalog::class)->filmPictures($this->members);
return count($films) > 1 ? $films : [];
}
/**
* @return array{id: int, title: string, image: string}|null
*/
public function suggestedFilm(): ?array
{
if (filled($this->thumbnailPath)) {
return null;
}
$films = app(EditorialCatalog::class)->filmPictures($this->members);
return count($films) === 1 ? $films[0] : null;
}
/**
* @return list<array{label: string, tone: string}>
*/
public function presentationChips(): array
{
/** @var Composition $composition */
$composition = $this->getRecord();
$offered = in_array($composition->id, app(EditorialCatalog::class)->offeredCompositionIds(), true);
return app(EditorialCatalog::class)->statusChips($composition, $offered);
}
public function publishRevision(): bool
{
$this->commitRoleDraft();
if ($this->members === []) {
$this->feedback = 'Eine Fassung braucht mindestens einen Bestandteil. Anzeige und Kurzbeschreibung kannst du schon speichern.';
return false;
}
if (! $this->needsRevision()) {
/** @var Composition $unchanged */
$unchanged = $this->getRecord();
app(EditorialWorkingDraft::class)->clear($unchanged);
$this->releaseArmed = false;
$this->feedback = 'Die freigegebene Fassung ist unverändert. Es entsteht keine neue Fassung.';
return false;
}
$minutes = $this->minutes($this->durationMinutes);
if ($minutes === false) {
$this->feedback = 'Der Zeitbedarf ist eine Zahl von Minuten oder bleibt leer.';
return false;
}
/** @var Composition $record */
$record = $this->getRecord();
$note = trim($this->revisionNote);
try {
app(CompositionRelease::class)->publish(
$record,
$this->members,
$this->actor(),
$note !== '' ? $note : null,
[
'learning_goal' => $this->blank($this->learningGoal),
'duration_minutes' => $minutes,
'material_note' => $this->blank($this->materialNote),
],
$this->releaseConsent,
);
} catch (DomainRuleException $exception) {
$this->feedback = $exception->getMessage();
$this->releaseArmed = true;
return false;
}
$this->revisionNote = '';
$this->templateNumber = null;
$this->releaseArmed = false;
$this->releaseConsent = false;
app(EditorialWorkingDraft::class)->clear($record);
$this->loadEditor();
$released = $this->currentReadyVersion();
$number = $released instanceof CompositionVersion ? $released->number : '';
$this->feedback = 'Fassung '.$number.' ist freigegeben. Der Entwurf ist geschlossen und die bisherige Fassung bleibt erhalten. Die Mitgliederbibliothek ändert sich dadurch nicht.';
if ($this->returnAfterRelease) {
$this->returnAfterRelease = false;
$this->finishReturn();
}
return true;
}
public function returnAndInclude(): void
{
if ($this->returnUrl === '') {
return;
}
if ($this->needsRevision()) {
$this->returnAfterRelease = true;
$this->armRelease();
return;
}
$this->finishReturn();
}
private function finishReturn(): void
{
$version = $this->currentReadyVersion();
$url = $this->returnUrl;
if ($version === null) {
session()->flash('redaktion', 'Es gibt noch keine Fassung, deshalb wurde nichts eingebunden.');
$this->redirect($url, navigate: false);
return;
}
$join = str_contains($url, '?') ? '&' : '?';
$this->redirect($url.$join.'uebernehmen=composition:'.$version->id, navigate: false);
}
/**
* @return array<string, string|null>|null
*/
public function selectedMember(): ?array
{
if ($this->selected === null) {
return null;
}
return $this->members[$this->selected] ?? null;
}
protected function loadEditor(): void
{
$this->fillRedaktion();
$this->loadAufbau();
}
/**
* Liest die Angaben der Redaktion (Name, Texte, Einordnung) aus dem gespeicherten Stand.
*/
protected function fillRedaktion(): void
{
/** @var Composition $composition */
$composition = $this->getRecord();
$composition->refresh();
$this->designation = $composition->designation;
$this->displayTitle = (string) ($composition->display_title ?? '');
$this->teaser = (string) ($composition->teaser ?? '');
$this->summary = (string) ($composition->summary ?? '');
$this->searchTerms = (string) ($composition->search_terms ?? '');
$this->description = (string) ($composition->description ?? '');
$this->dimensionIds = IdentityDimensionValue::query()
->where('subject_type', $composition->getMorphClass())
->where('subject_id', $composition->id)
->where('origin', 'direkt')
->pluck('editorial_dimension_value_id')
->map(fn (mixed $id): string => (string) (int) $id)
->all();
}
/**
* Liest Aufbau, Didaktik und Katalogbild aus Entwurf oder letzter freigegebener Fassung.
*/
protected function loadAufbau(): void
{
/** @var Composition $composition */
$composition = $this->getRecord();
$composition->refresh();
$version = $this->currentReadyVersion();
$this->thumbnailPath = $composition->thumbnail_path;
$this->thumbnailAlt = (string) ($composition->thumbnail_alt ?? '');
$this->thumbnailError = $composition->thumbnail_error;
$this->thumbnailSource = $composition->thumbnail_source;
$this->imageCaptionText = $this->captionFor($composition->thumbnail_source);
$this->catalogScope = match ($this->hostKind()) {
CompositionKind::Kurs => 'module',
CompositionKind::Uebung => 'medien',
default => 'alles',
};
$draft = app(EditorialWorkingDraft::class)->read($composition);
if ($draft !== null) {
$this->applyDraft($draft);
return;
}
if ($version === null) {
$this->members = [];
$this->learningGoal = '';
$this->durationMinutes = '';
$this->materialNote = '';
return;
}
$this->applyVersion($version);
}
/**
* @param array<string, mixed> $draft
*/
protected function applyDraft(array $draft): void
{
$catalog = app(EditorialCatalog::class);
$rows = [];
$requested = 0;
foreach ($draft['members'] ?? [] as $member) {
if (! is_array($member)) {
continue;
}
$requested++;
$row = $catalog->rowForTarget((string) ($member['target'] ?? ''), (int) $this->getRecord()->getKey(), allowSelf: true, allowDraft: true, allowBlocked: true);
if ($row === null) {
continue;
}
$row['role'] = (string) ($member['role'] ?? $row['kind']);
$row['note'] = trim((string) ($member['note'] ?? ''));
$rows[] = $row;
}
$this->members = $rows;
$this->learningGoal = (string) ($draft['learning_goal'] ?? '');
$this->durationMinutes = ($draft['duration_minutes'] ?? null) === null ? '' : (string) $draft['duration_minutes'];
$this->materialNote = (string) ($draft['material_note'] ?? '');
$this->revisionNote = (string) ($draft['revision_note'] ?? '');
$this->selected = null;
$this->roleDraft = '';
$this->noteDraft = '';
$this->panel = 'angaben';
if ($requested > count($rows) && $this->feedback === '') {
$this->feedback = 'Ein Bestandteil des Entwurfs ist nicht mehr bereit und wurde nicht geladen.';
}
}
protected function applyVersion(CompositionVersion $version): void
{
$this->members = app(EditorialCatalog::class)->rows($version, (int) $this->getRecord()->getKey());
$this->learningGoal = (string) ($version->learning_goal ?? '');
$this->durationMinutes = $version->duration_minutes === null ? '' : (string) $version->duration_minutes;
$this->materialNote = (string) ($version->material_note ?? '');
$this->selected = null;
$this->roleDraft = '';
$this->noteDraft = '';
$this->panel = 'angaben';
}
public function updatedRoleDraft(string $value): void
{
$this->commitRoleDraft($value);
}
protected function commitRoleDraft(?string $value = null): void
{
if ($this->selected === null || ! isset($this->members[$this->selected])) {
return;
}
$this->members[$this->selected]['role'] = trim($value ?? $this->roleDraft);
$this->members[$this->selected]['note'] = trim($this->noteDraft);
}
protected function syncRoleDraft(): void
{
$member = $this->selected !== null ? ($this->members[$this->selected] ?? null) : null;
$this->roleDraft = is_array($member) ? (string) ($member['role'] ?? '') : '';
$this->noteDraft = is_array($member) ? (string) ($member['note'] ?? '') : '';
$this->partTitle = is_array($member) ? (string) ($member['title'] ?? '') : '';
$this->partBody = is_array($member) ? (string) ($member['body'] ?? '') : '';
}
public function releaseDisplay(): void
{
$this->releaseCurrent();
}
protected function releaseCurrent(): void
{
$version = $this->currentReadyVersion();
$actor = $this->actor();
abort_unless($version !== null && $actor instanceof User, 403);
if ($this->needsRevision()) {
$this->feedback = 'Übernimm zuerst die Änderungen. Freigegeben wird nur eine bereits übernommene Fassung.';
return;
}
app(CompositionDisplayRelease::class)->release($version, $actor);
$this->feedback = 'Fassung '.$version->number.' ist in der Mitgliederbibliothek sichtbar. Frühere Fassungen bleiben erhalten.';
}
protected function currentReadyVersion(): ?CompositionVersion
{
/** @var Composition $composition */
$composition = $this->getRecord();
return $composition->versions()
->where('status', ContentVersionStatus::Bereit)
->orderByDesc('number')
->first();
}
protected function ownedVersion(int $versionId): ?CompositionVersion
{
/** @var Composition $composition */
$composition = $this->getRecord();
return $composition->versions()->whereKey($versionId)->first();
}
protected function needsRevision(): bool
{
$current = $this->currentReadyVersion();
if ($current === null) {
return $this->members !== [];
}
return ! $this->sameMembers($current) || $this->didacticChanged($current);
}
protected function sameMembers(CompositionVersion $version): bool
{
$version->loadMissing('members');
$current = $version->members->map(function ($member): string {
$target = $member->content_element_version_id
? 'element:'.$member->content_element_version_id
: 'composition:'.$member->nested_composition_version_id;
return $member->role.'|'.$target.'|'.trim((string) ($member->placement_note ?? ''));
})->all();
$next = array_values(array_map(
fn (array $member): string => trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? '').'|'.trim((string) ($member['note'] ?? '')),
$this->members,
));
return $current === $next;
}
protected function didacticChanged(CompositionVersion $version): bool
{
$minutes = $this->minutes($this->durationMinutes);
if ($minutes === false) {
return true;
}
$storedMinutes = $version->duration_minutes === null ? null : (int) $version->duration_minutes;
return $version->learning_goal !== $this->blank($this->learningGoal)
|| $version->material_note !== $this->blank($this->materialNote)
|| $storedMinutes !== $minutes;
}
protected function minutes(string $value): int|false|null
{
$value = trim($value);
if ($value === '') {
return null;
}
if (preg_match('/^\d+$/', $value) !== 1) {
return false;
}
$minutes = (int) $value;
return $minutes > 0 ? $minutes : false;
}
protected function blank(string $value): ?string
{
$value = trim($value);
return $value === '' ? null : $value;
}
/**
* @param list<int> $ids
*/
protected function syncDimensions(Composition $composition, array $ids): void
{
app(IdentityDimension::class)->replaceOffered($composition, $ids);
}
/**
* Schreibt Name, Texte und Einordnung. Aufbau, Didaktik, Katalogbild und Fassungen bleiben unberührt.
*/
protected function persistRedaktion(): bool
{
/** @var Composition $record */
$record = $this->getRecord();
$name = trim($this->designation);
if ($name === '') {
$this->feedback = 'Der Name fehlt.';
return false;
}
$record->designation = $name;
app(IdentityProfile::class)->fill($record, [
'display_title' => $this->displayTitle,
'teaser' => $this->teaser,
'summary' => $this->summary,
'search_terms' => $this->searchTerms,
'description' => $this->description,
], $this->actor());
$this->syncDimensions($record, array_map(intval(...), $this->dimensionIds));
$record->refresh();
$this->getRecord()->setRawAttributes($record->getAttributes());
return true;
}
protected function persistDraft(): bool
{
if ($this->minutes($this->durationMinutes) === false) {
$this->feedback = 'Der Zeitbedarf ist eine Zahl von Minuten oder bleibt leer.';
return false;
}
/** @var Composition $record */
$record = $this->getRecord();
app(EditorialWorkingDraft::class)->write($record, $this->payload());
return true;
}
protected function applyChosenImage(): string|false
{
if ($this->imageMode === 'upload' && $this->previewUpload instanceof TemporaryUploadedFile) {
$extension = strtolower($this->previewUpload->getClientOriginalExtension());
if (! in_array($extension, ['png', 'jpg', 'jpeg', 'webp'], true)) {
$this->feedback = 'Das Vorschaubild muss eine Bilddatei sein.';
return false;
}
$path = $this->previewUpload->storeAs(
'vorschau',
'karte-'.bin2hex(random_bytes(4)).'.'.$extension,
'cms_incoming',
);
$this->previewUpload = null;
if (! is_string($path)) {
$this->feedback = 'Das Vorschaubild wurde nicht übernommen.';
return false;
}
$this->storePreview($path);
return str_contains($this->feedback, 'unverändert') ? $this->feedback : false;
}
if ($this->imageMode === 'film' && $this->frameVersionId !== null && trim($this->frameSecond) !== '') {
if (! is_numeric($this->frameSecond) || (float) $this->frameSecond < 0 || (float) $this->frameSecond > 7200) {
$this->feedback = 'Die Zeitposition muss eine Zahl in Sekunden sein.';
return false;
}
$version = ContentElementVersion::query()->with('element')->find($this->frameVersionId);
$target = 'element:'.(int) $this->frameVersionId;
$known = array_map(fn (array $member): string => (string) ($member['target'] ?? ''), $this->members);
if (! $version instanceof ContentElementVersion || $version->element?->output_class !== 'film' || ! in_array($target, $known, true)) {
$this->feedback = 'Die Filmfassung gehört nicht zu diesem Aufbau.';
return false;
}
/** @var Composition $record */
$record = $this->getRecord();
$before = $record->versions()->count();
DeriveCompositionFrame::dispatch($record->id, $version->id, (float) $this->frameSecond);
$record->refresh();
$this->thumbnailPath = $record->thumbnail_path;
$this->thumbnailError = $record->thumbnail_error;
$this->rememberCaption($record);
$note = $this->previewFeedback($record, $before);
if (! str_contains($note, 'unverändert')) {
$this->feedback = $note;
return false;
}
return $note;
}
return '';
}
protected function storePreview(string $path): void
{
if (! str_starts_with($path, 'vorschau/') || str_contains($path, '..')) {
$this->feedback = 'Das Vorschaubild wurde nicht übernommen.';
return;
}
/** @var Composition $record */
$record = $this->getRecord();
$before = $record->versions()->count();
DeriveThumbnail::dispatch('komposition', $record->id, $path);
$record->refresh();
$this->thumbnailPath = $record->thumbnail_path;
$this->thumbnailError = $record->thumbnail_error;
$this->rememberCaption($record);
$this->feedback = $this->previewFeedback($record, $before);
}
protected function previewFeedback(Composition $record, int $versionsBefore): string
{
if ($record->versions()->count() !== $versionsBefore) {
return 'Das Vorschaubild wurde nicht übernommen.';
}
if (filled($record->thumbnail_path) && $record->thumbnail_error === null) {
return 'Das Vorschaubild ist gespeichert. Die Fassung bleibt unverändert.';
}
if (config('queue.default') !== 'sync') {
return 'Das Titelbild wird vorbereitet. Die Fassung bleibt unverändert.';
}
return $record->thumbnail_error ?: 'Das Vorschaubild wurde nicht übernommen.';
}
protected function statusSentence(): string
{
return $this->editorStatus();
}
/**
* @return array{learning_goal: ?string, duration_minutes: int|string|null, material_note: ?string, revision_note: ?string, members: list<array{role: string, target: string}>}
*/
protected function payload(): array
{
// Rolle und Hinweis stehen bereits in $members (commitRoleDraft bei jeder Änderung und vor jedem Speichern).
$members = $this->members;
$minutes = $this->minutes($this->durationMinutes);
return [
'learning_goal' => $this->blank($this->learningGoal),
'duration_minutes' => $minutes === false ? $this->durationMinutes : $minutes,
'material_note' => $this->blank($this->materialNote),
'revision_note' => $this->blank($this->revisionNote),
'members' => array_values(array_map(
fn (array $member): array => [
'role' => trim((string) ($member['role'] ?? '')),
'target' => (string) ($member['target'] ?? ''),
'note' => trim((string) ($member['note'] ?? '')),
],
$members,
)),
];
}
/**
* @return array{learning_goal: ?string, duration_minutes: int|null, material_note: ?string, revision_note: ?string, members: list<array{role: string, target: string}>}|null
*/
protected function storedPayload(): ?array
{
/** @var Composition $composition */
$composition = $this->getRecord();
$draft = $composition->working_draft;
if (! is_array($draft) || $draft === []) {
return null;
}
return $this->normalizePayload($draft);
}
/**
* @return array{learning_goal: ?string, duration_minutes: int|null, material_note: ?string, revision_note: ?string, members: list<array{role: string, target: string}>}
*/
protected function readyPayload(): array
{
$version = $this->currentReadyVersion();
if ($version === null) {
return [
'learning_goal' => null,
'duration_minutes' => null,
'material_note' => null,
'revision_note' => null,
'members' => [],
];
}
$rows = app(EditorialCatalog::class)->rows($version, (int) $this->getRecord()->getKey());
return [
'learning_goal' => $version->learning_goal,
'duration_minutes' => $version->duration_minutes === null ? null : (int) $version->duration_minutes,
'material_note' => $version->material_note,
'revision_note' => null,
'members' => array_values(array_map(
fn (array $row): array => [
'role' => trim((string) ($row['role'] ?? '')),
'target' => (string) ($row['target'] ?? ''),
'note' => trim((string) ($row['note'] ?? '')),
],
$rows,
)),
];
}
/**
* @param array<string, mixed> $payload
* @return array{learning_goal: ?string, duration_minutes: int|string|null, material_note: ?string, revision_note: ?string, members: list<array{role: string, target: string}>}
*/
protected function normalizePayload(array $payload): array
{
$members = [];
foreach ($payload['members'] ?? [] as $member) {
if (! is_array($member)) {
continue;
}
$members[] = [
'role' => trim((string) ($member['role'] ?? '')),
'target' => (string) ($member['target'] ?? ''),
'note' => trim((string) ($member['note'] ?? '')),
];
}
return [
'learning_goal' => $payload['learning_goal'] ?? null,
'duration_minutes' => $payload['duration_minutes'] ?? null,
'material_note' => $payload['material_note'] ?? null,
'revision_note' => $payload['revision_note'] ?? null,
'members' => $members,
];
}
/**
* @param array<string, mixed> $payload
*/
protected function fingerprint(array $payload): string
{
return json_encode($this->normalizePayload($payload), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
}
protected function actor(): ?User
{
$actor = Filament::auth()->user();
return $actor instanceof User ? $actor : null;
}
protected function safeReturn(mixed $url): string
{
if (! is_string($url) || $url === '') {
return '';
}
$parts = parse_url($url);
$path = is_array($parts) ? ($parts['path'] ?? '') : '';
if (! is_string($path) || ! str_starts_with($path, '/verwaltung/') || str_contains($path, '..')) {
return '';
}
$query = is_array($parts) ? ($parts['query'] ?? '') : '';
return $path.(is_string($query) && $query !== '' ? '?'.$query : '');
}
/**
* @param array<string, mixed> $data
*/
protected function handleRecordUpdate(Model $record, array $data): Model
{
return $record;
}
}