Files
laraundfelix/app/Filament/Resources/Compositions/Pages/EditComposition.php
T
LarsandCursor c997eb500c
Deploy Test / test (push) Successful in 2m28s
Deploy Test / deploy (push) Failing after 14s
Leite Vorschaubilder und Filmstufen geschuetzt ab
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-16 09:40:59 +01:00

477 lines
20 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Filament\Resources\Compositions\Pages;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionDisplayRelease;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\CompositionMember;
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\EditorialContentKind;
use App\Domain\Catalog\EditorialDimension;
use App\Domain\Catalog\EditorialDimensionValue;
use App\Domain\Catalog\IdentityDimension;
use App\Domain\Catalog\IdentityDimensionValue;
use App\Domain\Catalog\IdentityProfile;
use App\Domain\Catalog\StructureNode;
use App\Filament\Resources\Combinations\CombinationResource;
use App\Filament\Resources\Courses\CourseResource;
use App\Filament\Resources\Exercises\ExerciseResource;
use App\Filament\Support\CatalogOptions;
use App\Filament\Support\CatalogReading;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Filament\Schemas\Schema;
use Filament\Support\Exceptions\Halt;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\HtmlString;
abstract class EditComposition extends EditRecord
{
protected ?string $savedTitle = null;
public function getSubheading(): string|Htmlable|null
{
return 'Bausteine hinzufügen, gegen eine neuere Medienfassung tauschen oder aus der Liste nehmen. Speichern legt dafür eine neue Fassung an. Die bisherige Fassung bleibt und wird nicht nachträglich verändert.';
}
public function form(Schema $schema): Schema
{
return $schema->columns(1)->components([
TextInput::make('designation')->label('Bezeichnung')->required(),
TextInput::make('display_title')->label('Anzeigetitel')
->helperText('Erscheint in der Bibliothek. Leer lässt die Bezeichnung stehen.'),
Textarea::make('summary')->label('Kurzbeschreibung')->rows(3),
Textarea::make('learning_goal')->label('Lernziel')->rows(2)
->helperText('Gehört zur Fassung. Eine Änderung legt eine neue Fassung an.'),
TextInput::make('duration_minutes')->label('Zeitbedarf in Minuten')->numeric()->minValue(1),
Textarea::make('material_note')->label('Materialbedarf')->rows(2),
Placeholder::make('status')->label('Stand')->content(fn (): HtmlString => new HtmlString(e($this->statusText()))),
Placeholder::make('outline')->label('Gliederung der aktuellen Fassung')->content(fn (): HtmlString => new HtmlString($this->outlineHtml())),
Select::make('kind')->label('Zusammenstellung')->options(CompositionKind::deskOptions())->required()
->helperText('Programm, Modul oder fachliche Kombination. Die Inhaltsart steuert die Bibliothek. Die gespeicherte Herkunft bleibt bestehen.'),
Select::make('editorial_content_kind_id')
->label('Inhaltsart')
->options(fn (): array => EditorialContentKind::selectOptions())
->nullable()
->helperText('Optional für Bibliothek und Website. Ändert weder die technische Art noch eine Fassung.'),
Placeholder::make('usage')->label('Verwendung')->content(function (): HtmlString {
$version = $this->currentReadyVersion();
if ($version === null) {
return new HtmlString('Noch keine Fassung.');
}
$lines = CompositionMember::query()
->where('nested_composition_version_id', $version->id)
->with('compositionVersion.composition')
->get()
->map(fn (CompositionMember $member): string => ($member->compositionVersion->composition->designation ?? 'Programm').', Rolle '.$member->role)
->all();
$articles = ArticleRelease::query()
->where('root_composition_version_id', $version->id)
->with('article')
->get()
->map(fn (ArticleRelease $release): string => 'Lizenzartikel '.$release->article->code.', Stand '.$release->number)
->all();
$lines = [...$lines, ...$articles];
return new HtmlString($lines === [] ? 'In keinem anderen Programm und in keinem Lizenzartikel.' : implode('<br>', array_map(e(...), $lines)));
}),
CheckboxList::make('dimension_ids')->label('Fachliche Einordnung')
->options(fn (): array => self::dimensionOptions())
->columns(1)
->helperText('Wirkt auf die Suche in der Bibliothek und legt keine neue Fassung an.'),
FileUpload::make('thumbnail_upload')->label('Vorschaubild')
->disk('cms_incoming')->directory('vorschau')->visibility('private')->image()
->helperText('Ersetzt nur das Bild der Karte. Die Fassung und die Dateien bleiben unverändert.'),
Placeholder::make('history')->label('Aktuelle Fassung')->content(function (): HtmlString {
/** @var Composition $composition */
$composition = $this->getRecord();
$lines = app(CatalogReading::class)->compositionMembers($composition);
return new HtmlString(collect($lines)->map(fn (string $line): string => e($line))->implode('<br>'));
}),
Placeholder::make('pillars')->label('Säulen der Medien')->content(function (): HtmlString {
/** @var Composition $composition */
$composition = $this->getRecord();
$lines = app(CatalogReading::class)->memberPillars($composition);
return new HtmlString(collect($lines)->map(fn (string $line): string => e($line))->implode('<br>'));
}),
Repeater::make('members')
->label('Bausteine der neuen Fassung')
->schema([
TextInput::make('role')->label('Rolle')->placeholder('Film, Merkblatt, Übung')->required(),
Select::make('target')->label('Vorhandener Inhalt')->required()->searchable()
->options(fn (): array => CatalogOptions::assignmentTargets($this->getRecord()->getKey()))
->helperText('Titel, Inhaltsart und Fassungsnummer. Es wird genau diese Fassung verwendet.'),
])
->minItems(1)
->reorderable()
->addActionLabel('Baustein hinzufügen')
->helperText('Eine Zeile entfernen nimmt den Baustein nur aus der neuen Fassung. Eine neuere Medienfassung gilt erst, wenn du sie hier auswählst.'),
TextInput::make('note')->label('Notiz zur neuen Fassung'),
]);
}
protected function getHeaderActions(): array
{
return [
Action::make('displayRelease')
->label('Zur Anzeige freigeben')
->requiresConfirmation()
->visible(function (): bool {
$version = $this->currentReadyVersion();
return $version !== null && ! app(CompositionDisplayRelease::class)->isReleased($version);
})
->action(function (): void {
$version = $this->currentReadyVersion();
$actor = Filament::auth()->user();
abort_unless($version !== null && $actor instanceof User, 403);
app(CompositionDisplayRelease::class)->release($version, $actor);
Notification::make()->title('Die aktuelle Fassung ist zur Anzeige freigegeben.')->success()->send();
}),
Action::make('displayRevoke')
->label('Anzeigefreigabe zurücknehmen')
->color('danger')
->requiresConfirmation()
->visible(function (): bool {
$version = $this->currentReadyVersion();
return $version !== null && app(CompositionDisplayRelease::class)->isReleased($version);
})
->action(function (): void {
$version = $this->currentReadyVersion();
$actor = Filament::auth()->user();
abort_unless($version !== null && $actor instanceof User, 403);
app(CompositionDisplayRelease::class)->revoke($version, $actor);
Notification::make()->title('Die Anzeigefreigabe dieser Fassung ist zurückgenommen.')->success()->send();
}),
];
}
protected function getSaveFormAction(): Action
{
return parent::getSaveFormAction()->label('Neue Fassung veröffentlichen');
}
protected function getSavedNotificationTitle(): ?string
{
return $this->savedTitle ?? 'Die neue Fassung ist veröffentlicht.';
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeFill(array $data): array
{
/** @var Composition $composition */
$composition = $this->getRecord();
$version = $composition->versions()
->where('status', ContentVersionStatus::Bereit)
->orderByDesc('number')
->with('members')
->first();
$members = [];
foreach ($version?->members ?? [] as $member) {
$target = $member->content_element_version_id
? 'element:'.$member->content_element_version_id
: 'composition:'.$member->nested_composition_version_id;
$members[] = ['role' => $member->role, 'target' => $target];
}
$kind = $composition->kind;
return [
'designation' => $composition->designation,
'display_title' => $composition->display_title,
'summary' => $composition->summary,
'kind' => $kind instanceof CompositionKind ? $kind->value : $kind,
'editorial_content_kind_id' => $composition->editorial_content_kind_id,
'learning_goal' => $version?->learning_goal,
'duration_minutes' => $version?->duration_minutes,
'material_note' => $version?->material_note,
'dimension_ids' => IdentityDimensionValue::query()
->where('subject_type', $composition->getMorphClass())
->where('subject_id', $composition->id)
->where('origin', 'direkt')
->pluck('editorial_dimension_value_id')
->all(),
'members' => $members,
'note' => null,
];
}
/**
* @param array<string, mixed> $data
*/
protected function handleRecordUpdate(Model $record, array $data): Model
{
/** @var Composition $record */
try {
$kind = CompositionKind::from($data['kind']);
$record->designation = trim((string) $data['designation']);
app(IdentityProfile::class)->fill($record, [
'display_title' => $data['display_title'] ?? null,
'summary' => $data['summary'] ?? null,
], auth()->user());
$record->kind = $kind;
if (array_key_exists('editorial_content_kind_id', $data)) {
$record->editorial_content_kind_id = filled($data['editorial_content_kind_id'] ?? null)
? (int) $data['editorial_content_kind_id']
: null;
}
if (is_string($data['thumbnail_upload'] ?? null) && $data['thumbnail_upload'] !== '') {
$record->thumbnail_path = $data['thumbnail_upload'];
$record->thumbnail_error = null;
$record->thumbnail_alt = $record->designation;
}
$record->save();
if (array_key_exists('dimension_ids', $data)) {
$this->syncDimensions($record, array_map(intval(...), $data['dimension_ids'] ?? []));
}
$members = [];
foreach ($data['members'] as $member) {
if (! is_string($member['target'] ?? null) || ! str_contains($member['target'], ':')) {
throw new DomainRuleException('Jeder Baustein braucht eine Fassung.');
}
[$type, $id] = explode(':', $member['target'], 2);
$target = $type === 'composition'
? CompositionVersion::query()->findOrFail($id)
: ContentElementVersion::query()->findOrFail($id);
$members[] = ['role' => $member['role'], 'target' => $target];
}
$note = is_string($data['note'] ?? null) ? trim($data['note']) : '';
$current = $this->currentReadyVersion();
$didactic = [
'learning_goal' => $this->blankToNull(array_key_exists('learning_goal', $data) ? $data['learning_goal'] : $current?->learning_goal),
'duration_minutes' => $this->minutes(array_key_exists('duration_minutes', $data) ? $data['duration_minutes'] : $current?->duration_minutes),
'material_note' => $this->blankToNull(array_key_exists('material_note', $data) ? $data['material_note'] : $current?->material_note),
];
if ($note !== '' || ! $this->sameMembers($record, $members) || $this->didacticChanged($current, $didactic)) {
$actor = Filament::auth()->user();
app(ContentService::class)->publishComposition(
$record,
$members,
$actor instanceof User ? $actor : null,
$note !== '' ? $note : null,
$didactic,
);
$this->savedTitle = 'Die neue Fassung ist veröffentlicht. Die bisherige Fassung bleibt erhalten.';
} else {
$this->savedTitle = 'Bezeichnung und Art sind gespeichert. Die Bausteine sind unverändert, deshalb gibt es keine neue Fassung.';
}
} catch (DomainRuleException $exception) {
Notification::make()->title($exception->getMessage())->danger()->send();
throw new Halt;
}
return $record;
}
protected function afterSave(): void
{
$this->getRecord()->unsetRelations();
$this->getRecord()->refresh();
$this->fillForm();
}
protected function getRedirectUrl(): ?string
{
/** @var Composition $record */
$record = $this->getRecord();
$kind = $record->kind instanceof CompositionKind ? $record->kind : CompositionKind::from((string) $record->kind);
$resource = match ($kind) {
CompositionKind::Kurs => CourseResource::class,
CompositionKind::Kombination => CombinationResource::class,
CompositionKind::Uebung => ExerciseResource::class,
};
if ($resource !== static::getResource()) {
return $resource::getUrl('edit', ['record' => $record]);
}
return null;
}
/**
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
*/
private function currentReadyVersion(): ?CompositionVersion
{
/** @var Composition $composition */
$composition = $this->getRecord();
return $composition->versions()
->where('status', ContentVersionStatus::Bereit)
->orderByDesc('number')
->first();
}
private function sameMembers(Composition $composition, array $members): bool
{
$version = $composition->versions()
->where('status', ContentVersionStatus::Bereit)
->orderByDesc('number')
->with('members')
->first();
if ($version === null) {
return false;
}
$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 => $member['role'].'|'.($member['target'] instanceof ContentElementVersion ? 'element:' : 'composition:').$member['target']->id,
$members,
));
return $current === $next;
}
/**
* @param array{learning_goal: mixed, duration_minutes: mixed, material_note: mixed} $didactic
*/
private function didacticChanged(?CompositionVersion $version, array $didactic): bool
{
if ($version === null) {
return true;
}
$storedMinutes = $version->duration_minutes === null ? null : (int) $version->duration_minutes;
return $version->learning_goal !== $didactic['learning_goal']
|| $version->material_note !== $didactic['material_note']
|| $storedMinutes !== $didactic['duration_minutes'];
}
private function minutes(mixed $value): ?int
{
if ($value === null || $value === '') {
return null;
}
return (int) $value;
}
private function blankToNull(mixed $value): ?string
{
if (! is_string($value)) {
return null;
}
$value = trim($value);
return $value === '' ? null : $value;
}
/**
* @param list<int> $ids
*/
private 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');
}
}
/**
* @return array<int, string>
*/
private static function dimensionOptions(): array
{
$options = [];
foreach (EditorialDimension::query()->with('values')->orderBy('label')->get() as $dimension) {
foreach ($dimension->values as $value) {
$options[$value->id] = $dimension->label.': '.$value->label;
}
}
return $options;
}
private function statusText(): string
{
/** @var Composition $composition */
$composition = $this->getRecord();
$version = $this->currentReadyVersion();
if ($version === null) {
return 'Noch keine technisch bereite Fassung. Speichern legt die erste Fassung an.';
}
$released = app(CompositionDisplayRelease::class)->isReleased($version);
$older = $composition->versions()->where('number', '<', $version->number)->orderBy('number')->pluck('number')->all();
$history = $older === [] ? 'Es gibt keine ältere Fassung.' : 'Ältere Fassungen: '.implode(', ', $older).'.';
return 'Fassung '.$version->number.' ist technisch bereit. '
.($released ? 'Sie ist zur Anzeige freigegeben. ' : 'Sie ist noch nicht zur Anzeige freigegeben. ')
.$history;
}
private function outlineHtml(): string
{
$version = $this->currentReadyVersion();
if ($version === null) {
return 'Die Gliederung erscheint, sobald eine Fassung bereit ist.';
}
$lines = [];
$this->outlineLines(app(CompositionStructureReader::class)->tree($version), 0, $lines);
return $lines === [] ? 'Diese Fassung hat noch keine Bestandteile.' : implode('<br>', array_map(e(...), $lines));
}
/**
* @param list<StructureNode> $nodes
* @param list<string> $lines
*/
private function outlineLines(array $nodes, int $depth, array &$lines): void
{
foreach ($nodes as $node) {
$lines[] = str_repeat('– ', $depth).$node->role.': '.$node->title;
$this->outlineLines($node->children, $depth + 1, $lines);
}
}
}