Files
laraundfelix/app/Filament/Resources/Compositions/Pages/EditComposition.php
T
LarsandCursor 053a361801
Deploy Test / test (push) Successful in 22s
Deploy Test / deploy (push) Successful in 23s
Mache Auswahl, Aufbau und Entwurf im Redaktionseditor bedienbar.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-16 16:40:50 +01:00

1316 lines
41 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\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\Jobs\DeriveThumbnail;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Enums\Width;
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 $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 $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 $newModuleName = '';
public mixed $previewUpload = null;
public ?string $thumbnailPath = null;
public ?string $thumbnailError = null;
/** @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('Zur Anzeige freigeben')
->requiresConfirmation()
->modalHeading('Diese Fassung zur Anzeige freigeben')
->modalDescription('Freigegeben wird die zuletzt übernommene Fassung. 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('Anzeige zurücknehmen')
->color('danger')
->requiresConfirmation()
->modalDescription('Nur die Anzeige dieser Fassung wird zurückgenommen. Der Inhalt der Fassung bleibt gespeichert.')
->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 Anzeige dieser Fassung ist zurückgenommen. 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
{
$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;
}
return app(EditorialCatalog::class)->rowForTarget(
$this->pickerSelected,
(int) $this->getRecord()->getKey(),
);
}
public function openText(): void
{
$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->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 zur Anzeige freigegeben.'
: ' Sie ist noch nicht zur Anzeige freigegeben.');
$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 ? ', zur Anzeige freigegeben' : ''),
'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
{
if (preg_match('/^(element|composition):\d+$/', $target) !== 1) {
$this->feedback = 'Dieser Bestandteil ist nicht verfügbar.';
return;
}
foreach ($this->members as $index => $member) {
if (($member['target'] ?? '') === $target) {
$this->selected = $index;
$this->panel = 'bestandteil';
$this->feedback = 'Diese Fassung ist schon enthalten.';
return;
}
}
$row = app(EditorialCatalog::class)->rowForTarget($target, (int) $this->getRecord()->getKey());
if ($row === null) {
$this->feedback = 'Diese Fassung ist nicht bereit oder gehört zu diesem Eintrag.';
return;
}
$row['role'] = app(EditorialCatalog::class)->defaultRole((string) $row['kind']);
$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->feedback = $row['title'].' ist in den Aufbau übernommen. Die Datei wird nicht kopiert. Gespeichert ist das erst mit „Entwurf speichern“.';
}
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->panel = 'angaben';
$this->feedback = 'Der Bestandteil ist aus dem Arbeitsstand genommen. Gespeichert ist das erst mit einer neuen Fassung.';
}
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'];
$this->members[$index] = $row;
$this->syncRoleDraft();
$this->feedback = $row['version_label'].' ist für diese Stelle ausgewählt. Übernehmen legt dafür eine neue Fassung an.';
}
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. Übernehmen legt eine neue Fassung an und lässt die geladene Fassung 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->publishElementVersion($element, $body);
} catch (DomainRuleException $exception) {
$this->feedback = $exception->getMessage();
return;
}
$this->newTextTitle = '';
$this->newTextBody = '';
$this->textOpen = false;
$this->addPart('element:'.$version->id);
$this->feedback = $title.' ist angelegt und in den Aufbau übernommen. Derselbe Text kann später woanders wiederverwendet werden. Gespeichert ist das erst mit „Entwurf speichern“.';
}
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
{
/** @var Composition $record */
$record = $this->getRecord();
$name = trim($this->designation);
if ($name === '') {
$this->feedback = 'Der Name fehlt.';
return;
}
$record->designation = $name;
app(IdentityProfile::class)->fill($record, [
'display_title' => $this->displayTitle,
'summary' => $this->summary,
], $this->actor());
$this->syncDimensions($record, array_map(intval(...), $this->dimensionIds));
$record->refresh();
$this->getRecord()->setRawAttributes($record->getAttributes());
$this->feedback = 'Die Anzeige ist gespeichert. Die Fassung bleibt unverändert.';
}
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 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];
}
/** @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->thumbnailPath = $composition->thumbnail_path;
$this->thumbnailError = $composition->thumbnail_error;
$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);
if ($row === null) {
continue;
}
$row['role'] = (string) ($member['role'] ?? $row['kind']);
$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->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->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);
}
protected function syncRoleDraft(): void
{
$this->roleDraft = $this->selected !== null && isset($this->members[$this->selected])
? (string) ($this->members[$this->selected]['role'] ?? '')
: '';
}
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 zur Anzeige freigegeben. 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;
})->all();
$next = array_values(array_map(
fn (array $member): string => trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? ''),
$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 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->feedback = $record->versions()->count() === $before && filled($record->thumbnail_path)
? 'Das Vorschaubild ist gespeichert. Die Fassung bleibt unverändert.'
: ($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'] ?? ''),
],
$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'] ?? ''),
],
$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'] ?? ''),
];
}
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;
}
}