Biete Lizenzartikel mit mehreren Optionen direkt am Artikel an
CI Feature / test (push) Successful in 3m32s
Deploy Test / test (push) Successful in 3m23s
Deploy Test / deploy (push) Successful in 28s

Am Lizenzartikel gibt es den Abschnitt "Im Shop verkaufen": Er listet die
Optionen mit Preis, Rechten, Nutzerkreis und Zustand. "Option hinzufuegen"
fragt nur Rechteprofil, Preis, Eignung, Nutzerkreis und eine Bezeichnung ab;
Artikel, Inhalt und Vergabe stehen fest. Aendern und Aus dem Verkauf nehmen
laufen am selben Ort.

OfferService::offerArticle legt Angebot und erste Fassung in einer
Transaktion an, damit eine fehlgeschlagene Pruefung kein leeres Angebot
hinterlaesst. reviseArticleOption aktiviert die naechste Fassung und lehnt
Optionen anderer Artikel ab. Aus der Angebotsmaske entfaellt die Auswahl
"Programmfassung, die abgedeckt sein muss"; die Pruefung bleibt im Dienst.
Pakete und der Altbestand behalten die Angebotsmaske.
This commit is contained in:
Lars committed 2026-11-25 22:23:14 +01:00
1 parent 93ae01c986
commit 3b0b4c955e
9 files changed
+673 -18

No files matched your search

