Files
laraundfelix/app/Filament/Resources/ContentElements/Pages/EditContentElement.php
T
LarsandClaude Sonnet 5.5 9fbd933e1e Speichere formatierte Texte als bereinigtes HTML mit einem Editor (ADR-50)
Ein Baustein (FormattedText) bereinigt, bringt Werte in die kanonische Form und
wandelt Klartext des Altbestands; RichField ist der eine Editor, ManagesRichFields
verbindet ihn mit den Arbeitsplätzen. Formatiert sind Texte der Übungen und
Textbausteine, Kurzbeschreibung und Beschreibung, Lernziel und Ausstattung.
Mitgliederansicht und PDF zeigen fett, kursiv, Listen, Überschrift, Zitat und Link
(PDF: schräge Schnitte, nur wenn gebraucht). Das Livewire-Limit für verschachtelte
Pfade steigt auf 30, weil Aufzählungen sonst abgelehnt werden.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 23:45:54 +01:00

266 lines
13 KiB
PHP

<?php
namespace App\Filament\Resources\ContentElements\Pages;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\EditorialVocabulary;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\IdentityDimension;
use App\Domain\Catalog\IdentityDimensionValue;
use App\Domain\Catalog\IdentityProfile;
use App\Domain\Catalog\Pillar;
use App\Domain\Catalog\PillarService;
use App\Domain\Catalog\ReleaseContent;
use App\Domain\Media\ThumbnailRef;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Support\ElementRevision;
use App\Filament\Support\MediumForm;
use App\Filament\Support\ReportsDomainRules;
use App\Filament\Support\RichField;
use App\Jobs\DeriveThumbnail;
use Filament\Actions\Action;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
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;
/**
* Früheres Gesamtformular. Texte und Einordnung bearbeitet die gemeinsame Redaktion, Datei und Fassungen der
* Medieneditor; ein zweiter Editor für dieselben Felder ist nach Dokument 14 nicht zulässig. Die Adresse bleibt
* für alte Lesezeichen erhalten und führt nach der Rechteprüfung in die Redaktion des Mediums.
*/
class EditContentElement extends EditRecord
{
use ReportsDomainRules;
protected static string $resource = ContentElementResource::class;
public function mount(int|string $record): void
{
parent::mount($record);
$this->redirect(ContentElementResource::getUrl('view', ['record' => $this->getRecord(), 'redaktion' => 1]));
}
public function getSubheading(): string|Htmlable|null
{
return 'Titel, Beschreibung, Hinweise und Vorschaubild gehören zum Medium. Ein Text bleibt dieselbe Fassung, solange er nicht freigegeben und verwendet wird.';
}
public function form(Schema $schema): Schema
{
/** @var ContentElement $element */
$element = $this->getRecord();
return $schema->columns(1)->components([
Placeholder::make('open')->label('Medium')->content(function (): HtmlString {
$url = ContentElementResource::getUrl('view', ['record' => $this->getRecord()]);
return new HtmlString('<a href="'.e($url).'">Medium und Fassungen ansehen</a>');
}),
...MediumForm::fields(creating: false, element: $element),
TextInput::make('display_title')->label('Anzeigetitel')
->helperText('Erscheint in der Bibliothek. Leer lässt den Arbeitstitel stehen. Speichern legt keine Fassung an.'),
RichField::make('summary', 'Kurzbeschreibung', live: false),
Select::make('editorial_content_kind_id')
->label('Fachliche Materialart')
->options(fn (): array => app(EditorialVocabulary::class)->kindOptions('medium', $this->getRecord()->editorial_content_kind_id !== null ? (int) $this->getRecord()->editorial_content_kind_id : null))
->nullable()
->helperText('Optional für Bibliothek und Website. Ändert weder die Ausgabeart noch eine Fassung.'),
Placeholder::make('usage')->label('Verwendung')->content(function (): HtmlString {
/** @var ContentElement $element */
$element = $this->getRecord();
$versionIds = $element->versions()->pluck('id');
$compositionIds = [];
foreach ($element->versions as $version) {
$compositionIds = [...$compositionIds, ...app(ContentService::class)->containingCompositionIds($version)];
}
$names = Composition::query()->whereIn('id', array_unique($compositionIds))->orderBy('designation')->pluck('designation')->all();
$articles = ReleaseContent::query()
->whereIn('content_element_version_id', $versionIds)
->with('release.article')
->get()
->map(fn (ReleaseContent $content): string => 'Lizenzartikel '.($content->release->article->code ?? ''))
->unique()
->all();
$lines = [...array_map(fn (string $name): string => 'Enthalten in '.$name, $names), ...$articles];
return new HtmlString($lines === [] ? 'Noch in keinem Modul, Programm oder Lizenzartikel.' : implode('<br>', array_map(e(...), $lines)));
}),
CheckboxList::make('dimension_ids')->label('Fachliche Einordnung')
->options(function (): array {
$options = [];
foreach (app(EditorialVocabulary::class)->dimensionGroups($this->getRecord(), IdentityDimensionValue::query()
->where('subject_type', $this->getRecord()->getMorphClass())
->where('subject_id', $this->getRecord()->getKey())
->pluck('editorial_dimension_value_id')->map(fn ($id): int => (int) $id)->all()) as $dimension) {
foreach ($dimension['values'] as $value) {
$options[$value['id']] = $dimension['label'].': '.$value['label'];
}
}
return $options;
})
->helperText('Wirkt auf die Suche und legt keine neue Fassung an.'),
Placeholder::make('thumbnail_current')->label('Aktuelles Vorschaubild')->content(function (): HtmlString {
/** @var ContentElement $element */
$element = $this->getRecord();
$url = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
$caption = match ($element->thumbnail_source) {
'eigen' => 'Eigenes Vorschaubild.',
'datei' => 'Vorschaubild aus der Datei des Mediums.',
default => '',
};
if (is_string($element->thumbnail_source) && preg_match('/^frame:\d+@([\d.]+)$/', $element->thumbnail_source, $match) === 1) {
$caption = 'Vorschaubild aus dem Film bei '.$match[1].' Sekunden.';
}
if ($url === null) {
return new HtmlString('Noch kein Vorschaubild. Eine Filmstelle wählst du beim Ansehen des Mediums.');
}
return new HtmlString('<img src="'.e($url).'" alt="" style="width: 16rem; height: auto;">'.($caption !== '' ? '<p>'.e($caption).'</p>' : ''));
}),
CheckboxList::make('pillars')
->label('Fachliche Säulen')
->options(fn (): array => Pillar::query()->orderBy('name')->pluck('name', 'id')->all())
->helperText('Ein Medium kann mehreren Säulen zugeordnet sein. Weitere Säulen legst du unter Fachliche Säulen an.')
->columns(1),
]);
}
public static function uploadField(): FileUpload
{
return MediumForm::fileField();
}
protected function getHeaderActions(): array
{
return [
Action::make('view')
->label('Ansehen')
->url(fn (): string => ContentElementResource::getUrl('view', ['record' => $this->getRecord()])),
Action::make('revise')
->label('Neue Fassung anlegen')
->schema(fn (): array => ElementRevision::fields($this->getRecord()))
->action(function (array $data): void {
$this->report(function () use ($data): string {
/** @var ContentElement $element */
$element = $this->getRecord();
return ElementRevision::publish($element, $data);
}, 'Die neue Fassung ist angelegt.');
$this->getRecord()->unsetRelation('versions');
}),
Action::make('delete')
->label('Löschen')
->color('danger')
->requiresConfirmation()
->visible(fn (): bool => $this->getRecord()->versions()->doesntExist())
->action(function (): void {
$this->getRecord()->delete();
$this->redirect(ContentElementResource::getUrl('index'));
}),
];
}
protected function getSaveFormAction(): Action
{
return parent::getSaveFormAction()->label('Speichern');
}
protected function getSavedNotificationTitle(): ?string
{
return 'Gespeichert. Es gibt keine neue Fassung.';
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeFill(array $data): array
{
return [
'working_title' => $this->getRecord()->working_title,
'thumbnail_alt' => $this->getRecord()->thumbnail_alt,
'body' => FormattedText::html($this->getRecord()->versions()->orderByDesc('number')->first()?->body),
'display_title' => $this->getRecord()->display_title,
'description' => FormattedText::html($this->getRecord()->description),
'usage_note' => $this->getRecord()->usage_note,
'license_note' => $this->getRecord()->license_note,
'summary' => FormattedText::html($this->getRecord()->summary),
'editorial_content_kind_id' => $this->getRecord()->editorial_content_kind_id,
'dimension_ids' => IdentityDimensionValue::query()
->where('subject_type', $this->getRecord()->getMorphClass())
->where('subject_id', $this->getRecord()->id)
->where('origin', 'direkt')
->pluck('editorial_dimension_value_id')
->all(),
'pillars' => $this->getRecord()->pillars()->pluck('pillars.id')->all(),
];
}
/**
* @param array<string, mixed> $data
*/
protected function handleRecordUpdate(Model $record, array $data): Model
{
/** @var ContentElement $record */
try {
$description = FormattedText::same((string) ($data['description'] ?? ''), $record->description)
? $record->description
: (FormattedText::canonical((string) ($data['description'] ?? '')) ?: null);
app(ContentService::class)->describe($record, (string) $data['working_title'], $description);
app(IdentityProfile::class)->fill($record, [
'display_title' => $data['display_title'] ?? null,
'summary' => FormattedText::same((string) ($data['summary'] ?? ''), $record->summary)
? $record->summary
: (FormattedText::canonical((string) ($data['summary'] ?? '')) ?: null),
'usage_note' => $data['usage_note'] ?? null,
'license_note' => $data['license_note'] ?? null,
'thumbnail_alt' => $data['thumbnail_alt'] ?? null,
], auth()->user());
if ($record->output_class === 'text' && is_string($data['body'] ?? null)) {
$latest = $record->versions()->orderByDesc('number')->first();
if ($latest instanceof ContentElementVersion && ! FormattedText::same($data['body'], $latest->body)) {
app(ContentService::class)->reviseElementContent($latest, FormattedText::canonical($data['body']));
}
}
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;
$record->save();
}
if (is_string($data['thumbnail_upload'] ?? null) && $data['thumbnail_upload'] !== '') {
$record->thumbnail_error = null;
$record->save();
DeriveThumbnail::dispatch('element', $record->id, $data['thumbnail_upload']);
}
if (array_key_exists('dimension_ids', $data)) {
app(IdentityDimension::class)->replaceOffered($record, array_map(intval(...), $data['dimension_ids'] ?? []));
}
app(PillarService::class)->assign($record, array_map(intval(...), $data['pillars'] ?? []));
} catch (DomainRuleException $exception) {
Notification::make()->title($exception->getMessage())->danger()->send();
throw new Halt;
}
return $record;
}
}