Files
laraundfelix/app/Filament/Resources/Compositions/Pages/EditComposition.php
T
LarsandCursor 89c574106f
Deploy Test / test (push) Successful in 26s
Deploy Test / deploy (push) Successful in 28s
Lege Medien über eine gemeinsame Maske mit Upload-Fortschritt an.
Beschreibung, Hinweise und Vorschaubild bleiben danach in derselben Maske bearbeitbar, im Bestand wie im Modul und Programm.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 10:56:03 +01:00

2079 lines
66 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\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\EditorialDimensionValue;
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\Filament\Support\EditorialCatalog;
use App\Filament\Support\MediumForm;
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 WithFileUploads;
protected string $view = 'filament.editorial.edit';
public string $designation = '';
public string $displayTitle = '';
public string $summary = '';
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 $pickerOpen = false;
public string $pickerQuery = '';
public string $pickerKind = 'alle';
public string $pickerDimension = '';
public string $pickerSelected = '';
public bool $textOpen = false;
public bool $releaseArmed = 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;
public string $imageQuery = '';
public bool $moduleOpen = false;
public string $moduleTab = 'beschreibung';
public bool $partOpen = false;
public string $imageMode = 'film';
public string $imagePick = '';
public ?int $frameVersionId = null;
public string $frameSecond = '';
/** @var array<string, mixed> */
public array $moduleSnapshot = [];
/** @var list<array<string, mixed>> */
public array $partSnapshot = [];
/** @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->returnUrl = $this->safeReturn(request()->query('zurueck'));
$adopt = request()->query('uebernehmen');
if (is_string($adopt)) {
$this->addPart($adopt);
}
$flashed = session('redaktion');
if (is_string($flashed) && $flashed !== '' && $this->feedback === '') {
$this->feedback = $flashed;
}
}
public function getHeading(): string|Htmlable|null
{
$title = trim($this->displayTitle) !== '' ? trim($this->displayTitle) : trim($this->designation);
return $title !== '' ? $title : parent::getHeading();
}
public function getSubheading(): string|Htmlable|null
{
return $this->hostKind()->deskExplanation().' '.$this->statusSentence();
}
public function getMaxContentWidth(): Width|string|null
{
return Width::Full;
}
protected function mutateFormDataBeforeFill(array $data): array
{
return [];
}
protected function getHeaderActions(): array
{
return [
Action::make('preview')
->label('Vorschau für Trainer')
->url(fn (): ?string => $this->previewUrl())
->openUrlInNewTab()
->visible(fn (): bool => $this->previewUrl() !== null),
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();
}),
Action::make('displayRevoke')
->label('Aus Mitgliederbibliothek ausblenden')
->color('danger')
->requiresConfirmation()
->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 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
{
if ($this->moduleOpen) {
$this->closeModule();
}
if ($this->partOpen) {
$this->closePart();
}
$this->pickerOpen = true;
$this->textOpen = false;
$this->pickerSelected = '';
}
public function closePicker(): void
{
$this->pickerOpen = false;
}
/**
* @return array{items: list<array<string, string|null>>, more: bool}
*/
public function pickerResult(): array
{
if (! $this->pickerOpen) {
return ['items' => [], 'more' => false];
}
return app(EditorialCatalog::class)->browse(
$this->pickerQuery,
$this->pickerKind,
$this->pickerDimension,
(int) $this->getRecord()->getKey(),
);
}
/**
* @return array<string, string|null>|null
*/
public function pickerDetail(): ?array
{
if ($this->pickerSelected === '') {
return null;
}
$row = app(EditorialCatalog::class)->rowForTarget(
$this->pickerSelected,
(int) $this->getRecord()->getKey(),
);
if ($row === null) {
return null;
}
$row['playback'] = null;
if (preg_match('/^element:(\d+)$/', (string) $row['target'], $match) === 1) {
$version = ContentElementVersion::query()->with('element')->find($match[1]);
$row['playback'] = $version instanceof ContentElementVersion
? app(ContentPreviewController::class)->playback($version)
: null;
}
return $row;
}
/**
* @return list<array{target: string, label: string, current: bool}>
*/
public function pickerVersions(): array
{
$detail = $this->pickerDetail();
if ($detail === null) {
return [];
}
$options = app(EditorialCatalog::class)->alternatives(
(string) ($detail['identity'] ?? ''),
(int) $this->getRecord()->getKey(),
);
if ($options === []) {
return [];
}
$current = $options[array_key_last($options)]['target'];
return array_map(
fn (array $option): array => $option + ['current' => $option['target'] === $current],
$options,
);
}
public function pickerMatches(string $identity): bool
{
$detail = $this->pickerDetail();
return $detail !== null && ($detail['identity'] ?? '') === $identity;
}
public function openText(): void
{
$this->pickerOpen = false;
$this->moduleOpen = false;
$this->partOpen = 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->releaseArmed = true;
}
public function cancelRelease(): void
{
$this->releaseArmed = false;
}
public function discardDraft(): void
{
/** @var Composition $record */
$record = $this->getRecord();
app(EditorialWorkingDraft::class)->clear($record);
$this->releaseArmed = false;
$this->loadEditor();
$this->feedback = 'Der Entwurf ist verworfen. Eine freigegebene Fassung bleibt unverändert.';
}
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::query()->with('values')->orderBy('label')->get() 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:(\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->syncRoleDraft();
}
public function addPart(string $target): void
{
$this->includePart($target, false);
}
private function includePart(string $target, bool $allowDraft): bool
{
if (preg_match('/^(element|composition):\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 = '';
if (! $this->persistDraft()) {
return false;
}
$this->feedback = $row['title'].' ist in den Aufbau übernommen. Die Datei wird nicht kopiert. Der Entwurf ist gespeichert. Es entsteht keine neue Fassung.';
return true;
}
public function removePart(int $index): void
{
if (! isset($this->members[$index])) {
return;
}
unset($this->members[$index]);
$this->members = array_values($this->members);
$this->selected = null;
$this->roleDraft = '';
$this->noteDraft = '';
$this->panel = 'angaben';
$this->partOpen = false;
$this->partSnapshot = [];
$this->feedback = 'Der Bestandteil ist aus dem Arbeitsstand genommen. Entwurf speichern hält das fest. Eine freigegebene Fassung bleibt unverändert.';
}
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.';
}
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)
->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 editMediumAction(): Action
{
return Action::make('editMedium')
->modalHeading('Medium bearbeiten')
->modalDescription('Titel, Beschreibung, Hinweise und Vorschaubild gelten für das Medium. Eine neue Fassung entsteht nur, wenn der Text bereits freigegeben und verwendet wird.')
->modalSubmitActionLabel('Speichern')
->modalWidth(Width::Large)
->fillForm(function (array $arguments): array {
$element = ContentElement::query()->find($arguments['element'] ?? 0);
return $element instanceof ContentElement ? MediumForm::fill($element) : [];
})
->schema(function (array $arguments): array {
$element = ContentElement::query()->find($arguments['element'] ?? 0);
return MediumForm::fields(creating: false, element: $element instanceof ContentElement ? $element : null);
})
->action(function (array $data, array $arguments): void {
$element = ContentElement::query()->find($arguments['element'] ?? 0);
if (! $element instanceof ContentElement) {
Notification::make()->title('Dieses Medium ist nicht mehr vorhanden.')->danger()->send();
throw new Halt;
}
try {
$revised = MediumForm::update($element, $data);
} catch (DomainRuleException $exception) {
Notification::make()->title($exception->getMessage())->danger()->send();
throw new Halt;
}
$this->retargetContainedElement($element, $revised);
$this->feedback = 'Die Angaben des Mediums 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->persistPresentation()) {
return;
}
$this->feedback = 'Die Anzeige ist gespeichert. Die Fassung bleibt unverändert.';
}
public function openModule(): void
{
$this->moduleSnapshot = [
'designation' => $this->designation,
'displayTitle' => $this->displayTitle,
'summary' => $this->summary,
'description' => $this->description,
'learningGoal' => $this->learningGoal,
'durationMinutes' => $this->durationMinutes,
'materialNote' => $this->materialNote,
'revisionNote' => $this->revisionNote,
'thumbnailAlt' => $this->thumbnailAlt,
'dimensionIds' => $this->dimensionIds,
'imageMode' => $this->imageMode,
'imagePick' => $this->imagePick,
'frameVersionId' => $this->frameVersionId,
'frameSecond' => $this->frameSecond,
];
$this->pickerOpen = false;
$this->partOpen = false;
$this->textOpen = false;
$this->moduleTab = 'beschreibung';
$this->frameFilmChoices = $this->frameFilms();
$films = $this->frameFilmChoices;
$this->imageMode = $films === [] ? 'bestand' : 'film';
if ($films !== [] && $this->frameVersionId === null) {
$this->frameVersionId = $films[0]['version_id'];
}
$this->moduleOpen = true;
}
public function closeModule(): void
{
foreach ($this->moduleSnapshot as $key => $value) {
$this->{$key} = $value;
}
$this->moduleOpen = false;
$this->moduleSnapshot = [];
$this->previewUpload = null;
}
public function saveModule(): void
{
if ($this->minutes($this->durationMinutes) === false) {
$this->feedback = 'Der Zeitbedarf ist eine Zahl von Minuten oder bleibt leer.';
return;
}
if (! $this->persistPresentation()) {
return;
}
$image = $this->applyChosenImage();
if ($image === false) {
return;
}
/** @var Composition $record */
$record = $this->getRecord();
if ($this->needsRevision() || app(EditorialWorkingDraft::class)->read($record) !== null) {
$this->persistDraft();
}
$this->moduleOpen = false;
$this->moduleSnapshot = [];
$this->previewUpload = null;
$this->imagePick = '';
$this->feedback = trim('Die Angaben sind übernommen. Es entsteht keine neue Fassung.'.($image === '' ? '' : ' '.$image));
}
public function openPart(int $index): void
{
$this->selectPart($index);
$member = $this->selectedMember();
$this->partTitle = (string) ($member['title'] ?? '');
$this->partBody = (string) ($member['body'] ?? '');
$this->partSnapshot = $this->members;
$this->moduleOpen = false;
$this->pickerOpen = false;
$this->textOpen = false;
$this->partOpen = true;
}
public function closePart(): void
{
if ($this->partSnapshot !== []) {
$this->members = $this->partSnapshot;
}
$this->partOpen = false;
$this->partSnapshot = [];
$this->syncRoleDraft();
}
public function savePart(): void
{
if (trim($this->roleDraft) === '') {
$this->feedback = 'Die Rolle fehlt.';
return;
}
$this->commitRoleDraft();
$textNote = $this->writePartText();
if ($textNote === false) {
return;
}
if (! $this->persistDraft()) {
return;
}
$this->partOpen = false;
$this->partSnapshot = [];
$this->feedback = $textNote !== ''
? $textNote
: 'Die Angaben zum Bestandteil sind im Entwurf. Es entsteht keine neue Fassung.';
}
/**
* @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 retargetContainedElement(ContentElement $element, ?ContentElementVersion $revised): void
{
$element->refresh();
foreach ($this->members as $index => $member) {
if ((int) ($member['element_id'] ?? 0) !== $element->id) {
continue;
}
$target = $revised instanceof ContentElementVersion
? 'element:'.$revised->id
: (string) ($member['target'] ?? '');
$row = app(EditorialCatalog::class)->rowForTarget(
$target,
(int) $this->getRecord()->getKey(),
allowSelf: true,
allowDraft: true,
);
if ($row === null) {
continue;
}
$row['role'] = (string) ($member['role'] ?? $row['kind']);
$row['note'] = (string) ($member['note'] ?? '');
$this->members[$index] = $row;
}
$this->persistDraft();
}
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 list<array{role: string, target: ContentElementVersion|CompositionVersion, note: string}> $payload
*/
private function promoteDraftElements(array $payload): bool
{
foreach ($payload as $member) {
$target = $member['target'];
if (! $target instanceof ContentElementVersion || $target->status !== ContentVersionStatus::Entwurf) {
continue;
}
$meta = is_array($target->metadata) ? $target->metadata : [];
if (isset($meta['incoming']) && ! isset($meta['file'])) {
$this->feedback = 'Eine Datei wird noch übernommen. Gib den Aufbau frei, sobald die Datei bereitsteht.';
return false;
}
if (isset($meta['error'])) {
$this->feedback = (string) $meta['error'];
return false;
}
unset($meta['held']);
$target->metadata = $meta === [] ? null : $meta;
$target->content_hash = hash('sha256', json_encode([
'body' => $target->body,
'metadata' => $meta,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
$target->status = ContentVersionStatus::Bereit;
$target->save();
}
return true;
}
/**
* @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{id: int, title: string, image: string, kind: string}>
*/
public function mediaChoices(): array
{
return app(EditorialCatalog::class)->mediaPictures($this->imageQuery);
}
/**
* @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;
}
$payload = [];
foreach (array_values($this->members) as $member) {
$role = trim((string) ($member['role'] ?? ''));
$target = (string) ($member['target'] ?? '');
if ($role === '' || preg_match('/^(element|composition):(\d+)$/', $target, $match) !== 1) {
$this->feedback = 'Jeder Bestandteil braucht eine Rolle und eine vorhandene Fassung.';
return false;
}
$model = $match[1] === 'composition'
? CompositionVersion::query()->find($match[2])
: ContentElementVersion::query()->find($match[2]);
if ($model === null) {
$this->feedback = 'Ein Bestandteil ist nicht mehr vorhanden.';
return false;
}
$payload[] = [
'role' => $role,
'target' => $model,
'note' => trim((string) ($member['note'] ?? '')),
];
}
if (! $this->promoteDraftElements($payload)) {
return false;
}
/** @var Composition $record */
$record = $this->getRecord();
$note = trim($this->revisionNote);
try {
app(ContentService::class)->publishComposition(
$record,
$payload,
$this->actor(),
$note !== '' ? $note : null,
[
'learning_goal' => $this->blank($this->learningGoal),
'duration_minutes' => $minutes,
'material_note' => $this->blank($this->materialNote),
],
);
} catch (DomainRuleException $exception) {
$this->feedback = $exception->getMessage();
return false;
}
$this->revisionNote = '';
$this->templateNumber = null;
$this->releaseArmed = false;
app(EditorialWorkingDraft::class)->clear($record);
$this->loadEditor();
$this->feedback = 'Die neue Fassung ist übernommen. Die bisherige Fassung bleibt erhalten.';
return true;
}
public function returnAndInclude(): void
{
if ($this->returnUrl === '') {
return;
}
if ($this->needsRevision()) {
if (! $this->publishRevision()) {
return;
}
}
$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
{
/** @var Composition $composition */
$composition = $this->getRecord();
$composition->refresh();
$version = $this->currentReadyVersion();
$this->designation = $composition->designation;
$this->displayTitle = (string) ($composition->display_title ?? '');
$this->summary = (string) ($composition->summary ?? '');
$this->description = (string) ($composition->description ?? '');
$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->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();
$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);
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'] ?? '') : '';
}
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
{
IdentityDimensionValue::query()
->where('subject_type', $composition->getMorphClass())
->where('subject_id', $composition->id)
->where('origin', 'direkt')
->whereNotIn('editorial_dimension_value_id', $ids === [] ? [0] : $ids)
->delete();
foreach (EditorialDimensionValue::query()->whereIn('id', $ids)->get() as $value) {
app(IdentityDimension::class)->assign($composition, $value, 'direkt');
}
}
protected function persistPresentation(): 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,
'summary' => $this->summary,
'description' => $this->description,
'thumbnail_alt' => $this->thumbnailAlt,
], $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 === 'bestand' && ctype_digit($this->imagePick)) {
$this->adoptPicture((int) $this->imagePick);
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
{
$members = $this->members;
if ($this->selected !== null && isset($members[$this->selected]) && trim($this->roleDraft) !== '') {
$members[$this->selected]['role'] = trim($this->roleDraft);
}
$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;
}
}