Files
laraundfelix/app/Filament/Resources/LicenseArticles/Pages/ViewLicenseArticle.php
T
LarsandClaude Sonnet 5.5 657578455f
CI Feature / test (push) Successful in 3m35s
Deploy Test / test (push) Successful in 3m31s
Deploy Test / deploy (push) Successful in 27s
Lasse Vergaben auf Abruf und bei Registrierung nicht als Shop-Option aendern
Der Abschnitt "Im Shop verkaufen" listet alle Angebote eines Artikels. Fuer
Vergaben auf Abruf oder bei Registrierung bot er "Aendern" und "Aus dem
Verkauf nehmen" an; "Aendern" haette sie zum Kauf umgestellt. Jetzt zeigt der
Abschnitt sie nur noch mit dem Hinweis, dass sie am Angebot bearbeitet
werden, die Aktionen liefern 404, und reviseArticleOption lehnt sie ab.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 22:35:02 +01:00

633 lines
28 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\LicenseArticles\Pages;
use App\Domain\Catalog\ArticleService;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\EditorialProfileReader;
use App\Domain\Catalog\EditorialVocabulary;
use App\Domain\Catalog\IdentityDimension;
use App\Domain\Catalog\IdentityDimensionValue;
use App\Domain\Catalog\IdentityProfile;
use App\Domain\Catalog\LicenceScope;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService;
use App\Domain\Catalog\OfferStatus;
use App\Domain\Catalog\RightsProfileVersion;
use App\Domain\Catalog\StatusValue;
use App\Domain\Commerce\Money;
use App\Domain\Commerce\ProductOptions;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Resources\LicenseArticles\LicenseArticleResource;
use App\Filament\Resources\Offers\OfferResource;
use App\Filament\Support\AssignsPillars;
use App\Filament\Support\CatalogLabels;
use App\Filament\Support\CatalogOptions;
use App\Filament\Support\EditorialCatalog;
use App\Filament\Support\ManagesEditorialSurface;
use App\Filament\Support\ManagesRichFields;
use App\Filament\Support\PublicationReadiness;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\Utilities\Get;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Model;
class ViewLicenseArticle extends ViewRecord
{
use AssignsPillars;
use ManagesEditorialSurface;
use ManagesRichFields;
use ReportsDomainRules;
protected static string $resource = LicenseArticleResource::class;
public string $workingTitle = '';
public string $displayTitle = '';
public string $teaser = '';
public string $summary = '';
public string $descriptionText = '';
public string $searchTerms = '';
public int|string|null $kindId = null;
public ?int $releaseBeforeSave = null;
public int $releaseCountBeforeSave = 0;
/** @var list<int|string> */
public array $dimensionIds = [];
public function mount(int|string $record): void
{
parent::mount($record);
$this->fillLicenseEditorial();
}
public function canEditEditorial(): bool
{
return LicenseArticleResource::keeper();
}
public function canViewEditorial(): bool
{
return LicenseArticleResource::keeper();
}
public function getTitle(): string|Htmlable
{
return $this->redaktionTitel();
}
public function saveLicenseEditorial(): void
{
$this->saveRedaktion();
}
protected function saveRedaktionTexte(): bool
{
$this->guardEditorial();
/** @var LicenseArticle $article */
$article = $this->getRecord();
$this->releaseBeforeSave = $article->current_release_id;
$this->releaseCountBeforeSave = $article->releases()->count();
$kindError = app(EditorialVocabulary::class)->kindError(
'lizenzartikel',
filled($this->kindId) ? (int) $this->kindId : null,
$article->editorial_content_kind_id !== null ? (int) $article->editorial_content_kind_id : null,
);
if ($kindError !== null) {
$this->deskFeedback = $kindError;
$this->redaktionFehlerFeld = 'kindId';
return false;
}
app(IdentityProfile::class)->fill($article, [
'working_title' => $this->workingTitle,
'display_title' => $this->displayTitle,
'teaser' => $this->teaser,
'summary' => $this->richStore('summary', $article->summary),
'description' => $this->richStore('descriptionText', $article->description),
'search_terms' => $this->searchTerms,
'editorial_content_kind_id' => filled($this->kindId) ? (int) $this->kindId : null,
], auth()->user());
app(IdentityDimension::class)->replaceOffered($article, array_map(intval(...), $this->dimensionIds));
$this->persistPillarIds($article);
$article->refresh();
$this->fillLicenseEditorial();
return true;
}
protected function redaktionSavedMessage(): string
{
/** @var LicenseArticle $article */
$article = $this->getRecord();
return $article->current_release_id === $this->releaseBeforeSave && $article->releases()->count() === $this->releaseCountBeforeSave
? 'Gespeichert. Stand, Preis und Rechte bleiben unverändert.'
: 'Gespeichert. Prüfe den Artikelstand, er hat sich geändert.';
}
protected function resetRedaktionTexte(): void
{
$this->fillLicenseEditorial();
}
public function einordnungUnsaved(): bool
{
/** @var LicenseArticle $article */
$article = $this->getRecord()->fresh() ?? $this->getRecord();
$kind = filled($this->kindId) ? (int) $this->kindId : null;
$storedKind = $article->editorial_content_kind_id !== null ? (int) $article->editorial_content_kind_id : null;
if ($kind !== $storedKind) {
return true;
}
$stored = IdentityDimensionValue::query()
->where('subject_type', $article->getMorphClass())
->where('subject_id', $article->getKey())
->where('origin', 'direkt')
->pluck('editorial_dimension_value_id')
->map(fn ($id): int => (int) $id)
->all();
$current = array_map(intval(...), $this->dimensionIds);
sort($stored);
sort($current);
return $stored !== $current || $this->pillarsUnsaved($article);
}
/**
* @return array{art: string, fuer: string, liste: string, zurueck: string, typ: ?string, umfang: string}
*/
public function redaktionKopf(): array
{
return [
'art' => 'Lizenzartikel',
'fuer' => 'den Lizenzartikel',
'liste' => 'Lizenzartikel',
'zurueck' => 'Zurück zum Lizenzartikel',
'typ' => null,
'umfang' => '„Redaktion speichern“ sichert die eigenen Texte, Präsentationsmedien und Einordnung dieses Lizenzartikels. Leere Angaben übernehmen weiter die fachliche Quelle. Stand, Preis und Rechte bleiben unverändert.',
];
}
public function redaktionTitel(): string
{
foreach ([$this->displayTitle, $this->workingTitle] as $title) {
if (trim($title) !== '') {
return trim($title);
}
}
$profile = $this->editorialProfile('artikel');
if ($profile->value('display_title') !== null) {
return (string) $profile->value('display_title');
}
$source = $profile->source;
return $source !== null ? $this->sourceTitle($source) : (string) $this->getRecord()->code;
}
/**
* @return array<string, string>
*/
protected function richFelder(): array
{
return ['summary' => 'Kurzbeschreibung', 'descriptionText' => 'Beschreibung'];
}
/**
* @return list<array<string, mixed>>
*/
public function redaktionFelder(): array
{
/** @var LicenseArticle $article */
$article = $this->getRecord();
$source = app(EditorialProfileReader::class)->sourceOf($article);
$sourceTitle = $source !== null ? $this->sourceTitle($source) : null;
$stored = fn (string $column): string => (string) ($article->getAttribute($column) ?? '');
$quelle = fn (string $column): ?array => $sourceTitle === null ? null : [
'titel' => $sourceTitle,
'wert' => (string) ($source->getAttribute($column) ?? ''),
];
return [
['id' => 'arbeitstitel', 'label' => 'Interner Arbeitstitel', 'model' => 'workingTitle', 'kind' => 'text', 'stored' => $stored('working_title'), 'hilfe' => 'Nur in der Verwaltung sichtbar.'],
['id' => 'anzeigename', 'label' => 'Name', 'model' => 'displayTitle', 'kind' => 'text', 'stored' => $stored('display_title'), 'quelle' => $quelle('display_title')],
['id' => 'teaser', 'label' => 'Teaser', 'model' => 'teaser', 'kind' => 'textarea', 'rows' => 2, 'stored' => $stored('teaser'), 'quelle' => $quelle('teaser')],
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'rich', 'stored' => $stored('summary'), 'quelle' => $quelle('summary')],
['id' => 'beschreibung', 'label' => 'Beschreibung', 'model' => 'descriptionText', 'kind' => 'rich', 'stored' => $stored('description'), 'quelle' => $quelle('description')],
['id' => 'suche', 'label' => 'Suchbegriffe', 'model' => 'searchTerms', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('search_terms'), 'quelle' => $quelle('search_terms')],
];
}
/**
* @return array{titel: string, art: string, fuer: string, url: ?string}|null
*/
public function redaktionQuelle(): ?array
{
/** @var LicenseArticle $article */
$article = $this->getRecord();
$source = app(EditorialProfileReader::class)->sourceOf($article);
if ($source === null) {
return null;
}
$url = match (true) {
$source instanceof Composition => EditorialCatalog::editUrl($source),
$source instanceof ContentElement => ContentElementResource::getUrl('view', ['record' => $source]),
default => null,
};
return [
'titel' => $this->sourceTitle($source),
'art' => $source instanceof ContentElement ? 'Medium' : ($source instanceof Composition && $source->kind === CompositionKind::Kurs ? 'Programm' : 'Modul'),
'fuer' => 'diesen Lizenzartikel',
'url' => $url,
];
}
public function redaktionOhneQuelle(): string
{
return 'Keine eindeutige fachliche Quelle. Es wird nichts aus einem Modul, Programm oder Medium übernommen.';
}
/**
* @return array{model: string, options: array<int|string, string>, hilfe: string}
*/
public function einordnungArt(): array
{
return [
'model' => 'kindId',
'options' => app(EditorialVocabulary::class)->kindOptions('lizenzartikel', $this->getRecord()->editorial_content_kind_id !== null ? (int) $this->getRecord()->editorial_content_kind_id : null),
'hilfe' => 'Die Einordnung des Artikels ändert weder die Quelle noch den Preis.',
];
}
/**
* @return list<array{legend: string, model: string, values: list<array{id: int, label: string}>}>
*/
public function einordnungGruppen(): array
{
$groups = array_map(fn (array $group): array => [
'legend' => $group['label'],
'model' => 'dimensionIds',
'values' => $group['values'],
], $this->licenseDimensionGroups());
$pillars = $this->pillarGroup();
return $pillars === null ? $groups : [$pillars, ...$groups];
}
private function sourceTitle(Model $source): string
{
$title = $source->getAttribute('display_title') ?: ($source->getAttribute('working_title') ?? $source->getAttribute('designation'));
return (string) $title;
}
/**
* @return list<array{label: string, values: list<array{id: int, label: string}>}>
*/
public function licenseDimensionGroups(): array
{
return 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());
}
private function fillLicenseEditorial(): void
{
/** @var LicenseArticle $article */
$article = $this->getRecord();
$this->workingTitle = (string) ($article->working_title ?? '');
$this->displayTitle = (string) ($article->display_title ?? '');
$this->teaser = (string) ($article->teaser ?? '');
$this->summary = (string) ($article->summary ?? '');
$this->descriptionText = (string) ($article->description ?? '');
$this->searchTerms = (string) ($article->search_terms ?? '');
$this->kindId = $article->editorial_content_kind_id;
$this->dimensionIds = IdentityDimensionValue::query()
->where('subject_type', $article->getMorphClass())
->where('subject_id', $article->id)
->where('origin', 'direkt')
->pluck('editorial_dimension_value_id')
->all();
$this->loadPillarIds($article);
}
protected function getHeaderActions(): array
{
return [];
}
public function releaseAction(): Action
{
return Action::make('release')
->label(fn (): string => $this->isFirstStand() ? 'Inhalt festlegen' : 'Neuen Stand veröffentlichen')
->modalHeading(fn (): string => $this->isFirstStand() ? 'Inhalt festlegen: ersten Stand veröffentlichen' : 'Neuen Stand veröffentlichen')
->modalDescription(fn (): string => $this->isFirstStand()
? 'Der Stand legt fest, welche Inhalte dieser Lizenzartikel lizenziert: der gewählte Inhalt samt allem, was er enthält. Er ist danach unveränderlich. Pakete und Angebote können den Artikel danach verwenden; verkauft wird er erst über ein Angebot.'
: 'Ein neuer Stand ersetzt den aktuellen für künftige Ausgaben. Bestehende Käufer erhalten ihn im Rahmen ihrer Lizenz; frühere Stände bleiben gespeichert.')
->modalSubmitActionLabel('Stand veröffentlichen')
->fillForm(fn (): array => $this->isFirstStand() ? ['classification' => 'Erster Stand dieses Lizenzartikels.'] : [])
->schema([
Select::make('root')->label('Freigegebener Inhalt')
->options(fn (): array => CatalogOptions::assignmentTargets())
->searchable()
->required()
->helperText(fn (): string => CatalogOptions::assignmentTargets() === []
? 'Es gibt noch keinen freigegebenen Inhalt. Gib zuerst ein Medium, Modul oder Programm frei.'
: 'Medien, Module und Programme mit freigegebener Fassung. Bei Modulen und Programmen gehört alles Enthaltene zum Stand.'),
Textarea::make('classification')->label('Einordnung')
->required(fn (): bool => ! $this->isFirstStand())
->helperText(fn (): string => $this->isFirstStand()
? 'Beim ersten Stand genügt der vorgegebene Text.'
: 'Warum dies derselbe Lizenzartikel bleibt und kein neues Produkt ist.'),
TextInput::make('change_note')->label('Änderungshinweis')
->visible(fn (): bool => ! $this->isFirstStand()),
])
->action(function (array $data): void {
$this->report(function () use ($data): string {
/** @var LicenseArticle $article */
$article = $this->getRecord();
[$type, $id] = explode(':', $data['root'], 2);
$root = $type === 'composition'
? CompositionVersion::query()->findOrFail($id)
: ContentElementVersion::query()->findOrFail($id);
$release = app(ArticleService::class)->publishRelease(
$article,
$root,
(string) ($data['classification'] ?? 'Erster Stand dieses Lizenzartikels.'),
$data['change_note'] ?? null,
);
$report = $release->impact_report ?? [];
$offers = $report['offers'] ?? [];
return 'Stand '.$release->number.' ist veröffentlicht. Inhalte: '.($report['contents'] ?? 0)
.', Inhaber: '.($report['holders'] ?? 0)
.', Angebote: '.(implode(', ', $offers) !== '' ? implode(', ', $offers) : 'keins').'.';
}, 'Der Artikel-Stand ist veröffentlicht.');
$this->refreshRecord();
});
}
public function withdrawAction(): Action
{
return Action::make('withdraw')
->label('Stand zurückziehen')
->schema([
Textarea::make('reason')->label('Begründung')->required(),
])
->action(function (array $data): void {
$this->report(function () use ($data): string {
$result = app(ArticleService::class)->withdraw($this->getRecord(), $data['reason']);
$current = $result['fallback_number'] === null
? 'Es gibt keinen früheren Stand.'
: 'Aktuell ist wieder Stand '.$result['fallback_number'].'.';
$holders = $result['holders'] === [] ? 'niemand' : implode(', ', $result['holders']);
return 'Der Stand ist zurückgezogen. '.$current.' Betroffen: '.$holders.'.';
}, 'Der Stand ist zurückgezogen.');
$this->refreshRecord();
});
}
/**
* Die Optionen dieses Artikels im Shop: Bezeichnung, Preis, Rechte, Nutzerkreis und Zustand je Option. Gelesen wird
* die aktive, sonst die letzte Fassung.
*
* @return list<array<string, mixed>>
*/
public function optionRows(): array
{
/** @var LicenseArticle $article */
$article = $this->getRecord();
$options = app(ProductOptions::class);
$offers = app(OfferService::class);
$rows = [];
foreach ($options->offersOfArticle($article) as $offer) {
$version = $offers->purchasableVersion($offer)
?? $offer->versions()->where('status', OfferStatus::Aktiv)->orderByDesc('number')->first()
?? $offer->versions()->orderByDesc('number')->first();
if ($version === null) {
continue;
}
$version->loadMissing('lines.rights.profile');
$active = StatusValue::of($version->status) === OfferStatus::Aktiv->value;
$buyable = $active && $offers->purchasableVersion($offer) !== null;
$rows[] = [
'offer' => $offer->id,
'name' => $offer->optionName(),
'price' => $version->price_cents === null ? 'kein Preis' : Money::format((int) $version->price_cents),
'licence' => LicenceScope::label($version->licence_scope, $version->trainer_count),
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
'rights' => (string) ($version->lines->first()?->rights?->profile?->name ?? '–'),
'number' => $version->number,
'active' => $active,
'kauf' => $version->grant_kind === 'kauf',
'buyable' => $buyable,
'zustand' => match (true) {
$buyable => ['label' => 'Im Shop', 'ton' => 'gut'],
$active => ['label' => CatalogLabels::vergabe($version).' · nicht im Shop', 'ton' => 'neutral'],
default => ['label' => 'Nicht im Verkauf', 'ton' => 'leise'],
},
'page' => $buyable ? parse_url((string) $options->pageUrl($offer), PHP_URL_PATH) : null,
'url' => OfferResource::getUrl('view', ['record' => $offer]),
];
}
return $rows;
}
/** Ein Artikel lässt sich anbieten, wenn sein aktueller Stand veröffentlicht ist. */
public function canOffer(): bool
{
return app(PublicationReadiness::class)->articleUsable($this->getRecord());
}
/**
* Option hinzufügen oder ändern: Rechteprofil, Preis, Nutzerkreis und Eignung. Der Artikel steht fest, es gibt keine
* Auswahl von Artikel oder Inhalt. Mit dem Argument `offer` ändert die Aktion eine bestehende Option (nächste Fassung).
*/
public function optionAction(): Action
{
return Action::make('option')
->modalWidth('2xl')
->modalHeading(fn (array $arguments): string => isset($arguments['offer'])
? 'Option „'.$this->optionOf($arguments)->optionName().'“ ändern'
: 'Option hinzufügen: so wird der Artikel verkauft')
->modalDescription(fn (array $arguments): string => isset($arguments['offer'])
? 'Die Maske ist mit der letzten Fassung vorbelegt. Erst „Speichern und anbieten“ schaltet die Änderung öffentlich: Die bisherige Fassung wird beendet und bleibt gespeichert, neue Käufe nutzen die neue. Bereits begründete Berechtigungen und Bestellungen ändern sich nicht. „Abbrechen“ verwirft die Eingaben.'
: 'Eine Option ist eine Lizenz mit Rechteprofil und Preis. Der Artikel kann mehrere Optionen haben, zum Beispiel für Privatpersonen und für Vereine. Sie erscheinen gemeinsam auf der Produktseite des Artikels. „Abbrechen“ verwirft die Eingaben.')
->modalSubmitActionLabel('Speichern und anbieten')
->fillForm(fn (array $arguments): array => $this->optionForm($arguments))
->schema([
Select::make('rights_id')->label('Rechteprofil')
->options(fn (): array => CatalogOptions::rights())
->required()
->helperText('Was Käufer mit dem Artikel tun dürfen (ansehen, herunterladen, Nutzungszweck).'),
TextInput::make('price_euro')->label('Preis in Euro')->suffix('€')->required()
->helperText('Zum Beispiel 49,00. Ein Kauf braucht einen Preis über 0,00 €.'),
Select::make('holder_kind')->label('Geeignet für')->options([
'person' => 'Privatpersonen',
'organisation' => 'Organisationen und Vereine',
])->required()->live()
->helperText('Wähle die Eignung passend zum Rechteprofil: Organisationslizenzen brauchen institutionelle Rechte.'),
Select::make('licence_scope')->label('Nutzerkreis')
->options(LicenceScope::options())
->required()->live()
->helperText('Wie viele Trainer die Inhalte einsetzen dürfen. Der Download bleibt beim bestellenden Konto.'),
TextInput::make('trainer_count')->label('Anzahl Trainer')
->numeric()->minValue(2)->maxValue(LicenceScope::MAX_TRAINERS)->integer()
->required(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
->visible(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
->live(),
TextInput::make('option_label')->label('Bezeichnung der Option')
->maxLength(120)
->placeholder(fn (Get $get): string => OfferService::defaultOptionLabel($get('holder_kind'), $get('licence_scope'), $get('trainer_count')))
->helperText('So heißt die Option auf der Produktseite. Leer lassen übernimmt den grauen Vorschlag.'),
])
->action(function (array $data, array $arguments): void {
$this->report(function () use ($data, $arguments): string {
/** @var LicenseArticle $article */
$article = $this->getRecord();
$rights = RightsProfileVersion::query()->findOrFail($data['rights_id']);
$price = Money::parse($data['price_euro'] ?? null);
$label = filled($data['option_label'] ?? null)
? trim((string) $data['option_label'])
: OfferService::defaultOptionLabel($data['holder_kind'], $data['licence_scope'], $data['trainer_count'] ?? null);
$attributes = [
'holder_kind' => $data['holder_kind'],
'licence_scope' => $data['licence_scope'],
'trainer_count' => $data['trainer_count'] ?? null,
'price_cents' => $price,
];
$service = app(OfferService::class);
if (isset($arguments['offer'])) {
$offer = $this->optionOf($arguments);
$version = $service->reviseArticleOption($offer, $article, $rights, $attributes, $label);
} else {
$name = app(ProductOptions::class)->articleTitle($article).': '.$label;
$version = $service->offerArticle($article, $rights, $attributes, $name, $label);
$offer = $version->offer;
}
$page = app(ProductOptions::class)->pageUrl($offer);
return 'Die Option „'.$offer->optionName().'“ ist als Fassung '.$version->number.' aktiv und im Shop kaufbar'
.($page !== null ? ' unter '.parse_url($page, PHP_URL_PATH) : '').'.';
}, 'Die Option ist aktiv.');
$this->refreshRecord();
});
}
/** Eine Option aus dem Verkauf nehmen: nur die aktive Fassung dieser Option wird beendet. */
public function optionEndAction(): Action
{
return Action::make('optionEnd')
->color('danger')
->requiresConfirmation()
->modalHeading(fn (array $arguments): string => 'Option „'.$this->optionOf($arguments)->optionName().'“ aus dem Verkauf nehmen?')
->modalDescription('Die aktive Fassung wird beendet und bleibt gespeichert. Die Option ist danach nicht mehr kaufbar; in vorhandenen Warenkörben bleibt sie mit Hinweis sichtbar und blockiert den Abschluss, bis der Käufer sie entfernt. Bestehende Berechtigungen und Bestellungen ändern sich nicht. Andere Optionen des Artikels bleiben kaufbar.')
->modalSubmitActionLabel('Aus dem Verkauf nehmen')
->action(function (array $arguments): void {
$this->report(function () use ($arguments): string {
$offer = $this->optionOf($arguments);
$version = app(OfferService::class)->end($offer);
return 'Die Option „'.$offer->optionName().'“ ist aus dem Verkauf genommen (Fassung '.$version->number.' beendet).';
}, 'Die Option ist aus dem Verkauf genommen.');
$this->refreshRecord();
});
}
/**
* Die Option aus den Argumenten der Aktion, nur wenn sie zu diesem Artikel gehört.
*
* @param array<string, mixed> $arguments
*/
private function optionOf(array $arguments): Offer
{
/** @var LicenseArticle $article */
$article = $this->getRecord();
$offer = collect(app(ProductOptions::class)->offersOfArticle($article))->first(fn (Offer $offer): bool => $offer->id === (int) ($arguments['offer'] ?? 0)
&& $offer->versions()->orderByDesc('number')->value('grant_kind') === 'kauf');
// Vergaben auf Abruf oder bei Registrierung sind keine Shop-Optionen und werden am Angebot bearbeitet.
return $offer ?? abort(404);
}
/**
* @param array<string, mixed> $arguments
* @return array<string, mixed>
*/
private function optionForm(array $arguments): array
{
if (! isset($arguments['offer'])) {
$rights = array_keys(CatalogOptions::rights());
return [
'holder_kind' => 'person',
'licence_scope' => LicenceScope::SINGLE,
'rights_id' => count($rights) === 1 ? $rights[0] : null,
];
}
$offer = $this->optionOf($arguments);
$version = $offer->versions()->with('lines')->orderByDesc('number')->firstOrFail();
return [
'rights_id' => $version->lines->first()?->rights_profile_version_id,
'price_euro' => $version->price_cents === null ? null : number_format($version->price_cents / 100, 2, ',', ''),
'holder_kind' => $version->holder_kind,
'licence_scope' => $version->licence_scope,
'trainer_count' => $version->trainer_count,
'option_label' => $offer->option_label,
];
}
private function isFirstStand(): bool
{
return ! $this->getRecord()->releases()->exists();
}
private function refreshRecord(): void
{
$this->getRecord()->unsetRelations();
$this->getRecord()->refresh();
}
}