+58
View File
@@ -163,6 +163,64 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
});
}
/**
* Bietet einen Lizenzartikel als Kauf an: legt die Option (Angebot) an und aktiviert ihre erste Fassung in einem
* Schritt. Besteht eine Prüfung nicht (Stand, Preis, Rechte), bleibt kein leeres Angebot zurück.
*
* @param array<string, mixed> $attributes holder_kind, licence_scope, trainer_count, price_cents
*/
public function offerArticle(LicenseArticle $article, RightsProfileVersion $rights, array $attributes, string $name, ?string $label = null): OfferVersion
{
return DB::transaction(function () use ($article, $rights, $attributes, $name, $label): OfferVersion {
$offer = $this->create($name);
$this->setOptionLabel($offer, $label);
return $this->activate($offer, [['target' => $article, 'rights' => $rights]], [...$attributes, 'grant_kind' => 'kauf']);
});
}
/**
* Ändert eine Option eines Artikels: Die nächste Fassung wird aktiv, die bisherige bleibt gespeichert. Bedingungen,
* die die Maske nicht zeigt (Laufzeit, Steuerklasse), bleiben die der letzten Fassung. Die Option muss den Artikel
* als einzige Position verkaufen.
*
* @param array<string, mixed> $attributes holder_kind, licence_scope, trainer_count, price_cents
*/
public function reviseArticleOption(Offer $offer, LicenseArticle $article, RightsProfileVersion $rights, array $attributes, ?string $label = null): OfferVersion
{
return DB::transaction(function () use ($offer, $article, $rights, $attributes, $label): OfferVersion {
$latest = $offer->versions()->with('lines')->orderByDesc('number')->first();
if ($latest === null || $latest->lines->count() !== 1 || (int) $latest->lines->first()->license_article_id !== $article->id) {
throw new DomainRuleException('Diese Option gehört nicht zu diesem Lizenzartikel.');
}
$this->setOptionLabel($offer, $label);
return $this->activate($offer, [['target' => $article, 'rights' => $rights]], [
'term_rule' => $latest->term_rule,
'tax_class' => $latest->tax_class,
'dynamic' => (bool) $latest->dynamic,
...$attributes,
'grant_kind' => 'kauf',
]);
});
}
/**
* Vorschlag für die Bezeichnung einer Option, wenn keine eingegeben wird: Nutzerkreis und Eignung.
*/
public static function defaultOptionLabel(?string $holderKind, ?string $licenceScope, mixed $trainers): string
{
$scope = match ($licenceScope) {
LicenceScope::MULTI => 'Mehrfachlizenz ('.(int) $trainers.' Trainer)',
LicenceScope::SINGLE => 'Einzellizenz',
default => 'Lizenz',
};
return $scope.' für '.($holderKind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen');
}
/**
* Zieht die Option aus dem Verkauf zurück: Die aktive Fassung wird beendet und bleibt gespeichert. Bereits
* begründete Berechtigungen und Bestellungen ändern sich nicht; offene Warenkörbe zeigen die Position als
+17
View File
@@ -33,6 +33,23 @@ public function forArticle(LicenseArticle $article): array
return $this->optionsFor('a:'.$article->id);
}
/**
* Alle Optionen, die diesen Artikel als einzige Position verkaufen oder verkauften, auch beendete und solche ohne
* Preis (Verwaltung). Die öffentliche Seite zeigt davon nur die kaufbaren (`forArticle`).
*
* @return list<Offer>
*/
public function offersOfArticle(LicenseArticle $article): array
{
return Offer::query()
->whereHas('versions.lines', fn ($query) => $query->where('license_article_id', $article->id))
->orderBy('id')
->get()
->filter(fn (Offer $offer): bool => $this->groupKey($offer) === 'a:'.$article->id)
->values()
->all();
}
/**
* Kaufbare Optionen der Produktseite eines Pakets: Angebote, deren einzige Position eine Fassung dieses Pakets ist.
*
@@ -13,20 +13,32 @@
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;
@@ -409,6 +421,201 @@ public function withdrawAction(): Action
});
}
/**
* 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,
'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));
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();
@@ -24,7 +24,7 @@ class ListOffers extends ListRecords
public function getSubheading(): string|Htmlable|null
{
return 'Ein Angebot verbindet Artikel oder eine Paketfassung mit einem Rechteprofil. Die aufgelösten Berechtigungen stehen auf der Angebotsseite.';
return 'Ein Angebot ist eine Option zum Kauf: ein Artikel oder eine Paketfassung mit Rechteprofil und Preis. Optionen eines einzelnen Artikels legst du am Lizenzartikel an („Im Shop verkaufen“); hier stehen alle Angebote, auch die der Pakete.';
}
protected function getHeaderActions(): array
@@ -6,7 +6,6 @@
use App\Domain\Catalog\BundleService;
use App\Domain\Catalog\BundleVersion;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\LicenceScope;
use App\Domain\Catalog\LicenseArticle;
@@ -136,18 +135,6 @@ public function activateAction(): Action
])->required(),
TextInput::make('price_euro')->label('Preis in Euro')->suffix('€')
->helperText('Nur bei einem Kauf, zum Beispiel 49,00.'),
Select::make('composition_version_id')->label('Programmfassung, die abgedeckt sein muss')
->options(function (): array {
return CompositionVersion::query()
->where('status', 'bereit')
->with('composition.editorialContentKind')
->orderByDesc('id')
->get()
->mapWithKeys(fn (CompositionVersion $version): array => [$version->id => CatalogOptions::compositionLabel($version)])
->all();
})
->searchable()
->helperText('Wenn gewählt, lässt sich die Fassung nur aktivieren, wenn jeder Bestandteil in den Artikeln enthalten ist.'),
Repeater::make('lines')->label('Positionen')->schema([
Select::make('kind')->label('Ziel')->options([
'article' => 'Lizenzartikel',
@@ -217,7 +204,6 @@ public function activateAction(): Action
'trainer_count' => $data['trainer_count'] ?? null,
'grant_kind' => $data['grant_kind'],
'price_cents' => $price,
'composition_version_id' => filled($data['composition_version_id'] ?? null) ? (int) $data['composition_version_id'] : null,
]);
});
@@ -155,12 +155,14 @@ public function forArticle(LicenseArticle $article): array
'aktion' => $this->articleName($article) !== '' ? null : ['label' => 'Redaktion bearbeiten', 'wire' => "openRedaktion('texte')"],
],
[
'titel' => 'In einem Paket oder Angebot verwenden',
'titel' => 'Im Shop verkaufen',
'text' => $inUse
? 'Der Artikel ist in einem Paket oder Angebot enthalten.'
: 'Verkauft wird der Artikel erst über ein Angebot, allein oder in einem Paket.',
: 'Verkauft wird der Artikel über eine Option mit Rechteprofil und Preis, allein oder in einem Paket.',
'stand' => $inUse ? 'erledigt' : 'offen',
'aktion' => $inUse ? null : ['label' => 'Angebote öffnen', 'href' => OfferResource::getUrl('index')],
'aktion' => $inUse ? null : ($usable
? ['label' => 'Option hinzufügen', 'wire' => "mountAction('option')"]
: ['label' => 'Angebote öffnen', 'href' => OfferResource::getUrl('index')]),
'pflicht' => false,
],
]);
@@ -40,6 +40,7 @@
@include('filament.verwaltung.abgang', ['offen' => $offen])
<div class="vw-medien-raster">
<div class="vw-spalte">
<section class="vw-karte-box" aria-labelledby="artikel-redaktion">
<div class="vw-spalte-kopf">
<h2 id="artikel-redaktion">Präsentation des Artikels</h2>
@@ -66,6 +67,46 @@
<div><button type="button" class="vw-btn is-line" wire:click="openRedaktion('texte')">@include('filament.verwaltung.icon', ['name' => 'stift'])Redaktion bearbeiten</button></div>
@endif
</section>
<section class="vw-karte-box" aria-labelledby="artikel-optionen" id="optionen">
<div class="vw-spalte-kopf">
<h2 id="artikel-optionen">Im Shop verkaufen</h2>
<span class="vw-feld-hilfe">Jede Option ist eine Lizenz mit Rechteprofil und Preis. Alle Optionen erscheinen auf der Produktseite dieses Artikels.</span>
</div>
@if (! $this->canOffer())
<p class="vw-feld-hilfe">Zuerst den Inhalt festlegen: Ohne veröffentlichten Stand lizenziert der Artikel nichts und lässt sich nicht verkaufen.</p>
@else
@php($optionen = $this->optionRows())
@if ($optionen === [])
<div class="vw-leer">
<strong>Noch keine Option</strong>
<p>Lege fest, mit welchem Rechteprofil und zu welchem Preis der Artikel verkauft wird. Mehrere Optionen, etwa für Privatpersonen und für Vereine, sind möglich.</p>
</div>
@else
<ul class="vw-verwendungsliste">
@foreach ($optionen as $option)
<li>
<strong>{{ $option['name'] }}</strong>
<span @class(['vw-zustand', 'is-'.$option['zustand']['ton']])>{{ $option['zustand']['label'] }}</span>
<span class="vw-feld-hilfe">{{ $option['price'] }} · {{ $option['licence'] }} · {{ $option['for'] }} · Rechte: {{ $option['rights'] }} · Fassung {{ $option['number'] }}</span>
<span class="vw-zeilenaktionen">
<button type="button" class="vw-link" wire:click="mountAction('option', { offer: {{ $option['offer'] }} })">{{ $option['active'] ? 'Ändern' : 'Wieder anbieten' }}</button>
@if ($option['active'])
<button type="button" class="vw-link is-quiet" wire:click="mountAction('optionEnd', { offer: {{ $option['offer'] }} })">Aus dem Verkauf nehmen</button>
@endif
@if ($option['page'])
<a class="vw-link is-quiet" href="{{ $option['page'] }}" target="_blank" rel="noopener">Produktseite ansehen</a>
@endif
<a class="vw-link is-quiet" href="{{ $option['url'] }}">Angebot öffnen</a>
</span>
</li>
@endforeach
</ul>
@endif
<div><button type="button" class="vw-btn is-line" wire:click="mountAction('option')">@include('filament.verwaltung.icon', ['name' => 'plus'])Option hinzufügen</button></div>
@endif
</section>
</div>
<aside class="vw-spalte">
@include('filament.verwaltung.voraussetzungen', ['voraussetzungen' => $voraussetzungen])
<section class="vw-karte-box" aria-labelledby="artikel-stand">
@@ -378,6 +378,7 @@
.vw-schritt.is-erledigt .vw-schritt-text { color: var(--vw-quiet); }
@media (max-width: 640px) { .vw-schritt { grid-template-columns: minmax(0, 1fr); } .vw-schritt .vw-btn { grid-column: 1; grid-row: auto; justify-self: start; } }
.vw-verwendungsliste li { display: flex; flex-wrap: wrap; gap: 0.25rem 0.75rem; align-items: baseline; padding: 0.6rem 0; border-bottom: 1px solid var(--vw-line); }
.vw-zeilenaktionen { flex-basis: 100%; display: flex; flex-wrap: wrap; gap: 0.25rem 1rem; }
.vw-vorschaubild.is-gross { max-width: 40rem; }
.vw-trennlinie { padding-top: 0.85rem; border-top: 1px solid var(--vw-line); }
.vw-inhaltsvorschau { width: 100%; height: 34rem; border: 1px solid var(--vw-line); border-radius: var(--vw-radius); background: #fff; }
+343
View File
@@ -0,0 +1,343 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\ArticleService;
use App\Domain\Catalog\DomainRuleException;
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\Commerce\Cart;
use App\Domain\Commerce\ProductOptions;
use App\Filament\Resources\LicenseArticles\Pages\ViewLicenseArticle;
use App\Filament\Resources\Offers\Pages\ViewOffer;
use App\Filament\Support\PublicationReadiness;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\Support\BuildsShop;
use Tests\TestCase;
/**
* Optionen am Lizenzartikel: Der Artikel wird direkt in seiner Maske verkauft (Rechteprofil, Preis, Nutzerkreis,
* Eignung), mehrere Optionen je Artikel sind möglich, und eine fehlgeschlagene Prüfung hinterlässt kein leeres Angebot.
*/
class ArticleOptionsTest extends TestCase
{
use BuildsShop;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seedShop();
}
private function keeper(): User
{
$keeper = User::factory()->katalogverwalter()->create();
$keeper->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
return $keeper;
}
/** Ein Artikel mit veröffentlichtem Stand, aber ohne Angebot. */
private function freshArticle(string $code = 'neu-optionen'): LicenseArticle
{
$article = app(ArticleService::class)->create($code);
app(ArticleService::class)->publishRelease($article, $this->article('shop-grenzen')->currentRelease->rootCompositionVersion, 'Erster Stand dieses Lizenzartikels.');
return $article->fresh();
}
private function privateRights(): RightsProfileVersion
{
return RightsProfileVersion::query()->whereHas('profile', fn ($query) => $query->where('name', 'Privatlizenz ehrenamtlich'))->firstOrFail();
}
private function clubRights(): RightsProfileVersion
{
return RightsProfileVersion::query()->whereHas('profile', fn ($query) => $query->where('name', 'Vereinslizenz institutionell'))->firstOrFail();
}
private function page(LicenseArticle $article)
{
return Livewire::actingAs($this->keeper(), 'staff')->test(ViewLicenseArticle::class, ['record' => $article->getKey()]);
}
public function test_the_dialog_asks_only_for_rights_price_scope_suitability_and_label(): void
{
$article = $this->freshArticle();
$component = $this->page($article)->mountAction('option');
$page = $component->instance();
$schema = (new \ReflectionMethod($page, 'getMountedActionSchema'))->invoke($page);
$labels = collect($schema->getFlatComponents())
->map(fn ($field): ?string => method_exists($field, 'getLabel') ? (string) $field->getLabel() : null)
->filter()
->values()
->all();
foreach (['Rechteprofil', 'Preis in Euro', 'Geeignet für', 'Nutzerkreis', 'Bezeichnung der Option'] as $label) {
$this->assertContains($label, $labels);
}
foreach (['Artikel', 'Ziel', 'Positionen', 'Paketfassung', 'Programmfassung, die abgedeckt sein muss', 'Vergabe'] as $label) {
$this->assertNotContains($label, $labels, 'Der Artikel steht fest, es gibt keine Auswahl von Artikel, Inhalt oder Vergabe.');
}
$data = $component->get('mountedActions.0.data');
$this->assertSame('person', $data['holder_kind']);
$this->assertSame('einzel', $data['licence_scope']);
}
public function test_an_article_gets_two_options_that_share_its_product_page_and_are_alternatives_in_the_cart(): void
{
$article = $this->freshArticle();
$this->page($article)
->mountAction('option')
->fillForm(['rights_id' => $this->privateRights()->id, 'price_euro' => '39,00', 'holder_kind' => 'person', 'licence_scope' => 'einzel', 'option_label' => ''])
->callMountedAction()
->assertHasNoActionErrors();
$this->page($article)
->mountAction('option')
->fillForm(['rights_id' => $this->clubRights()->id, 'price_euro' => '149,00', 'holder_kind' => 'organisation', 'licence_scope' => 'mehrfach', 'trainer_count' => 8, 'option_label' => 'Vereinslizenz'])
->callMountedAction()
->assertHasNoActionErrors();
$offers = app(ProductOptions::class)->offersOfArticle($article);
$this->assertCount(2, $offers);
[$private, $club] = $offers;
$this->assertSame('Einzellizenz für Privatpersonen', $private->optionName(), 'Ohne Eingabe gilt der Vorschlag aus Nutzerkreis und Eignung.');
$this->assertSame('Vereinslizenz', $club->optionName());
$this->assertStringStartsWith(app(ProductOptions::class)->articleTitle($article).': ', $private->name);
$privateVersion = $private->versions()->firstOrFail();
$this->assertSame(OfferStatus::Aktiv, $privateVersion->status);
$this->assertSame(3900, $privateVersion->price_cents);
$this->assertSame('kauf', $privateVersion->grant_kind);
$this->assertSame('einzel', $privateVersion->licence_scope);
$clubVersion = $club->versions()->firstOrFail();
$this->assertSame(14900, $clubVersion->price_cents);
$this->assertSame('organisation', $clubVersion->holder_kind);
$this->assertSame(8, $clubVersion->trainer_count);
$this->get('/shop/'.$article->id)
->assertOk()
->assertSee('Einzellizenz für Privatpersonen')
->assertSee('39,00')
->assertSee('Vereinslizenz')
->assertSee('149,00');
$this->get('/shop')->assertOk()->assertSee('/shop/'.$article->id, false);
$cart = app(Cart::class);
$this->assertSame(Cart::ADDED, $cart->add($private));
$this->assertSame(Cart::ALTERNATIVE, $cart->add($club), 'Zwei Optionen desselben Artikels sind Alternativen im Warenkorb.');
$this->assertSame(1, $cart->count());
}
public function test_the_article_page_lists_its_options_with_price_rights_and_state(): void
{
$article = $this->freshArticle();
$this->page($article)->assertSee('Im Shop verkaufen')->assertSee('Noch keine Option')->assertSee('Option hinzufügen');
app(OfferService::class)->offerArticle($article, $this->privateRights(), ['holder_kind' => 'person', 'licence_scope' => 'einzel', 'trainer_count' => 1, 'price_cents' => 3900], 'Neu: Privat', 'Privatlizenz');
$this->page($article)
->assertSee('Privatlizenz')
->assertSee('39,00 €')
->assertSee('Einzellizenz · 1 Trainer')
->assertSee('Rechte: Privatlizenz ehrenamtlich')
->assertSee('Im Shop')
->assertSee('Produktseite ansehen')
->assertSee('Aus dem Verkauf nehmen')
->assertDontSee('Noch keine Option');
}
public function test_an_article_without_stand_cannot_be_offered_and_the_page_says_so(): void
{
$article = app(ArticleService::class)->create('neu-ohne-stand-optionen');
$this->page($article)
->assertSee('Zuerst den Inhalt festlegen')
->assertDontSee('Noch keine Option');
$before = Offer::query()->count();
$this->page($article)
->mountAction('option')
->fillForm(['rights_id' => $this->privateRights()->id, 'price_euro' => '39,00', 'holder_kind' => 'person', 'licence_scope' => 'einzel'])
->callMountedAction();
$this->assertSame($before, Offer::query()->count(), 'Ein Artikel ohne Stand hinterlässt kein Angebot.');
}
public function test_a_failed_check_leaves_no_empty_offer_behind(): void
{
$article = $this->freshArticle();
$before = Offer::query()->count();
foreach (['0,00', '-3', 'abc'] as $price) {
$this->page($article)
->mountAction('option')
->fillForm(['rights_id' => $this->privateRights()->id, 'price_euro' => $price, 'holder_kind' => 'person', 'licence_scope' => 'einzel'])
->callMountedAction();
}
$this->assertSame($before, Offer::query()->count(), 'Ein Kauf ohne Preis über 0,00 € legt kein Angebot an.');
$service = app(OfferService::class);
try {
$service->offerArticle($article, $this->privateRights(), ['holder_kind' => 'person', 'licence_scope' => 'mehrfach', 'trainer_count' => 1, 'price_cents' => 3900], 'Neu: Fehler');
$this->fail('Eine Mehrfachlizenz mit einem Trainer wird abgelehnt.');
} catch (DomainRuleException) {
$this->assertSame($before, Offer::query()->count());
}
$withoutStand = app(ArticleService::class)->create('neu-ohne-stand-dienst');
try {
$service->offerArticle($withoutStand, $this->privateRights(), ['holder_kind' => 'person', 'licence_scope' => 'einzel', 'trainer_count' => 1, 'price_cents' => 3900], 'Neu: Ohne Stand');
$this->fail('Ein Artikel ohne Stand lässt sich nicht verkaufen.');
} catch (DomainRuleException) {
$this->assertSame($before, Offer::query()->count());
}
}
public function test_changing_an_option_activates_the_next_version_and_keeps_the_others(): void
{
$article = $this->freshArticle();
$service = app(OfferService::class);
$service->offerArticle($article, $this->privateRights(), ['holder_kind' => 'person', 'licence_scope' => 'einzel', 'trainer_count' => 1, 'price_cents' => 3900], 'Neu: Privat', 'Privatlizenz');
$service->offerArticle($article, $this->clubRights(), ['holder_kind' => 'organisation', 'licence_scope' => 'mehrfach', 'trainer_count' => 5, 'price_cents' => 14900], 'Neu: Verein', 'Vereinslizenz');
[$private, $club] = app(ProductOptions::class)->offersOfArticle($article);
$component = $this->page($article)->mountAction('option', ['offer' => $private->id]);
$data = $component->get('mountedActions.0.data');
$this->assertSame('39,00', $data['price_euro'], 'Die Maske ist mit der letzten Fassung vorbelegt, der Preis steht in Euro.');
$this->assertSame('Privatlizenz', $data['option_label']);
$this->assertSame($this->privateRights()->id, (int) $data['rights_id']);
$component->fillForm(['price_euro' => '29,00'])->callMountedAction()->assertHasNoActionErrors();
$versions = $private->versions()->orderBy('number')->get();
$this->assertCount(2, $versions);
$this->assertSame(OfferStatus::Beendet, $versions[0]->status);
$this->assertSame(3900, $versions[0]->price_cents, 'Die frühere Fassung bleibt unverändert gespeichert.');
$this->assertSame(OfferStatus::Aktiv, $versions[1]->status);
$this->assertSame(2900, $versions[1]->price_cents);
$this->assertSame(1, $club->versions()->count(), 'Die andere Option bleibt unberührt.');
$this->assertSame(14900, $club->versions()->firstOrFail()->price_cents);
}
public function test_cancelling_the_dialog_changes_nothing(): void
{
$article = $this->freshArticle();
app(OfferService::class)->offerArticle($article, $this->privateRights(), ['holder_kind' => 'person', 'licence_scope' => 'einzel', 'trainer_count' => 1, 'price_cents' => 3900], 'Neu: Privat', 'Privatlizenz');
[$offer] = app(ProductOptions::class)->offersOfArticle($article);
$this->page($article)
->mountAction('option', ['offer' => $offer->id])
->fillForm(['price_euro' => '1,00', 'option_label' => 'Geändert'])
->unmountAction();
$this->assertSame(1, $offer->versions()->count());
$this->assertSame(3900, $offer->versions()->firstOrFail()->price_cents);
$this->assertSame('Privatlizenz', $offer->fresh()->option_label);
}
public function test_ending_one_option_leaves_the_other_purchasable_and_it_can_be_offered_again(): void
{
$article = $this->freshArticle();
$service = app(OfferService::class);
$service->offerArticle($article, $this->privateRights(), ['holder_kind' => 'person', 'licence_scope' => 'einzel', 'trainer_count' => 1, 'price_cents' => 3900], 'Neu: Privat', 'Privatlizenz');
$service->offerArticle($article, $this->clubRights(), ['holder_kind' => 'organisation', 'licence_scope' => 'mehrfach', 'trainer_count' => 5, 'price_cents' => 14900], 'Neu: Verein', 'Vereinslizenz');
[$private, $club] = app(ProductOptions::class)->offersOfArticle($article);
$this->page($article)->mountAction('optionEnd', ['offer' => $private->id])->callMountedAction();
$this->assertNull($service->purchasableVersion($private->fresh()));
$this->assertNotNull($service->purchasableVersion($club->fresh()));
$this->get('/shop/'.$article->id)->assertOk()->assertDontSee('Privatlizenz')->assertSee('Vereinslizenz');
$this->page($article)
->assertSee('Nicht im Verkauf')
->assertSee('Wieder anbieten')
->mountAction('option', ['offer' => $private->id])
->callMountedAction()
->assertHasNoActionErrors();
$this->assertNotNull($service->purchasableVersion($private->fresh()));
$this->assertSame(2, $private->versions()->count());
$this->page($article)->mountAction('optionEnd', ['offer' => $private->id])->callMountedAction();
$this->page($article)->mountAction('optionEnd', ['offer' => $club->id])->callMountedAction();
$this->get('/shop/'.$article->id)->assertNotFound();
}
public function test_an_option_of_another_article_cannot_be_opened_or_changed(): void
{
$article = $this->freshArticle();
$foreign = $this->privateKonflikte();
$this->page($article)->call('mountAction', 'option', ['offer' => $foreign->id])->assertStatus(404);
$this->page($article)->call('mountAction', 'optionEnd', ['offer' => $foreign->id])->assertStatus(404);
$this->assertSame(1, $foreign->versions()->count());
$this->assertNotNull(app(OfferService::class)->purchasableVersion($foreign->fresh()), 'Eine fremde Option lässt sich weder öffnen noch beenden.');
try {
app(OfferService::class)->reviseArticleOption($foreign, $article, $this->privateRights(), ['holder_kind' => 'person', 'licence_scope' => 'einzel', 'trainer_count' => 1, 'price_cents' => 100]);
$this->fail('Der Dienst lehnt eine Option eines anderen Artikels ab.');
} catch (DomainRuleException $exception) {
$this->assertStringContainsString('gehört nicht zu diesem Lizenzartikel', $exception->getMessage());
$this->assertSame(1, $foreign->versions()->count());
}
}
public function test_the_dialog_neither_saves_nor_resets_open_editorial_input(): void
{
$article = $this->freshArticle();
$storedTitle = $article->display_title;
$component = $this->page($article)->set('displayTitle', 'Noch nicht gespeichert');
$component
->mountAction('option')
->fillForm(['rights_id' => $this->privateRights()->id, 'price_euro' => '39,00', 'holder_kind' => 'person', 'licence_scope' => 'einzel'])
->callMountedAction()
->assertHasNoActionErrors();
$component->assertSet('displayTitle', 'Noch nicht gespeichert');
$this->assertSame($storedTitle, $article->fresh()->display_title, 'Die Option speichert die Redaktion nicht mit.');
$this->assertCount(1, app(ProductOptions::class)->offersOfArticle($article));
}
public function test_the_next_step_on_the_article_opens_the_option_dialog(): void
{
$article = $this->freshArticle();
$steps = collect(app(PublicationReadiness::class)->forArticle($article)['schritte']);
$step = $steps->firstWhere('titel', 'Im Shop verkaufen');
$this->assertNotNull($step);
$this->assertSame("mountAction('option')", $step['aktion']['wire']);
}
public function test_the_offer_dialog_no_longer_asks_for_a_program_version_to_cover(): void
{
$component = Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $this->privateKonflikte()->getKey()])
->mountAction('activate');
$page = $component->instance();
$schema = (new \ReflectionMethod($page, 'getMountedActionSchema'))->invoke($page);
$labels = collect($schema->getFlatComponents())
->map(fn ($field): ?string => method_exists($field, 'getLabel') ? (string) $field->getLabel() : null)
->filter()
->all();
$this->assertNotContains('Programmfassung, die abgedeckt sein muss', $labels);
$this->assertContains('Positionen', $labels, 'Pakete und der Altbestand behalten die Positionen.');
}
}