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.
404 lines
16 KiB
PHP
404 lines
16 KiB
PHP
<?php
|
|
|
|
namespace App\Domain\Catalog;
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class OfferService
|
|
{
|
|
public function __construct(private readonly BundleService $bundles) {}
|
|
|
|
public function currentActiveVersion(Offer $offer): OfferVersion
|
|
{
|
|
$version = $offer->versions()
|
|
->where('status', OfferStatus::Aktiv)
|
|
->orderByDesc('number')
|
|
->first();
|
|
|
|
if ($version === null) {
|
|
throw new DomainRuleException('Das Angebot hat keine aktive Fassung.');
|
|
}
|
|
|
|
return $version;
|
|
}
|
|
|
|
/**
|
|
* Die aktive, als Kauf angebotene Fassung mit Preis; sonst null (nicht kaufbar, zurückgezogen oder kostenlos).
|
|
*/
|
|
public function purchasableVersion(Offer $offer): ?OfferVersion
|
|
{
|
|
$version = $offer->versions()
|
|
->where('status', OfferStatus::Aktiv)
|
|
->orderByDesc('number')
|
|
->first();
|
|
|
|
if ($version === null || $version->grant_kind !== 'kauf' || $version->price_cents === null) {
|
|
return null;
|
|
}
|
|
|
|
return $version;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $capabilities
|
|
* @param array<string, mixed> $options
|
|
*/
|
|
public function createRightsProfile(
|
|
string $name,
|
|
string $purpose,
|
|
array $capabilities,
|
|
array $options = [],
|
|
): RightsProfileVersion {
|
|
$purpose = trim($purpose);
|
|
|
|
if (! in_array($purpose, ['ehrenamtlich', 'kommerziell', 'institutionell'], true)) {
|
|
throw new DomainRuleException('Der Nutzungszweck eines Rechteprofils ist ehrenamtlich, kommerziell oder institutionell.');
|
|
}
|
|
|
|
if ($capabilities === []) {
|
|
throw new DomainRuleException('Ein Rechteprofil braucht mindestens eine Fähigkeit.');
|
|
}
|
|
|
|
$profile = RightsProfile::query()->create([
|
|
'name' => trim($name) !== '' ? trim($name) : throw new DomainRuleException('Der Name des Rechteprofils fehlt.'),
|
|
]);
|
|
|
|
return $profile->versions()->create([
|
|
'number' => 1,
|
|
'purpose' => $purpose,
|
|
'capabilities' => $capabilities,
|
|
'options' => $options,
|
|
]);
|
|
}
|
|
|
|
public function create(string $name): Offer
|
|
{
|
|
$name = trim($name);
|
|
|
|
if ($name === '') {
|
|
throw new DomainRuleException('Der Name des Angebots fehlt.');
|
|
}
|
|
|
|
return Offer::query()->create([
|
|
'name' => $name,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
|
* @param array<string, mixed> $attributes
|
|
*/
|
|
public function activate(Offer $offer, array $lines, array $attributes = []): OfferVersion
|
|
{
|
|
if ($lines === []) {
|
|
throw new DomainRuleException('Eine Angebotsfassung braucht mindestens eine Position.');
|
|
}
|
|
|
|
$attributes = array_merge([
|
|
'price_cents' => null,
|
|
'tax_class' => null,
|
|
'term_rule' => 'dauerhaft',
|
|
'update_promise' => 'alle_freigegebenen_fassungen',
|
|
'dynamic' => false,
|
|
'grant_kind' => 'kauf',
|
|
'holder_kind' => 'person',
|
|
'licence_scope' => null,
|
|
'trainer_count' => null,
|
|
], $attributes);
|
|
|
|
$this->assertBuyable($lines, $attributes);
|
|
|
|
$this->assertAttributes($attributes);
|
|
[$attributes['licence_scope'], $attributes['trainer_count']] = LicenceScope::normalise($attributes['licence_scope'], $attributes['trainer_count']);
|
|
$scope = $this->scopeFor($lines);
|
|
$this->assertSellableContent($scope);
|
|
$this->assertCoverage($lines, $attributes);
|
|
|
|
return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion {
|
|
$offer = Offer::query()->lockForUpdate()->findOrFail($offer->id);
|
|
|
|
OfferVersion::query()
|
|
->where('offer_id', $offer->id)
|
|
->where('status', OfferStatus::Aktiv)
|
|
->update(['status' => OfferStatus::Beendet->value]);
|
|
|
|
$version = $offer->versions()->create([
|
|
'number' => ((int) $offer->versions()->max('number')) + 1,
|
|
'status' => OfferStatus::Entwurf,
|
|
'price_cents' => $attributes['price_cents'],
|
|
'tax_class' => $attributes['tax_class'],
|
|
'term_rule' => $attributes['term_rule'],
|
|
'update_promise' => $attributes['update_promise'],
|
|
'dynamic' => $attributes['dynamic'],
|
|
'grant_kind' => $attributes['grant_kind'],
|
|
'holder_kind' => $attributes['holder_kind'],
|
|
'licence_scope' => $attributes['licence_scope'],
|
|
'trainer_count' => $attributes['trainer_count'],
|
|
]);
|
|
|
|
foreach (array_values($lines) as $index => $line) {
|
|
$target = $line['target'];
|
|
$version->lines()->create([
|
|
'position' => $index + 1,
|
|
'license_article_id' => $target instanceof LicenseArticle ? $target->id : null,
|
|
'bundle_version_id' => $target instanceof BundleVersion ? $target->id : null,
|
|
'rights_profile_version_id' => $line['rights']->id,
|
|
]);
|
|
}
|
|
|
|
foreach ($scope as $entry) {
|
|
$version->resolvedScopes()->create($entry);
|
|
}
|
|
|
|
RightsProfileVersion::query()
|
|
->whereIn('id', array_column($scope, 'rights_profile_version_id'))
|
|
->whereNull('locked_at')
|
|
->update(['locked_at' => now()]);
|
|
|
|
$version->status = OfferStatus::Aktiv;
|
|
$version->activated_at = now();
|
|
$version->save();
|
|
|
|
return $version->load('resolvedScopes');
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 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
|
|
* zurückgezogen und blockieren den Abschluss, bis der Käufer sie entfernt.
|
|
*/
|
|
public function end(Offer $offer): OfferVersion
|
|
{
|
|
return DB::transaction(function () use ($offer): OfferVersion {
|
|
$offer = Offer::query()->lockForUpdate()->findOrFail($offer->id);
|
|
$version = $this->currentActiveVersion($offer);
|
|
$version->status = OfferStatus::Beendet;
|
|
$version->save();
|
|
|
|
return $version;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Die Bezeichnung der Option auf der Produktseite. Die Seite selbst wird nicht zugeordnet: Sie ist die Seite des
|
|
* Artikels bzw. des Pakets, das die einzige Position der Fassung verkauft. Die Bezeichnung ist keine bindende Kondition.
|
|
*/
|
|
public function setOptionLabel(Offer $offer, ?string $optionLabel): Offer
|
|
{
|
|
$offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null;
|
|
$offer->save();
|
|
|
|
return $offer;
|
|
}
|
|
|
|
/**
|
|
* @return list<int>
|
|
*/
|
|
public function scopeArticleIds(OfferVersion $version): array
|
|
{
|
|
return $version->resolvedScopes()->orderBy('id')->pluck('license_article_id')->all();
|
|
}
|
|
|
|
/**
|
|
* Ein Kauf muss im Shop auffindbar und kaufbar sein, sonst lässt er sich nicht aktivieren: Er verkauft genau einen
|
|
* Artikel oder ein Paket (das ist die Produktseite) und hat einen Preis. Mehrere Artikel gemeinsam verkauft ein
|
|
* Paket. Vergaben bei Registrierung oder auf Abruf stehen nie im Shop und sind davon ausgenommen.
|
|
*
|
|
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
|
* @param array<string, mixed> $attributes
|
|
*/
|
|
private function assertBuyable(array $lines, array $attributes): void
|
|
{
|
|
if (($attributes['grant_kind'] ?? null) !== 'kauf') {
|
|
return;
|
|
}
|
|
|
|
if (count($lines) !== 1) {
|
|
throw new DomainRuleException('Ein Kauf verkauft genau einen Artikel oder ein Paket. Mehrere Artikel gemeinsam verkaufst du als Paket (Katalog → Pakete).');
|
|
}
|
|
|
|
if (! is_int($attributes['price_cents'] ?? null) || $attributes['price_cents'] <= 0) {
|
|
throw new DomainRuleException('Ein Kauf braucht einen Preis über 0,00 €.');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $attributes
|
|
*/
|
|
private function assertAttributes(array $attributes): void
|
|
{
|
|
if (! in_array($attributes['term_rule'], ['dauerhaft', 'befristet', 'solange_angebot_aktiv', 'periodisch'], true)) {
|
|
throw new DomainRuleException('Die Laufzeitregel der Angebotsfassung ist unbekannt.');
|
|
}
|
|
|
|
if (! in_array($attributes['grant_kind'], ['kauf', 'bei_registrierung', 'auf_abruf'], true)) {
|
|
throw new DomainRuleException('Die Vergabeart der Angebotsfassung ist unbekannt.');
|
|
}
|
|
|
|
if (! in_array($attributes['holder_kind'], ['person', 'organisation'], true)) {
|
|
throw new DomainRuleException('Die Inhaberart der Angebotsfassung ist Person oder Organisation.');
|
|
}
|
|
|
|
if ($attributes['update_promise'] !== 'alle_freigegebenen_fassungen') {
|
|
throw new DomainRuleException('Die Updatezusage umfasst alle später freigegebenen Fassungen des Artikels.');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Ein Angebot ohne verkaufbaren Inhalt wird nicht aktiviert: Jeder Lizenzartikel des Umfangs braucht einen
|
|
* veröffentlichten Stand, sonst erhielten Käufer nichts. Die Prüfung liegt im Domänenmodell, nicht nur in der
|
|
* Maske, damit auch jeder andere Weg (Skript, Import) sie durchläuft.
|
|
*
|
|
* @param list<array{license_article_id: int, rights_profile_version_id: int}> $scope
|
|
*/
|
|
private function assertSellableContent(array $scope): void
|
|
{
|
|
$ids = array_values(array_unique(array_column($scope, 'license_article_id')));
|
|
$missing = LicenseArticle::query()->with('currentRelease')->whereIn('id', $ids)->orderBy('code')->get()
|
|
->filter(fn (LicenseArticle $article): bool => ! ($article->currentRelease instanceof ArticleRelease
|
|
&& StatusValue::of($article->currentRelease->status) === ReleaseStatus::Veroeffentlicht->value));
|
|
|
|
if ($missing->isEmpty()) {
|
|
return;
|
|
}
|
|
|
|
$names = $missing->map(fn (LicenseArticle $article): string => '„'.($article->working_title ?: $article->code).'“ ('.$article->code.')')->implode(', ');
|
|
|
|
throw new DomainRuleException(($missing->count() === 1 ? 'Der Lizenzartikel ' : 'Die Lizenzartikel ').$names
|
|
.($missing->count() === 1 ? ' hat' : ' haben')
|
|
.' noch keinen veröffentlichten Stand und vergibt'.($missing->count() === 1 ? '' : ' keine').' keine Inhalte. '
|
|
.'Lege zuerst am Artikel den Inhalt fest, bevor das Angebot aktiviert wird.');
|
|
}
|
|
|
|
/**
|
|
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
|
* @return list<array{license_article_id: int, rights_profile_version_id: int}>
|
|
*/
|
|
/**
|
|
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
|
* @param array<string, mixed> $attributes
|
|
*/
|
|
private function assertCoverage(array $lines, array $attributes): void
|
|
{
|
|
$versionId = $attributes['composition_version_id'] ?? null;
|
|
|
|
if ($versionId === null) {
|
|
return;
|
|
}
|
|
|
|
$version = CompositionVersion::query()->findOrFail($versionId);
|
|
|
|
if (app(ForeignCompositions::class)->reaches($version)) {
|
|
throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Das Angebot wird hier nicht aktiviert.');
|
|
}
|
|
$articles = [];
|
|
|
|
foreach ($lines as $line) {
|
|
if ($line['target'] instanceof LicenseArticle) {
|
|
$articles[] = $line['target'];
|
|
}
|
|
}
|
|
|
|
$blocked = app(OfferCoverage::class)->blockedLeaves($version);
|
|
|
|
if ($blocked !== []) {
|
|
throw new DomainRuleException('Das Angebot enthält gesperrte Bestandteile: '.implode(', ', $blocked));
|
|
}
|
|
|
|
$missing = app(OfferCoverage::class)->missingLeaves($version, $articles);
|
|
|
|
if ($missing !== []) {
|
|
throw new DomainRuleException('Das Angebot deckt nicht alle Blätter: '.implode(', ', $missing));
|
|
}
|
|
}
|
|
|
|
private function scopeFor(array $lines): array
|
|
{
|
|
$scope = [];
|
|
|
|
foreach ($lines as $line) {
|
|
$target = $line['target'];
|
|
$rights = $line['rights'];
|
|
|
|
if ($target instanceof BundleVersion && $target->status !== BundleStatus::Veroeffentlicht) {
|
|
throw new DomainRuleException('Eine Angebotsfassung enthält nur veröffentlichte Paketfassungen.');
|
|
}
|
|
|
|
$articleIds = match (true) {
|
|
$target instanceof LicenseArticle => [$target->id],
|
|
$target instanceof BundleVersion => $this->bundles->articleIds($target),
|
|
default => throw new DomainRuleException('Eine Angebotsposition zeigt auf einen Lizenzartikel oder eine Paketfassung.'),
|
|
};
|
|
|
|
foreach ($articleIds as $articleId) {
|
|
$key = $articleId.'-'.$rights->id;
|
|
$scope[$key] = [
|
|
'license_article_id' => $articleId,
|
|
'rights_profile_version_id' => $rights->id,
|
|
];
|
|
}
|
|
}
|
|
|
|
return array_values($scope);
|
|
}
|
|
}
|