Compare commits
89
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
881703ba0e | ||
|
|
bbee288e69 | ||
|
|
d1f97a351a | ||
|
|
ef56befc0e | ||
|
|
da02e0bbda | ||
|
|
3f9e463dfa | ||
|
|
03737a5fc7 | ||
|
|
b453a8be10 | ||
|
|
a3c159a729 | ||
|
|
b3fb619bda | ||
|
|
78c8870e4e | ||
|
|
dd3cc83057 | ||
|
|
32272e8e40 | ||
|
|
9db3a98440 | ||
|
|
f87e67ce02 | ||
|
|
fe39e1efb6 | ||
|
|
6518d1b80f | ||
|
|
69a22deb1f | ||
|
|
f0287eec2f | ||
|
|
42e0a6bb93 | ||
|
|
76fab81386 | ||
|
|
1ce2e1e51f | ||
|
|
0154182f3b | ||
|
|
cb80835c92 | ||
|
|
e7efb073da | ||
|
|
433f9aee61 | ||
|
|
bb0949dcd9 | ||
|
|
2d54d39c24 | ||
|
|
cf50d341f5 | ||
|
|
8b644292a7 | ||
|
|
0c4ef4c4ed | ||
|
|
2e6260acca | ||
|
|
8ecc1ecdaa | ||
|
|
9f070fbab2 | ||
|
|
ca0f68e8f6 | ||
|
|
aa1e6eb6ac | ||
|
|
05d487dd0b | ||
|
|
67614158e4 | ||
|
|
e0a3fdbb70 | ||
|
|
b8c5c68887 | ||
|
|
acb88e4a1d | ||
|
|
2a54347d50 | ||
|
|
992171bb7a | ||
|
|
8b59946bb1 | ||
|
|
061181f30d | ||
|
|
f54acd55e6 | ||
|
|
2ca7a8b268 | ||
|
|
cc890d9fc7 | ||
|
|
37056761a3 | ||
|
|
1413e0640f | ||
|
|
631502c064 | ||
|
|
4bc2e5871b | ||
|
|
1bc5356e84 | ||
|
|
2094961b6e | ||
|
|
7ef58e0e6e | ||
|
|
94eda30298 | ||
|
|
bff17a9e8e | ||
|
|
73126fec0c | ||
|
|
437bb394b2 | ||
|
|
5e28538551 | ||
|
|
be932c113a | ||
|
|
ef3af0e036 | ||
|
|
936c85ef5e | ||
|
|
c61869f8aa | ||
|
|
9f7c645baf | ||
|
|
08d03d0f56 | ||
|
|
ea4244487f | ||
|
|
fc40aba26c | ||
|
|
32837639e6 | ||
|
|
3825f53a9b | ||
|
|
604e1791c5 | ||
|
|
cd66561ca9 | ||
|
|
886715af96 | ||
|
|
05bd36509c | ||
|
|
96bb661239 | ||
|
|
340b898b7b | ||
|
|
9701777011 | ||
|
|
4520dba2f0 | ||
|
|
d49b178ebd | ||
|
|
da7ebca999 | ||
|
|
f72b79fd8c | ||
|
|
4e0760db1e | ||
|
|
6c8bbee363 | ||
|
|
7ad5929588 | ||
|
|
ed1f706d46 | ||
|
|
7c48a6480c | ||
|
|
d5c2b34b9d | ||
|
|
eb6192b067 | ||
|
|
061bc00564 |
No files matched your search
@@ -70,3 +70,7 @@ PAYMENT_DRIVER=test
|
||||
MEDIA_PUBLIC_PATH=
|
||||
MEDIA_DERIVED_PATH=
|
||||
MEDIA_ORIGINALS_PATH=
|
||||
|
||||
# Übernahme von Übungen aus Shinkan (Test: erst nach Freigabe der Anbindung eintragen; Werte nie ins Repository)
|
||||
SHINKAN_DISTRIBUTION_URL=
|
||||
SHINKAN_DISTRIBUTION_KEY=
|
||||
@@ -63,6 +63,6 @@ ## Entwicklung
|
||||
## Verwaltungsoberfläche
|
||||
|
||||
- Maßgeblich sind `docs/ux/verwaltung/14-verwaltungsstandard.md` (Design und Interaktion) und `15-umbauauftrag.md` (Auftrag, Nachweise). Keine neue allgemeine Designabstimmung verlangen. Einstieg für alle Agenten: `AGENTS.md`, `.cursor/rules/verwaltung-ux.mdc`.
|
||||
- Gemeinsame Bausteine wiederverwenden statt neue Masken bauen: `resources/views/filament/verwaltung/` (`kopf`, `redaktion`, `texte`, `praesentation`, `einordnung`, `picker`, `bestaetigung`, `abgang`, `aufbau`, `bestand`) mit dem Trait `App\Filament\Support\ManagesEditorialSurface`. Listen nutzen `verwaltung/bestand` mit `ShowsBestand` (bzw. `ListsCompositions`, `ListsCatalog`) und den Eintrag `<x-vw.eintrag>`, den auch der Picker verwendet; Katalogobjekte die Seite `catalog/objekt`. CMS: Seitenkopf `cms/seite-kopf` (Register, Kontexte „Abschnitt gestalten“ und „Konfigurieren“); Seiten und Menüs in der Webpräsenz (`App\Filament\Pages\Webpraesenz`, Menüs als Arbeitsstand mit einer Speicherhandlung). Der Picker liegt im Trait `ChoosesMedia` (Redaktion über `ManagesEditorialSurface`, CMS-Bilder über `ChoosesWebsiteImages`); keine eigenen Auswahllisten für Medien bauen. Redaktionelle Auswahlwerte (Materialart, Einordnung) nur über `App\Domain\Catalog\EditorialVocabulary` anbieten und prüfen (aktiv, zulässiger Kontext, vorhandene Zuordnungen erhalten); gepflegt werden sie unter „Redaktionelle Stammdaten“. Ersetzt eine Seite die Filament-Tabelle, muss sie den Dialogbereich ausgeben (in `bestand` enthalten), sonst öffnen „… anlegen“-Dialoge nicht. Gestaltungswerte nur in `verwaltung/styles.blade.php` (Tokens `--vw-…`, dokumentiert in `docs/ux/verwaltung/tokens.md`).
|
||||
- Gemeinsame Bausteine wiederverwenden statt neue Masken bauen: `resources/views/filament/verwaltung/` (`kopf`, `redaktion`, `texte`, `praesentation`, `einordnung`, `picker`, `bestaetigung`, `abgang`, `aufbau`, `bestand`) mit dem Trait `App\Filament\Support\ManagesEditorialSurface`. Listen nutzen `verwaltung/bestand` mit `ShowsBestand` (bzw. `ListsCompositions`, `ListsCatalog`) und den Eintrag `<x-vw.eintrag>`, den auch der Picker verwendet; Katalogobjekte die Seite `catalog/objekt`. CMS: Seitenkopf `cms/seite-kopf` (Register, Kontexte „Abschnitt gestalten“ und „Konfigurieren“); Seiten und Menüs in der Webpräsenz (`App\Filament\Pages\Webpraesenz`, Menüs als Arbeitsstand mit einer Speicherhandlung). Der Picker liegt im Trait `ChoosesMedia` (Redaktion über `ManagesEditorialSurface`, CMS-Bilder über `ChoosesWebsiteImages`); keine eigenen Auswahllisten für Medien bauen. Redaktionelle Auswahlwerte (Materialart, Einordnung) nur über `App\Domain\Catalog\EditorialVocabulary` anbieten und prüfen (aktiv, zulässiger Kontext, vorhandene Zuordnungen erhalten); gepflegt werden sie unter „Redaktionelle Stammdaten“. Fachliche Säulen gibt es nur in der Säulenverwaltung (`pillars`); Zuordnung über `PillarService::assign`, nie über eine Dimension. Ersetzt eine Seite die Filament-Tabelle, muss sie den Dialogbereich ausgeben (in `bestand` enthalten), sonst öffnen „… anlegen“-Dialoge nicht. Gestaltungswerte nur in `verwaltung/styles.blade.php` (Tokens `--vw-…`, dokumentiert in `docs/ux/verwaltung/tokens.md`).
|
||||
- Die Redaktion ist ein Arbeitsstand: nur „Redaktion speichern“ schreibt Texte, Einordnung, Präsentationsmedien und Abweichungen. Kein verdecktes Mitspeichern aus anderen Dialogen, offene Eingaben bleiben beim Wechsel erhalten.
|
||||
- Jede UI-Änderung in der echten Anwendung prüfen (luf-test, breite und schmale Fenster, Tastatur) und mit Screenshots in `docs/ux/verwaltung/abnahme/` belegen. Stand der Abnahme: `abnahme/teil-a.md`, `abnahme/teil-b.md`, `abnahme/teil-c.md`, `abnahme/stammdaten.md`.
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Domain\Catalog\LegacyPillarAdoption;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class AdoptLegacyPillars extends Command
|
||||
{
|
||||
protected $signature = 'luf:saeulen-uebernehmen {--dry-run : Nur berichten, nichts schreiben}';
|
||||
|
||||
protected $description = 'Übernimmt die alte Dimension „Fachliche Säule“ in die zentrale Säulenverwaltung und berichtet ungeklärte Fälle';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$report = (new LegacyPillarAdoption)->run($dryRun);
|
||||
|
||||
foreach (LegacyPillarAdoption::lines($report, $dryRun) as $line) {
|
||||
$this->line($line);
|
||||
}
|
||||
|
||||
return $report['unresolved'] === [] ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,8 @@ public function publishRelease(
|
||||
'content_element_version_id' => $row['version_id'],
|
||||
'role' => $row['role'] !== '' ? $row['role'] : $row['path'],
|
||||
'path' => $row['path'],
|
||||
'requirement' => $row['requirement'] ?? null,
|
||||
'variant_key' => $row['variant'] ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -141,6 +143,10 @@ private function checkedRows(ContentElementVersion|CompositionVersion $root): ar
|
||||
{
|
||||
$root->refresh();
|
||||
|
||||
if (app(ForeignCompositions::class)->reaches($root)) {
|
||||
throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Er wird hier nicht veröffentlicht, damit nichts fehlt oder zu viel ausgegeben wird.');
|
||||
}
|
||||
|
||||
if ($root->status !== ContentVersionStatus::Bereit) {
|
||||
throw new DomainRuleException('Ein Artikel-Stand kann nur eine bereitgestellte Fassung festschreiben.');
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ class CompatibilityAttestation extends Model
|
||||
protected $fillable = [
|
||||
'composition_version_id',
|
||||
'resolved_hash',
|
||||
'structure_hash',
|
||||
'confirmed_by',
|
||||
'confirmed_at',
|
||||
'note',
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Composition extends Model
|
||||
@@ -35,6 +36,11 @@ protected function casts(): array
|
||||
];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::addGlobalScope(new SupportedKindScope);
|
||||
}
|
||||
|
||||
public function editorialContentKind(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EditorialContentKind::class);
|
||||
@@ -44,4 +50,13 @@ public function versions(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompositionVersion::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Direkt zugeordnete fachliche Säulen (zentrale Säulenverwaltung). Die Säulen der enthaltenen Medien sind davon
|
||||
* getrennt und werden zur Laufzeit abgeleitet (CatalogReading::memberPillars).
|
||||
*/
|
||||
public function pillars(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Pillar::class)->orderBy('pillars.sort_order')->orderBy('pillars.name');
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,24 @@ enum CompositionKind: string
|
||||
case Kombination = 'kombination';
|
||||
case Uebung = 'uebung';
|
||||
case Kurs = 'kurs';
|
||||
/** Seit der Übungsverwaltung: die fachliche Übung. Der ältere Wert `uebung` bezeichnet in der Verwaltung das Modul. */
|
||||
case Exercise = 'exercise';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_map(fn (self $case): string => $case->value, self::cases());
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombination',
|
||||
self::Uebung => 'Übung',
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Kurs',
|
||||
self::Exercise => 'Übung',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -21,8 +32,9 @@ public function plural(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombinationen',
|
||||
self::Uebung => 'Übungen',
|
||||
self::Uebung => 'Module',
|
||||
self::Kurs => 'Kurse',
|
||||
self::Exercise => 'Übungen',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -30,8 +42,9 @@ public function createLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Kombination anlegen',
|
||||
self::Uebung => 'Übung anlegen',
|
||||
self::Uebung => 'Modul anlegen',
|
||||
self::Kurs => 'Kurs anlegen',
|
||||
self::Exercise => 'Übung anlegen',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,6 +54,7 @@ public function explanation(): string
|
||||
self::Kombination => 'Didaktische oder thematische Zusammenstellung, zum Beispiel ein Materialsatz. Sie wird in Übungen und Kursen wiederverwendet und ist selbst kein Kurs.',
|
||||
self::Uebung => 'Eine konkrete Lernsituation, zum Beispiel aus Film und Merkblatt. Dieselben Medien können in mehreren Übungen stecken.',
|
||||
self::Kurs => 'Ein Ablauf für den Kursbetrieb aus Übungen, Kombinationen und Medien. Ein Kurs ist keine Übung.',
|
||||
self::Exercise => 'Eine Übung mit Lernziel, Vorbereitung, Durchführung und Varianten, mit Texten und Medien in fester Abfolge. Sie wird in Module und Programme aufgenommen.',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -50,6 +64,7 @@ public function deskLabel(): string
|
||||
self::Kombination => 'Fachliche Kombination',
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Programm',
|
||||
self::Exercise => 'Übung',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -59,6 +74,7 @@ public function deskExplanation(): string
|
||||
self::Kombination => $this->explanation(),
|
||||
self::Uebung => 'Ein Modul mit Lernziel, Zeit, Material und geordneten Bestandteilen. Dieselben Medien können in mehreren Modulen stecken.',
|
||||
self::Kurs => 'Ein Programm aus Modulen und weiteren Inhalten.',
|
||||
self::Exercise => $this->explanation(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,21 @@ class CompositionMember extends Model
|
||||
'placement_note',
|
||||
'content_element_version_id',
|
||||
'nested_composition_version_id',
|
||||
'variant_id',
|
||||
'requirement',
|
||||
'variant_selection',
|
||||
'origin',
|
||||
];
|
||||
|
||||
public const REQUIRED = 'erforderlich';
|
||||
|
||||
public const SUPPLEMENTARY = 'ergaenzend';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['variant_selection' => 'array'];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (CompositionMember $member): void {
|
||||
@@ -41,6 +54,11 @@ public function contentElementVersion(): BelongsTo
|
||||
return $this->belongsTo(ContentElementVersion::class);
|
||||
}
|
||||
|
||||
public function variant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersionVariant::class, 'variant_id');
|
||||
}
|
||||
|
||||
public function nestedCompositionVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id');
|
||||
|
||||
@@ -54,6 +54,7 @@ public function publish(
|
||||
?string $note,
|
||||
array $didactic,
|
||||
bool $consent,
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
$review = $this->review($host, $members);
|
||||
|
||||
@@ -67,8 +68,8 @@ public function publish(
|
||||
|
||||
$this->publishedDrafts = [];
|
||||
|
||||
return DB::transaction(function () use ($host, $members, $actor, $note, $didactic): CompositionVersion {
|
||||
return $this->materialize($host, $members, $didactic, $actor, $note, []);
|
||||
return DB::transaction(function () use ($host, $members, $actor, $note, $didactic, $variants): CompositionVersion {
|
||||
return $this->materialize($host, $members, $didactic, $actor, $note, [], $variants);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -220,6 +221,12 @@ private function inspectReleasedComposition(
|
||||
): void {
|
||||
$version = CompositionVersion::query()->with('composition', 'members')->find($id);
|
||||
|
||||
if ($version instanceof CompositionVersion && $version->composition === null && app(ForeignCompositions::class)->isForeignVersion($version->id)) {
|
||||
$blocked[] = $this->block('Bestandteil', 'Dieser Bestandteil stammt aus einer neueren Programmversion und kann hier nicht freigegeben werden.', $depth, null);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $version instanceof CompositionVersion || $version->composition === null) {
|
||||
$blocked[] = $this->block('Modul', 'Ein Bestandteil ist nicht mehr vorhanden.', $depth, null);
|
||||
|
||||
@@ -324,6 +331,7 @@ private function materialize(
|
||||
?User $actor,
|
||||
?string $note,
|
||||
array $stack,
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
if (isset($this->publishedDrafts[$composition->id])) {
|
||||
return $this->publishedDrafts[$composition->id];
|
||||
@@ -341,6 +349,10 @@ private function materialize(
|
||||
'role' => trim((string) ($member['role'] ?? '')),
|
||||
'note' => trim((string) ($member['note'] ?? '')),
|
||||
'target' => $this->resolveTarget((string) ($member['target'] ?? ''), $actor, $stack),
|
||||
'variant' => isset($member['variant']) && $member['variant'] !== '' ? (string) $member['variant'] : null,
|
||||
'requirement' => $member['requirement'] ?? 'erforderlich',
|
||||
'selection' => is_array($member['selection'] ?? null) && $member['selection'] !== [] ? array_values($member['selection']) : null,
|
||||
'origin' => $member['origin'] ?? 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -352,8 +364,11 @@ private function materialize(
|
||||
[
|
||||
'learning_goal' => $didactic['learning_goal'] ?? null,
|
||||
'duration_minutes' => $didactic['duration_minutes'] ?? null,
|
||||
'duration_max' => $didactic['duration_max'] ?? null,
|
||||
'material_note' => $didactic['material_note'] ?? null,
|
||||
'prerequisites' => $didactic['prerequisites'] ?? null,
|
||||
],
|
||||
$variants,
|
||||
);
|
||||
$this->publishedDrafts[$composition->id] = $version;
|
||||
|
||||
@@ -414,11 +429,14 @@ private function resolveTarget(string $target, ?User $actor, array $stack): Cont
|
||||
[
|
||||
'learning_goal' => $draft['learning_goal'] ?? null,
|
||||
'duration_minutes' => $draft['duration_minutes'] ?? null,
|
||||
'duration_max' => $draft['duration_max'] ?? null,
|
||||
'material_note' => $draft['material_note'] ?? null,
|
||||
'prerequisites' => $draft['prerequisites'] ?? null,
|
||||
],
|
||||
$actor,
|
||||
is_string($draft['revision_note'] ?? null) ? $draft['revision_note'] : null,
|
||||
$stack,
|
||||
is_array($draft['variants'] ?? null) ? $draft['variants'] : [],
|
||||
);
|
||||
app(EditorialWorkingDraft::class)->clear($composition);
|
||||
|
||||
|
||||
@@ -60,6 +60,11 @@ private function members(CompositionVersion $version, array $stack = []): array
|
||||
$nested->loadMissing('composition.editorialContentKind', 'composition');
|
||||
$composition = $nested->composition;
|
||||
|
||||
// Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht anzeigen (Rückfallschutz).
|
||||
if ($composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$nodes[] = new StructureNode(
|
||||
role: $member->role,
|
||||
position: $member->position,
|
||||
|
||||
@@ -17,6 +17,10 @@ class CompositionVersion extends Model
|
||||
'learning_goal',
|
||||
'duration_minutes',
|
||||
'material_note',
|
||||
'duration_max',
|
||||
'prerequisites',
|
||||
'structure_hash',
|
||||
'source_snapshot_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -60,6 +64,11 @@ public function members(): HasMany
|
||||
return $this->hasMany(CompositionMember::class)->orderBy('position');
|
||||
}
|
||||
|
||||
public function variants(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompositionVersionVariant::class)->orderBy('position');
|
||||
}
|
||||
|
||||
public function attestations(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompatibilityAttestation::class);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Durchführungsvariante einer Übungsfassung. Der Schlüssel ist je Fassung eindeutig und bleibt über Fassungen hinweg
|
||||
* gleich, damit eine Auswahl im Modul oder Programm und der Abgleich mit einer Quelle dieselbe Variante meinen.
|
||||
* Wie die Mitglieder ist sie nur im Entwurf der Fassung schreibbar.
|
||||
*/
|
||||
class CompositionVersionVariant extends Model
|
||||
{
|
||||
protected $fillable = ['composition_version_id', 'key', 'position', 'name', 'description', 'origin'];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (CompositionVersionVariant $variant): void {
|
||||
$status = CompositionVersion::query()->whereKey($variant->composition_version_id)->value('status');
|
||||
|
||||
if (StatusValue::of($status) === ContentVersionStatus::Bereit->value) {
|
||||
throw new DomainRuleException('Eine bestätigte Kompositionsfassung nimmt keine weiteren Varianten auf.');
|
||||
}
|
||||
});
|
||||
|
||||
static::updating(function (): void {
|
||||
throw new DomainRuleException('Varianten einer Komposition werden nicht verändert, sondern durch eine neue Fassung ersetzt.');
|
||||
});
|
||||
}
|
||||
|
||||
public function compositionVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ class ContentElement extends Model
|
||||
'preview_path',
|
||||
'editorial_content_kind_id',
|
||||
'archived_at',
|
||||
'source_ref',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
|
||||
@@ -5,9 +5,14 @@
|
||||
class ContentResolver
|
||||
{
|
||||
/**
|
||||
* @return list<array{version_id: int, role: string, path: string}>
|
||||
* Löst eine Wurzel zu den enthaltenen Medienfassungen auf. Eine Übung wird nur mit ihren gemeinsamen Mitgliedern und
|
||||
* den ausgewählten Varianten aufgelöst: Das Mitglied, das die Übungsfassung einbindet, trägt die Auswahl
|
||||
* (`variant_selection`, Liste von Variantenschlüsseln; leer gelassen bedeutet alle Varianten).
|
||||
*
|
||||
* @param list<string>|null $selection Variantenschlüssel, die für diese Fassung gelten; null = alle
|
||||
* @return list<array{version_id: int, role: string, path: string, requirement: string, variant: string|null}>
|
||||
*/
|
||||
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = []): array
|
||||
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = [], ?array $selection = null): array
|
||||
{
|
||||
if ($node instanceof ContentElementVersion) {
|
||||
$node->loadMissing('element');
|
||||
@@ -16,6 +21,8 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'version_id' => $node->id,
|
||||
'role' => $path,
|
||||
'path' => $path !== '' ? $path : $node->element->working_title,
|
||||
'requirement' => CompositionMember::REQUIRED,
|
||||
'variant' => null,
|
||||
]];
|
||||
}
|
||||
|
||||
@@ -26,7 +33,13 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
$stack[] = $node->composition_id;
|
||||
$rows = [];
|
||||
|
||||
foreach ($node->members()->orderBy('position')->get() as $member) {
|
||||
foreach ($node->members()->with('variant')->orderBy('position')->get() as $member) {
|
||||
$variantKey = $member->variant?->key;
|
||||
|
||||
if ($variantKey !== null && $selection !== null && ! in_array($variantKey, $selection, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$segment = $path === '' ? $member->role : $path.' / '.$member->role;
|
||||
|
||||
if ($member->content_element_version_id !== null) {
|
||||
@@ -34,6 +47,8 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'version_id' => $member->content_element_version_id,
|
||||
'role' => $member->role,
|
||||
'path' => $segment,
|
||||
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
|
||||
'variant' => $variantKey,
|
||||
];
|
||||
|
||||
continue;
|
||||
@@ -45,7 +60,20 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.');
|
||||
}
|
||||
|
||||
$rows = array_merge($rows, $this->expand($nested, $segment, $stack));
|
||||
// Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht auflösen (Rückfallschutz).
|
||||
// Veröffentlichen verweigern die aufrufenden Stellen über ForeignCompositions.
|
||||
$nested->loadMissing('composition');
|
||||
|
||||
if ($nested->composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows = array_merge($rows, $this->expand(
|
||||
$nested,
|
||||
$segment,
|
||||
$stack,
|
||||
is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null,
|
||||
));
|
||||
}
|
||||
|
||||
return $rows;
|
||||
|
||||
@@ -225,7 +225,9 @@ public function releaseElementVersion(ContentElementVersion $version): ContentEl
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
|
||||
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion, note?: string|null, variant?: string|null, requirement?: string|null, selection?: list<string>|null}> $members
|
||||
* @param array{learning_goal?: mixed, duration_minutes?: mixed, duration_max?: mixed, material_note?: mixed, prerequisites?: mixed} $didactic
|
||||
* @param list<array{key: string, name: string, description?: string|null, origin?: string}> $variants Durchführungsvarianten einer Übung
|
||||
*/
|
||||
public function publishComposition(
|
||||
Composition $composition,
|
||||
@@ -233,18 +235,21 @@ public function publishComposition(
|
||||
?User $confirmedBy = null,
|
||||
?string $note = null,
|
||||
array $didactic = [],
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
if ($members === []) {
|
||||
throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.');
|
||||
}
|
||||
|
||||
$variants = $this->checkedVariants($variants);
|
||||
$this->assertAcyclic($composition->id, $members);
|
||||
|
||||
foreach ($members as $member) {
|
||||
$this->assertReadyMember($member['target']);
|
||||
$this->assertMemberPlacement($member, $variants);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic): CompositionVersion {
|
||||
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic, $variants): CompositionVersion {
|
||||
$number = ((int) $composition->versions()->max('number')) + 1;
|
||||
$version = $composition->versions()->create([
|
||||
'number' => $number,
|
||||
@@ -253,28 +258,52 @@ public function publishComposition(
|
||||
'resolved_hash' => 'pending',
|
||||
'learning_goal' => $this->optionalText($didactic['learning_goal'] ?? null),
|
||||
'duration_minutes' => isset($didactic['duration_minutes']) ? (int) $didactic['duration_minutes'] : null,
|
||||
'duration_max' => isset($didactic['duration_max']) ? (int) $didactic['duration_max'] : null,
|
||||
'material_note' => $this->optionalText($didactic['material_note'] ?? null),
|
||||
'prerequisites' => $this->optionalText($didactic['prerequisites'] ?? null),
|
||||
'source_snapshot_id' => isset($didactic['source_snapshot_id']) ? (int) $didactic['source_snapshot_id'] : null,
|
||||
]);
|
||||
|
||||
$variantIds = [];
|
||||
|
||||
foreach ($variants as $index => $variant) {
|
||||
$variantIds[$variant['key']] = $version->variants()->create([
|
||||
'key' => $variant['key'],
|
||||
'position' => $index + 1,
|
||||
'name' => $variant['name'],
|
||||
'description' => $variant['description'],
|
||||
'origin' => $variant['origin'],
|
||||
])->id;
|
||||
}
|
||||
|
||||
foreach (array_values($members) as $index => $member) {
|
||||
$target = $member['target'];
|
||||
$selection = $target instanceof CompositionVersion ? ($member['selection'] ?? null) : null;
|
||||
$version->members()->create([
|
||||
'position' => $index + 1,
|
||||
'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'),
|
||||
'placement_note' => $this->optionalText($member['note'] ?? null),
|
||||
'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
||||
'nested_composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
|
||||
'variant_id' => isset($member['variant']) ? $variantIds[$member['variant']] : null,
|
||||
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
|
||||
'variant_selection' => $selection === null ? null : array_values($selection),
|
||||
'origin' => ($member['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
]);
|
||||
}
|
||||
|
||||
$version->load('members.variant', 'variants');
|
||||
$resolvedHash = $this->resolver->resolvedHash($version);
|
||||
$structureHash = $this->structureHash($version);
|
||||
$version->attestations()->create([
|
||||
'resolved_hash' => $resolvedHash,
|
||||
'structure_hash' => $structureHash,
|
||||
'confirmed_by' => $confirmedBy?->id,
|
||||
'confirmed_at' => now(),
|
||||
'note' => $note,
|
||||
]);
|
||||
$version->resolved_hash = $resolvedHash;
|
||||
$version->structure_hash = $structureHash;
|
||||
$version->status = ContentVersionStatus::Bereit;
|
||||
$version->save();
|
||||
|
||||
@@ -282,6 +311,103 @@ public function publishComposition(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Änderungsnachweis einer Fassung: Felder, Varianten und die Verwendung jedes Mitglieds. Anders als der
|
||||
* `resolved_hash` (nur die Menge der enthaltenen Medienfassungen) ändert er sich auch dann, wenn Variante,
|
||||
* Verwendung, Reihenfolge oder Variantenauswahl wechseln und die Medien gleich bleiben.
|
||||
*/
|
||||
public function structureHash(CompositionVersion $version): string
|
||||
{
|
||||
$version->loadMissing('members.variant', 'variants');
|
||||
|
||||
return hash('sha256', json_encode([
|
||||
'fields' => [
|
||||
$version->learning_goal,
|
||||
$version->duration_minutes,
|
||||
$version->duration_max,
|
||||
$version->material_note,
|
||||
$version->prerequisites,
|
||||
],
|
||||
'variants' => $version->variants->map(fn (CompositionVersionVariant $variant): array => [
|
||||
$variant->key, $variant->position, $variant->name, $variant->description, $variant->origin,
|
||||
])->all(),
|
||||
'members' => $version->members->map(fn (CompositionMember $member): array => [
|
||||
$member->position,
|
||||
$member->role,
|
||||
$member->placement_note,
|
||||
$member->content_element_version_id,
|
||||
$member->nested_composition_version_id,
|
||||
$member->variant?->key,
|
||||
$member->requirement,
|
||||
$member->variant_selection,
|
||||
$member->origin,
|
||||
])->all(),
|
||||
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{key?: string, name?: string, description?: string|null}> $variants
|
||||
* @return list<array{key: string, name: string, description: string|null}>
|
||||
*/
|
||||
private function checkedVariants(array $variants): array
|
||||
{
|
||||
$checked = [];
|
||||
$keys = [];
|
||||
|
||||
foreach (array_values($variants) as $variant) {
|
||||
$key = trim((string) ($variant['key'] ?? ''));
|
||||
|
||||
if ($key === '' || in_array($key, $keys, true)) {
|
||||
throw new DomainRuleException('Jede Variante braucht einen eigenen Schlüssel.');
|
||||
}
|
||||
|
||||
$keys[] = $key;
|
||||
$checked[] = [
|
||||
'key' => $key,
|
||||
'name' => $this->required((string) ($variant['name'] ?? ''), 'Jede Variante braucht einen Namen.'),
|
||||
'description' => $this->optionalText($variant['description'] ?? null),
|
||||
'origin' => ($variant['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
return $checked;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{target: ContentElementVersion|CompositionVersion, variant?: string|null, requirement?: string|null, selection?: list<string>|null} $member
|
||||
* @param list<array{key: string, name: string, description: string|null}> $variants
|
||||
*/
|
||||
private function assertMemberPlacement(array $member, array $variants): void
|
||||
{
|
||||
$variant = $member['variant'] ?? null;
|
||||
|
||||
if ($variant !== null && ! in_array($variant, array_column($variants, 'key'), true)) {
|
||||
throw new DomainRuleException('Ein Mitglied verweist auf eine Variante, die es in dieser Fassung nicht gibt.');
|
||||
}
|
||||
|
||||
$requirement = $member['requirement'] ?? CompositionMember::REQUIRED;
|
||||
|
||||
if (! in_array($requirement, [CompositionMember::REQUIRED, CompositionMember::SUPPLEMENTARY], true)) {
|
||||
throw new DomainRuleException('Die Verwendung eines Mitglieds ist erforderlich oder ergänzend.');
|
||||
}
|
||||
|
||||
$selection = $member['selection'] ?? null;
|
||||
|
||||
if ($selection === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $member['target'] instanceof CompositionVersion) {
|
||||
throw new DomainRuleException('Eine Variantenauswahl gibt es nur an einer eingebundenen Übungsfassung.');
|
||||
}
|
||||
|
||||
$offered = $member['target']->variants()->pluck('key')->all();
|
||||
|
||||
if ($selection === [] || array_diff($selection, $offered) !== []) {
|
||||
throw new DomainRuleException('Die Variantenauswahl nennt eine Variante, die die eingebundene Fassung nicht anbietet, oder keine.');
|
||||
}
|
||||
}
|
||||
|
||||
public function createComposition(string $designation, CompositionKind $kind = CompositionKind::Uebung): Composition
|
||||
{
|
||||
return Composition::query()->create([
|
||||
@@ -345,6 +471,10 @@ private function assertAcyclic(int $compositionId, array $members, array $stack
|
||||
|
||||
private function assertReadyMember(ContentElementVersion|CompositionVersion $target): void
|
||||
{
|
||||
if (app(ForeignCompositions::class)->reaches($target)) {
|
||||
throw new DomainRuleException('Dieser Bestandteil stammt aus einer neueren Programmversion und wird hier nicht in eine Fassung aufgenommen.');
|
||||
}
|
||||
|
||||
if ($target->status !== ContentVersionStatus::Bereit) {
|
||||
throw new DomainRuleException('Eine Komposition darf nur bereitgestellte Fassungen enthalten.');
|
||||
}
|
||||
@@ -365,6 +495,9 @@ private function membersHash(array $members): string
|
||||
'note' => $this->optionalText($member['note'] ?? null),
|
||||
'element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
||||
'composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
|
||||
'variant' => $member['variant'] ?? null,
|
||||
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
|
||||
'selection' => $member['selection'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ class EditorialContentKind extends Model
|
||||
public const CONTEXTS = [
|
||||
'medium' => 'Medium',
|
||||
'modul' => 'Modul',
|
||||
'uebung' => 'Übung',
|
||||
'programm' => 'Programm',
|
||||
'lizenzartikel' => 'Lizenzartikel',
|
||||
];
|
||||
@@ -26,7 +27,7 @@ class EditorialContentKind extends Model
|
||||
* Modulen (programm, modul), Vertraulichkeit von Traineranleitungen (traineranleitung). Ihre Bezeichnung bleibt
|
||||
* pflegbar; deaktivieren, Kontexte ändern und löschen sind gesperrt.
|
||||
*/
|
||||
public const SYSTEM_SLUGS = ['programm', 'modul', 'traineranleitung'];
|
||||
public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'traineranleitung'];
|
||||
|
||||
protected $fillable = [
|
||||
'slug',
|
||||
|
||||
@@ -20,20 +20,15 @@ public function values(): HasMany
|
||||
}
|
||||
|
||||
/**
|
||||
* Inhaltselemente pflegen Themen über die Säulen, nicht noch einmal über die Dimension.
|
||||
* Module, Programme und Lizenzartikel haben keine Säulenauswahl und behalten die Dimension.
|
||||
* Fachliche Säulen werden für alle Objektarten über die zentrale Säulenverwaltung gewählt (`pillars`), nie über
|
||||
* eine Dimension. Die alte Dimension „Fachliche Säule“ bleibt nur als Verlauf in der Datenbank und wird nirgends
|
||||
* mehr angeboten, geändert oder gefiltert.
|
||||
*
|
||||
* @return Collection<int, self>
|
||||
*/
|
||||
public static function forSubject(Model $subject): Collection
|
||||
{
|
||||
$query = static::query()->with('values')->orderBy('label');
|
||||
|
||||
if ($subject instanceof ContentElement) {
|
||||
$query->where('slug', '!=', self::PILLAR_SLUG);
|
||||
}
|
||||
|
||||
return $query->get();
|
||||
return static::query()->with('values')->where('slug', '!=', self::PILLAR_SLUG)->orderBy('label')->get();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
class EditorialDimensionValue extends Model
|
||||
{
|
||||
protected $fillable = ['editorial_dimension_id', 'slug', 'label', 'sort_order', 'is_active'];
|
||||
protected $fillable = ['editorial_dimension_id', 'pillar_id', 'slug', 'label', 'sort_order', 'is_active'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
|
||||
@@ -46,6 +46,7 @@ public static function compositionContext(?CompositionKind $kind): ?string
|
||||
return match ($kind) {
|
||||
CompositionKind::Kurs => 'programm',
|
||||
CompositionKind::Uebung => 'modul',
|
||||
CompositionKind::Exercise => 'uebung',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
@@ -137,6 +138,7 @@ private function usedKindIds(string $context): array
|
||||
'lizenzartikel' => DB::table('license_articles'),
|
||||
'programm' => DB::table('compositions')->where('kind', CompositionKind::Kurs->value),
|
||||
'modul' => DB::table('compositions')->where('kind', CompositionKind::Uebung->value),
|
||||
'uebung' => DB::table('compositions')->where('kind', CompositionKind::Exercise->value),
|
||||
default => null,
|
||||
};
|
||||
|
||||
@@ -181,13 +183,13 @@ public function dimensionGroups(Model $subject, array $assignedIds): array
|
||||
* @param list<int> $selectedIds
|
||||
* @return list<array{label: string, values: list<array{id: int, label: string}>}>
|
||||
*/
|
||||
public function dimensionFilterGroups(array $selectedIds = [], bool $withPillars = true): array
|
||||
public function dimensionFilterGroups(array $selectedIds = []): array
|
||||
{
|
||||
$used = DB::table('identity_dimension_values')->distinct()->pluck('editorial_dimension_value_id')->map(fn ($id): int => (int) $id)->all();
|
||||
$groups = [];
|
||||
|
||||
foreach (EditorialDimension::query()->with('values')->orderBy('label')->get() as $dimension) {
|
||||
if (! $withPillars && $dimension->slug === EditorialDimension::PILLAR_SLUG) {
|
||||
if ($dimension->slug === EditorialDimension::PILLAR_SLUG) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -217,7 +219,7 @@ public function dimensionFilterGroups(array $selectedIds = [], bool $withPillars
|
||||
*/
|
||||
public function memberFilterDimensions(array $selectedIds = []): Collection
|
||||
{
|
||||
$dimensions = EditorialDimension::query()->with('values')->orderBy('label')->get();
|
||||
$dimensions = EditorialDimension::query()->with('values')->where('slug', '!=', EditorialDimension::PILLAR_SLUG)->orderBy('label')->get();
|
||||
|
||||
foreach ($dimensions as $dimension) {
|
||||
$dimension->setRelation('values', $dimension->values
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Entitlement\DecideAccess;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Http\LibraryCatalog;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Die Anleitung einer Übung, wie ein Stand sie festschreibt: die im Stand gebundene Übungsfassung, die angebotenen
|
||||
* Varianten und je Abschnitt oder Medium die Entscheidung der zentralen Rechteprüfung (`DecideAccess`). Ansicht und
|
||||
* PDF lesen dieses Ergebnis und zeigen damit dieselbe Fassung.
|
||||
*
|
||||
* Eine Sperre oder fehlende Berechtigung betrifft nur den betroffenen Abschnitt oder das Medium. Anleitung und übrige
|
||||
* Inhalte bleiben im selben Stand erreichbar. Fehlt in einer Variante ein erforderlicher Bestandteil, gilt die Variante
|
||||
* als derzeit nicht vollständig durchführbar; ein ergänzender Bestandteil entfällt mit einem Hinweis.
|
||||
*/
|
||||
class ExerciseGuide
|
||||
{
|
||||
public function __construct(private readonly DecideAccess $access) {}
|
||||
|
||||
/**
|
||||
* Darf dieses Konto den Stand überhaupt sehen? Aktive, nutzbare Berechtigung auf den Artikel und ein auslieferbarer
|
||||
* Stand. Über die einzelnen Inhalte entscheidet danach `DecideAccess`.
|
||||
*/
|
||||
public function mayOpen(User $user, LicenseArticle $article, ArticleRelease $release): bool
|
||||
{
|
||||
if ($release->license_article_id !== $article->id
|
||||
|| ! in_array($release->status, [ReleaseStatus::Veroeffentlicht, ReleaseStatus::AbgeloestVerfuegbar], true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Grant::query()
|
||||
->where('license_article_id', $article->id)
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->usableBy($user)
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Übungsfassung an einer Stelle des Stands. Der Pfad nennt die Positionen der Mitglieder von der Wurzel des
|
||||
* Stands abwärts („2“ oder „1-3“). So ist auch dieselbe Übung an zwei Stellen eines Produkts unterscheidbar.
|
||||
*
|
||||
* @return array{version: CompositionVersion, selection: list<string>|null}|null
|
||||
*/
|
||||
public function locate(ArticleRelease $release, string $path): ?array
|
||||
{
|
||||
if (preg_match('/^\d+(-\d+)*$/', $path) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$version = $release->rootCompositionVersion;
|
||||
$selection = null;
|
||||
|
||||
foreach (array_map('intval', explode('-', $path)) as $position) {
|
||||
if ($version === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$member = $version->members()->where('position', $position)->first();
|
||||
|
||||
if ($member === null || $member->nested_composition_version_id === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$selection = is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null;
|
||||
$version = $member->nestedCompositionVersion;
|
||||
}
|
||||
|
||||
$version?->loadMissing('composition');
|
||||
|
||||
if ($version === null || $version->composition === null || $version->composition->kind !== CompositionKind::Exercise) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['version' => $version, 'selection' => $selection];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pfad zur ersten Stelle, an der die Wurzel die Übungsfassung einbindet.
|
||||
*/
|
||||
public function pathTo(CompositionVersion $root, int $versionId, array $stack = []): ?string
|
||||
{
|
||||
if (in_array($root->id, $stack, true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($root->members()->orderBy('position')->get() as $member) {
|
||||
if ($member->nested_composition_version_id === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($member->nested_composition_version_id === $versionId) {
|
||||
return (string) $member->position;
|
||||
}
|
||||
|
||||
$below = $this->pathTo($member->nestedCompositionVersion, $versionId, [...$stack, $root->id]);
|
||||
|
||||
if ($below !== null) {
|
||||
return $member->position.'-'.$below;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string>|null $selection angebotene Variantenschlüssel; null = alle
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function build(User $user, LicenseArticle $article, ArticleRelease $release, CompositionVersion $exercise, ?array $selection, ?string $variantKey = null): array
|
||||
{
|
||||
$exercise->loadMissing(['composition', 'variants', 'members.variant', 'members.contentElementVersion.element']);
|
||||
$library = app(LibraryCatalog::class);
|
||||
$offered = $exercise->variants->filter(fn (CompositionVersionVariant $variant): bool => $selection === null || in_array($variant->key, $selection, true))->values();
|
||||
$chosen = $offered->firstWhere('key', $variantKey) ?? $offered->first();
|
||||
$entries = [];
|
||||
|
||||
foreach ($exercise->members as $member) {
|
||||
$version = $member->contentElementVersion;
|
||||
|
||||
if ($version === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = $member->variant?->key;
|
||||
$class = (string) $version->element->output_class;
|
||||
$action = in_array($class, ['film', 'audio'], true) ? 'streamen' : 'ansehen';
|
||||
$decision = ($this->access)($user, $article, $release, $version, $action);
|
||||
$download = $action === 'ansehen' ? ($this->access)($user, $article, $release, $version, 'laden') : null;
|
||||
|
||||
$entries[] = [
|
||||
'variant' => $key,
|
||||
'role' => $member->role,
|
||||
'note' => $member->placement_note,
|
||||
'title' => $library->text($version->element)['title'] ?: $version->element->working_title,
|
||||
'class' => $class,
|
||||
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
|
||||
'action' => $action,
|
||||
'version' => $version,
|
||||
'allowed' => $decision->allowed,
|
||||
'may_download' => $download?->allowed ?? false,
|
||||
'grant' => $decision->grant,
|
||||
'download_grant' => $download?->grant,
|
||||
'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
|
||||
'blocks' => $decision->allowed && $class === 'text' ? GuideText::blocks($version->body) : null,
|
||||
];
|
||||
}
|
||||
|
||||
$variants = $offered->map(function (CompositionVersionVariant $variant) use ($entries): array {
|
||||
$missing = array_values(array_filter($entries, fn (array $entry): bool => ($entry['variant'] === null || $entry['variant'] === $variant->key)
|
||||
&& $entry['requirement'] === CompositionMember::REQUIRED
|
||||
&& ! $entry['allowed']));
|
||||
|
||||
return [
|
||||
'key' => $variant->key,
|
||||
'name' => $variant->name,
|
||||
'description' => $variant->description,
|
||||
'complete' => $missing === [],
|
||||
'missing' => array_map(fn (array $entry): string => $entry['title'], $missing),
|
||||
];
|
||||
})->all();
|
||||
|
||||
$shown = array_values(array_filter($entries, fn (array $entry): bool => $entry['variant'] === null || $entry['variant'] === $chosen?->key));
|
||||
|
||||
return [
|
||||
'exercise' => $exercise,
|
||||
'title' => $library->text($exercise->composition)['title'],
|
||||
'summary' => $library->text($exercise->composition)['summary'],
|
||||
'learning_goal' => $exercise->learning_goal,
|
||||
'duration_minutes' => $exercise->duration_minutes,
|
||||
'duration_max' => $exercise->duration_max,
|
||||
'prerequisites' => $exercise->prerequisites,
|
||||
'material_note' => $exercise->material_note,
|
||||
'variants' => $variants,
|
||||
'chosen' => $chosen?->key,
|
||||
'entries' => $shown,
|
||||
'entry_total' => count($entries),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ExerciseImportRun extends Model
|
||||
{
|
||||
protected $fillable = ['source_system', 'status', 'cursor', 'added', 'updated', 'removed', 'error', 'started_at', 'finished_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['started_at' => 'datetime', 'finished_at' => 'datetime'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Commerce\Receipt\PdfDocument;
|
||||
use Transliterator;
|
||||
|
||||
/**
|
||||
* Druckbare Ausgabe einer Übung (DIN A4, mehrere Seiten) aus demselben Ergebnis wie die Ansicht ({@see ExerciseGuide}).
|
||||
* Kennzeichnung: Fußzeile mit Lizenznehmer und Lizenzkopie auf jeder Seite (K2) und die Kennung in den Metadaten (K1).
|
||||
* Das Dokument wird bei jedem Abruf neu erzeugt und nie abgelegt, damit eine spätere Sperre keine ältere Kopie
|
||||
* ausliefern kann.
|
||||
*/
|
||||
class ExercisePdf
|
||||
{
|
||||
private const LEFT = 56.0;
|
||||
|
||||
private const RIGHT = 539.0;
|
||||
|
||||
private const TOP = 790.0;
|
||||
|
||||
private const BOTTOM = 72.0;
|
||||
|
||||
private PdfDocument $pdf;
|
||||
|
||||
private float $y = self::TOP;
|
||||
|
||||
private int $page = 0;
|
||||
|
||||
private string $footer = '';
|
||||
|
||||
/**
|
||||
* Welche Abschnitte gehören ins PDF? Erforderliche Textabschnitte der Auswahl müssen für `laden` zulässig sein, sonst
|
||||
* ist das PDF nicht erlaubt (null). Ergänzende ohne Berechtigung entfallen. Videos und Dokumente erscheinen nur als
|
||||
* Hinweis.
|
||||
*
|
||||
* @param array<string, mixed> $guide Ergebnis von {@see ExerciseGuide::build}
|
||||
* @return list<array<string, mixed>>|null
|
||||
*/
|
||||
public function sections(array $guide): ?array
|
||||
{
|
||||
$included = [];
|
||||
|
||||
foreach ($guide['entries'] as $entry) {
|
||||
if ($entry['class'] === 'text') {
|
||||
if ($entry['may_download'] && $entry['allowed']) {
|
||||
$included[] = $entry;
|
||||
} elseif ($entry['requirement'] === CompositionMember::REQUIRED) {
|
||||
return null;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($entry['allowed']) {
|
||||
$included[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
return array_filter($included, fn (array $entry): bool => $entry['class'] === 'text') === [] ? null : $included;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $guide
|
||||
* @param list<array<string, mixed>> $sections
|
||||
*/
|
||||
public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl): string
|
||||
{
|
||||
$this->pdf = new PdfDocument;
|
||||
$this->page = 0;
|
||||
$this->footer = self::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId);
|
||||
$this->newPage();
|
||||
|
||||
$this->write(self::printable((string) $guide['title']), 18, true, 8);
|
||||
|
||||
if ($variantName !== '') {
|
||||
$this->write(self::printable('Variante: '.$variantName), 11, true, 6);
|
||||
}
|
||||
|
||||
$facts = array_filter([
|
||||
filled($guide['learning_goal']) ? 'Lernziel: '.$guide['learning_goal'] : null,
|
||||
$guide['duration_minutes'] !== null ? 'Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten' : null,
|
||||
filled($guide['prerequisites']) ? 'Voraussetzungen: '.$guide['prerequisites'] : null,
|
||||
filled($guide['material_note']) ? 'Ausstattung: '.$guide['material_note'] : null,
|
||||
]);
|
||||
|
||||
foreach ($facts as $fact) {
|
||||
$this->write(self::printable($fact), 10.5, false, 4);
|
||||
}
|
||||
|
||||
$this->y -= 6;
|
||||
|
||||
foreach ($sections as $section) {
|
||||
$this->section($section, $guideUrl);
|
||||
}
|
||||
|
||||
$this->closePage();
|
||||
|
||||
$ascii = Transliterator::create('Any-Latin; Latin-ASCII');
|
||||
|
||||
return $this->pdf->output($ascii?->transliterate((string) $guide['title']) ?: 'Uebung', 'Lizenzkopie '.$copyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere
|
||||
* lateinische Buchstaben); sonst bleibt „?“.
|
||||
*/
|
||||
public static function printable(string $text): string
|
||||
{
|
||||
$text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']);
|
||||
$latin = Transliterator::create('Any-Latin; Latin-ASCII');
|
||||
$out = '';
|
||||
|
||||
foreach (mb_str_split($text) as $char) {
|
||||
$encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8');
|
||||
$out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char;
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $section
|
||||
*/
|
||||
private function section(array $section, string $guideUrl): void
|
||||
{
|
||||
$title = self::printable((string) $section['title']);
|
||||
|
||||
if ($section['class'] !== 'text') {
|
||||
$label = in_array($section['class'], ['film', 'audio'], true)
|
||||
? 'Film: '.$title.' - online abrufbar im Mitgliederbereich (geschützte Wiedergabe): '.$guideUrl
|
||||
: 'Material: '.$title.' - im Mitgliederbereich abrufbar: '.$guideUrl;
|
||||
$this->write(self::printable($label), 10, false, 6);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->write($title, 12.5, true, 5);
|
||||
|
||||
foreach ($section['blocks'] ?? [] as $block) {
|
||||
match ($block['type']) {
|
||||
'heading' => $this->write(self::printable($block['text']), 11, true, 4),
|
||||
'paragraph' => $this->write(self::printable($block['text']), 10.5, false, 5),
|
||||
'bullets' => $this->items($block['items'], fn (int $n): string => '•'),
|
||||
'numbered' => $this->items($block['items'], fn (int $n): string => $n.'.'),
|
||||
};
|
||||
}
|
||||
|
||||
$this->y -= 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $items
|
||||
*/
|
||||
private function items(array $items, callable $marker): void
|
||||
{
|
||||
foreach ($items as $index => $item) {
|
||||
$lines = PdfDocument::wrap(self::printable($item), self::RIGHT - self::LEFT - 18, 10.5);
|
||||
|
||||
foreach ($lines as $line => $text) {
|
||||
$this->room(14);
|
||||
|
||||
if ($line === 0) {
|
||||
$this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5);
|
||||
}
|
||||
|
||||
$this->pdf->text(self::LEFT + 18, $this->y, $text, 10.5);
|
||||
$this->y -= 14;
|
||||
}
|
||||
}
|
||||
|
||||
$this->y -= 3;
|
||||
}
|
||||
|
||||
private function write(string $text, float $size, bool $bold, float $after): void
|
||||
{
|
||||
foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) {
|
||||
$this->room($size + 4);
|
||||
$this->pdf->text(self::LEFT, $this->y, $line, $size, $bold);
|
||||
$this->y -= $size + 4;
|
||||
}
|
||||
|
||||
$this->y -= $after;
|
||||
}
|
||||
|
||||
private function room(float $needed): void
|
||||
{
|
||||
if ($this->y - $needed < self::BOTTOM) {
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}
|
||||
}
|
||||
|
||||
private function newPage(): void
|
||||
{
|
||||
$this->pdf->addPage();
|
||||
$this->page++;
|
||||
$this->y = self::TOP;
|
||||
}
|
||||
|
||||
private function closePage(): void
|
||||
{
|
||||
$this->pdf->line(self::LEFT, 54, self::RIGHT, 54, 0.4);
|
||||
$this->pdf->text(self::LEFT, 40, $this->footer, 8);
|
||||
$this->pdf->textRight(self::RIGHT, 40, 'Seite '.$this->page, 8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Eine Übung der Quelle, gebunden an ihre stabile Kennung. `availability` hält nur fest, ob die Quelle sie noch
|
||||
* bereitstellt. Das ist kein Rechtsvorgang: Eine rechtliche Sperre ist der lokale `block`.
|
||||
*/
|
||||
class ExerciseSource extends Model
|
||||
{
|
||||
public const PROVIDED = 'bereitgestellt';
|
||||
|
||||
public const WITHDRAWN = 'nicht_mehr_bereitgestellt';
|
||||
|
||||
protected $fillable = ['source_system', 'source_id', 'composition_id', 'title', 'availability', 'last_hash', 'last_seen_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['last_seen_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
public function snapshots(): HasMany
|
||||
{
|
||||
return $this->hasMany(ExerciseSourceSnapshot::class)->orderBy('id');
|
||||
}
|
||||
|
||||
public function latestSnapshot(): ?ExerciseSourceSnapshot
|
||||
{
|
||||
return $this->snapshots()->reorder()->orderByDesc('id')->first();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Ein abgerufener Inhaltsstand einer Quellübung (Prüfsumme der Quelle und ihre Nutzlast). Er ist unveränderlich;
|
||||
* nur die Übernahme trägt die daraus entstandene lokale Fassung ein.
|
||||
*/
|
||||
class ExerciseSourceSnapshot extends Model
|
||||
{
|
||||
protected $fillable = ['exercise_source_id', 'content_hash', 'payload', 'adopted_version_id', 'fetched_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['payload' => 'array', 'fetched_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function source(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ExerciseSource::class, 'exercise_source_id');
|
||||
}
|
||||
|
||||
public function adoptedVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class, 'adopted_version_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Verwendungsnachweis: Wo wird eine Übungsfassung tatsächlich verwendet, und was trifft eine Sperre? Der Nachweis steigt
|
||||
* über die Verschachtelung bis zu den Wurzeln der Artikel-Stände auf und erfasst damit auch ältere, abgelöste und
|
||||
* gesperrte Stände. Er liest nur und ändert keinen Stand.
|
||||
*/
|
||||
class ExerciseUsage
|
||||
{
|
||||
/**
|
||||
* Je Fassung der Komposition: die einbindenden Fassungen (mit Rolle, Position und Variantenauswahl) und die
|
||||
* Artikel-Stände, deren Wurzel die Fassung selbst oder eine einbindende Fassung ist.
|
||||
*
|
||||
* @return list<array{version: CompositionVersion, hosts: list<array<string, mixed>>, releases: list<array<string, mixed>>}>
|
||||
*/
|
||||
public function forComposition(Composition $composition): array
|
||||
{
|
||||
$guide = app(ExerciseGuide::class);
|
||||
$result = [];
|
||||
|
||||
foreach ($composition->versions()->orderBy('number')->get() as $version) {
|
||||
$hosts = [];
|
||||
$roots = [$version->id => $version];
|
||||
$queue = [$version->id];
|
||||
$seen = [$version->id];
|
||||
|
||||
while ($queue !== []) {
|
||||
$current = array_shift($queue);
|
||||
|
||||
foreach (CompositionMember::query()->where('nested_composition_version_id', $current)->with('compositionVersion.composition')->orderBy('id')->get() as $member) {
|
||||
$host = $member->compositionVersion;
|
||||
|
||||
if ($host === null || $host->composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hosts[] = [
|
||||
'composition' => $host->composition,
|
||||
'version' => $host,
|
||||
'role' => $member->role,
|
||||
'position' => $member->position,
|
||||
'selection' => $member->variant_selection,
|
||||
'direct' => $current === $version->id,
|
||||
];
|
||||
|
||||
if (! in_array($host->id, $seen, true)) {
|
||||
$seen[] = $host->id;
|
||||
$roots[$host->id] = $host;
|
||||
$queue[] = $host->id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$releases = [];
|
||||
|
||||
foreach (ArticleRelease::query()->whereIn('root_composition_version_id', array_keys($roots))->with('article')->orderBy('license_article_id')->orderBy('number')->get() as $release) {
|
||||
$root = $roots[$release->root_composition_version_id];
|
||||
$releases[] = [
|
||||
'article' => $release->article,
|
||||
'release' => $release,
|
||||
'status' => $release->status,
|
||||
'path' => $root->id === $version->id ? null : $guide->pathTo($root, $version->id),
|
||||
'root' => $root,
|
||||
];
|
||||
}
|
||||
|
||||
$result[] = ['version' => $version, 'hosts' => $hosts, 'releases' => $releases];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Folgen einer Sperre dieser Medienfassung je Artikel-Stand. Die Festschreibung bleibt unverändert; gesperrt wird
|
||||
* nur die Ausgabe des Mediums.
|
||||
*
|
||||
* @return list<array{article: LicenseArticle, release: ArticleRelease, status: ReleaseStatus, variant: string|null, requirement: string|null, path: string, effect: string}>
|
||||
*/
|
||||
public function blockImpact(ContentElementVersion $version): array
|
||||
{
|
||||
$impact = [];
|
||||
|
||||
foreach (ReleaseContent::query()->where('content_element_version_id', $version->id)->with('release.article')->orderBy('id')->get() as $content) {
|
||||
$release = $content->release;
|
||||
$required = ($content->requirement ?? CompositionMember::REQUIRED) === CompositionMember::REQUIRED;
|
||||
$effect = match (true) {
|
||||
! $required => 'Nur dieses ergänzende Medium entfällt. Die Übung bleibt vollständig durchführbar.',
|
||||
$content->variant_key !== null => 'Die Variante „'.$content->variant_key.'“ ist nicht mehr vollständig durchführbar. Andere Varianten bleiben nutzbar.',
|
||||
default => 'Ein erforderlicher Bestandteil entfällt. Die Anleitung bleibt lesbar.',
|
||||
};
|
||||
$impact[] = [
|
||||
'article' => $release->article,
|
||||
'release' => $release,
|
||||
'status' => $release->status,
|
||||
'variant' => $content->variant_key,
|
||||
'requirement' => $content->requirement,
|
||||
'path' => $content->path,
|
||||
'effect' => $effect,
|
||||
];
|
||||
}
|
||||
|
||||
return $impact;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Erkennt Kompositionen, deren Art dieser Programmstand nicht kennt (siehe {@see SupportedKindScope}), und Aufbauten, die
|
||||
* solche Bestandteile enthalten. Gelesen wird am Modell vorbei, weil der Bereichsfilter diese Zeilen ausblendet.
|
||||
*
|
||||
* Wozu: Eine ältere Programmversion darf eine Fassung mit unbekanntem Bestandteil weder neu veröffentlichen noch
|
||||
* überarbeiten. Sie würde den Bestandteil auslassen oder ohne seine Variantenwahl auflösen und damit Inhalt verlieren
|
||||
* oder zu viel ausgeben.
|
||||
*/
|
||||
class ForeignCompositions
|
||||
{
|
||||
public function isForeignVersion(int $compositionVersionId): bool
|
||||
{
|
||||
return DB::table('composition_versions as v')
|
||||
->join('compositions as c', 'c.id', '=', 'v.composition_id')
|
||||
->where('v.id', $compositionVersionId)
|
||||
->whereNotIn('c.kind', CompositionKind::values())
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $target „composition:ID“ (Fassung) oder „composition-draft:ID“ (Komposition)
|
||||
*/
|
||||
public function isForeignTarget(string $target): bool
|
||||
{
|
||||
if (preg_match('/^composition:(\d+)$/', $target, $match) === 1) {
|
||||
return $this->isForeignVersion((int) $match[1]);
|
||||
}
|
||||
|
||||
if (preg_match('/^composition-draft:(\d+)$/', $target, $match) === 1) {
|
||||
return DB::table('compositions')
|
||||
->where('id', (int) $match[1])
|
||||
->whereNotIn('kind', CompositionKind::values())
|
||||
->exists();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ist die Fassung selbst unbekannt oder erreicht sie, auch verschachtelt, einen unbekannten Bestandteil?
|
||||
*/
|
||||
public function reaches(ContentElementVersion|CompositionVersion $node): bool
|
||||
{
|
||||
return $node instanceof CompositionVersion && $this->reachesVersion($node->id, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enthält irgendeine Fassung dieser Komposition einen unbekannten Bestandteil?
|
||||
*/
|
||||
public function compositionHasForeignMembers(int $compositionId): bool
|
||||
{
|
||||
return DB::table('composition_members as m')
|
||||
->join('composition_versions as host', 'host.id', '=', 'm.composition_version_id')
|
||||
->join('composition_versions as nested', 'nested.id', '=', 'm.nested_composition_version_id')
|
||||
->join('compositions as c', 'c.id', '=', 'nested.composition_id')
|
||||
->where('host.composition_id', $compositionId)
|
||||
->whereNotIn('c.kind', CompositionKind::values())
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $seen
|
||||
*/
|
||||
private function reachesVersion(int $versionId, array $seen): bool
|
||||
{
|
||||
if (in_array($versionId, $seen, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->isForeignVersion($versionId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$seen[] = $versionId;
|
||||
|
||||
foreach (DB::table('composition_members')
|
||||
->where('composition_version_id', $versionId)
|
||||
->whereNotNull('nested_composition_version_id')
|
||||
->pluck('nested_composition_version_id') as $nestedId) {
|
||||
if ($this->reachesVersion((int) $nestedId, $seen)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Anleitungstext als Klartext mit wenigen Konventionen: Absätze an Leerzeilen, Listen mit „- “ oder „• “ und
|
||||
* nummerierte Listen mit „1. “, Zwischenüberschriften mit „## “. Ansicht und PDF lesen dieselben Blöcke und zeigen damit
|
||||
* dieselbe Fassung. Es gibt kein freies HTML.
|
||||
*/
|
||||
final class GuideText
|
||||
{
|
||||
/**
|
||||
* @return list<array{type: 'paragraph'|'bullets'|'numbered'|'heading', text?: string, items?: list<string>}>
|
||||
*/
|
||||
public static function blocks(?string $body): array
|
||||
{
|
||||
$blocks = [];
|
||||
$paragraph = [];
|
||||
$list = null;
|
||||
|
||||
$flushParagraph = function () use (&$blocks, &$paragraph): void {
|
||||
if ($paragraph !== []) {
|
||||
$blocks[] = ['type' => 'paragraph', 'text' => implode(' ', $paragraph)];
|
||||
$paragraph = [];
|
||||
}
|
||||
};
|
||||
$flushList = function () use (&$blocks, &$list): void {
|
||||
if ($list !== null) {
|
||||
$blocks[] = ['type' => $list['type'], 'items' => $list['items']];
|
||||
$list = null;
|
||||
}
|
||||
};
|
||||
|
||||
foreach (preg_split('/\R/u', trim((string) $body)) ?: [] as $line) {
|
||||
$line = rtrim($line);
|
||||
|
||||
if (trim($line) === '') {
|
||||
$flushParagraph();
|
||||
$flushList();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^##\s+(.+)$/u', $line, $match) === 1) {
|
||||
$flushParagraph();
|
||||
$flushList();
|
||||
$blocks[] = ['type' => 'heading', 'text' => trim($match[1])];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^\s*(?:[-•*])\s+(.+)$/u', $line, $match) === 1) {
|
||||
$flushParagraph();
|
||||
if ($list === null || $list['type'] !== 'bullets') {
|
||||
$flushList();
|
||||
$list = ['type' => 'bullets', 'items' => []];
|
||||
}
|
||||
|
||||
$list['items'][] = trim($match[1]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^\s*\d+[.)]\s+(.+)$/u', $line, $match) === 1) {
|
||||
$flushParagraph();
|
||||
if ($list === null || $list['type'] !== 'numbered') {
|
||||
$flushList();
|
||||
$list = ['type' => 'numbered', 'items' => []];
|
||||
}
|
||||
|
||||
$list['items'][] = trim($match[1]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$flushList();
|
||||
$paragraph[] = trim($line);
|
||||
}
|
||||
|
||||
$flushParagraph();
|
||||
$flushList();
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Übernimmt die frühere Kopie „Fachliche Säule“ (Dimension `saeule`) in die zentrale Säulenverwaltung (Tabelle
|
||||
* `pillars`). Verlustfrei, wiederholbar und ohne Raten:
|
||||
*
|
||||
* - **Zuordnung Wert → Säule** nur über die gespeicherte Kennung `pfeiler-{Säulenkennung}`, die die Migration
|
||||
* vom 16.11.2026 beim Spiegeln geschrieben hat, und nur, wenn die Säule existiert und nicht jünger als der Wert ist
|
||||
* (sonst kann die Kennung nicht aus ihr entstanden sein). Eine abweichende Bezeichnung ist nach einem Umbenennen
|
||||
* erwartet und wird nur berichtet. Die Verknüpfung steht in `editorial_dimension_values.pillar_id`.
|
||||
* - **Übernommen** werden nur direkte Zuordnungen von Modulen, Programmen und Lizenzartikeln in `composition_pillar`
|
||||
* und `license_article_pillar` (insert-or-ignore, daher beliebig oft ausführbar).
|
||||
* - **Nicht übernommen, sondern gemeldet:** Werte ohne belastbare Kennung, Zuordnungen zu fehlenden Objekten,
|
||||
* abgeleitete Zuordnungen und unbekannte Objektarten. Abgeleitete Säulen eines Programms oder Moduls entstehen zur
|
||||
* Laufzeit aus den enthaltenen Medien und werden nie als direkte Zuordnung gespeichert.
|
||||
* - **Medien:** Die gespiegelten Zeilen sind eine veraltete Kopie; maßgeblich ist `content_element_pillar`. Sie werden
|
||||
* nicht zurückgemischt, nur gezählt.
|
||||
* - Alte Zeilen werden weder geändert noch gelöscht.
|
||||
*
|
||||
* Nur die Datenbankfassade, damit spätere Änderungen an Modellen die Migration nicht berühren.
|
||||
*/
|
||||
final class LegacyPillarAdoption
|
||||
{
|
||||
/** @var array<string, array{table: string, column: string, subjects: string}> */
|
||||
private const TARGETS = [
|
||||
'composition' => ['table' => 'composition_pillar', 'column' => 'composition_id', 'subjects' => 'compositions'],
|
||||
'license_article' => ['table' => 'license_article_pillar', 'column' => 'license_article_id', 'subjects' => 'license_articles'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* mapping: list<array<string, mixed>>,
|
||||
* unresolved: list<array<string, mixed>>,
|
||||
* copied: array<string, int>,
|
||||
* already: array<string, int>,
|
||||
* before: array<string, int>,
|
||||
* after: array<string, int>,
|
||||
* mirror: array<string, int>
|
||||
* }
|
||||
*/
|
||||
public function run(bool $dryRun = false): array
|
||||
{
|
||||
$report = [
|
||||
'mapping' => [],
|
||||
'unresolved' => [],
|
||||
'copied' => ['composition' => 0, 'license_article' => 0],
|
||||
'already' => ['composition' => 0, 'license_article' => 0],
|
||||
'before' => $this->counts(),
|
||||
'after' => [],
|
||||
'mirror' => ['element_rows' => 0, 'missing_in_pivot' => 0, 'only_in_pivot' => 0],
|
||||
];
|
||||
|
||||
$dimension = DB::table('editorial_dimensions')->where('slug', 'saeule')->first();
|
||||
|
||||
if ($dimension === null) {
|
||||
$report['after'] = $report['before'];
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
$resolved = [];
|
||||
|
||||
foreach (DB::table('editorial_dimension_values')->where('editorial_dimension_id', $dimension->id)->orderBy('id')->get() as $value) {
|
||||
$pillar = $this->pillarFor($value);
|
||||
|
||||
if (is_string($pillar)) {
|
||||
$report['unresolved'][] = ['art' => 'Wert', 'wert_id' => (int) $value->id, 'wert' => $value->label, 'kennung' => $value->slug, 'grund' => $pillar];
|
||||
$report['mapping'][] = ['wert_id' => (int) $value->id, 'wert' => $value->label, 'saeule_id' => null, 'status' => 'offen'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$resolved[(int) $value->id] = (int) $pillar->id;
|
||||
$status = $value->pillar_id === null ? 'zugeordnet' : 'bereits zugeordnet';
|
||||
$hint = $value->label !== $pillar->name ? 'über Kennung zugeordnet, Bezeichnung weicht ab („'.$pillar->name.'“)' : null;
|
||||
$report['mapping'][] = ['wert_id' => (int) $value->id, 'wert' => $value->label, 'saeule_id' => (int) $pillar->id, 'saeule' => $pillar->name, 'status' => $status, 'hinweis' => $hint];
|
||||
|
||||
if ($value->pillar_id === null && ! $dryRun) {
|
||||
DB::table('editorial_dimension_values')->where('id', $value->id)->update(['pillar_id' => $pillar->id]);
|
||||
}
|
||||
}
|
||||
|
||||
$subjectTypes = $this->subjectTypes();
|
||||
|
||||
foreach (DB::table('identity_dimension_values')
|
||||
->whereIn('editorial_dimension_value_id', DB::table('editorial_dimension_values')->where('editorial_dimension_id', $dimension->id)->select('id'))
|
||||
->orderBy('id')->get() as $row) {
|
||||
$valueId = (int) $row->editorial_dimension_value_id;
|
||||
$label = DB::table('editorial_dimension_values')->where('id', $valueId)->value('label');
|
||||
$target = $subjectTypes[$row->subject_type] ?? null;
|
||||
|
||||
if ($target === 'content_element') {
|
||||
$report['mirror']['element_rows']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$where = ['art' => 'Zuordnung', 'zuordnung_id' => (int) $row->id, 'wert_id' => $valueId, 'wert' => $label, 'objektart' => $row->subject_type, 'objekt_id' => (int) $row->subject_id, 'herkunft' => $row->origin];
|
||||
|
||||
if ($target === null) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'unbekannte Objektart'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($row->origin !== 'direkt') {
|
||||
$report['unresolved'][] = $where + ['grund' => 'abgeleitete Zuordnung (wird nicht als direkte übernommen)'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! isset($resolved[$valueId])) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'Wert ohne belastbare Säule'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$config = self::TARGETS[$target];
|
||||
|
||||
if (! DB::table($config['subjects'])->where('id', $row->subject_id)->exists()) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'Objekt nicht mehr vorhanden'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$present = DB::table($config['table'])->where($config['column'], $row->subject_id)->where('pillar_id', $resolved[$valueId])->exists();
|
||||
|
||||
if ($present) {
|
||||
$report['already'][$target]++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $dryRun) {
|
||||
DB::table($config['table'])->insertOrIgnore([$config['column'] => $row->subject_id, 'pillar_id' => $resolved[$valueId]]);
|
||||
}
|
||||
|
||||
$report['copied'][$target]++;
|
||||
}
|
||||
|
||||
$report['mirror'] = array_merge($report['mirror'], $this->mirrorDivergence($dimension->id, $resolved));
|
||||
$report['after'] = $dryRun ? $report['before'] : $this->counts();
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $report
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function lines(array $report, bool $dryRun = false): array
|
||||
{
|
||||
$names = ['composition' => 'Module und Programme', 'license_article' => 'Lizenzartikel'];
|
||||
$lines = [$dryRun ? 'Probelauf, es wird nichts geschrieben.' : 'Übernahme abgeschlossen.', ''];
|
||||
|
||||
foreach ($report['mapping'] as $row) {
|
||||
$lines[] = sprintf('Wert %d „%s“ → %s%s', $row['wert_id'], $row['wert'], $row['saeule_id'] === null ? 'keine Säule (offen)' : 'Säule '.$row['saeule_id'].' „'.($row['saeule'] ?? '').'“ ('.$row['status'].')', ! empty($row['hinweis']) ? ' – '.$row['hinweis'] : '');
|
||||
}
|
||||
|
||||
$lines[] = '';
|
||||
|
||||
foreach ($names as $key => $label) {
|
||||
$lines[] = sprintf('%s: %d übernommen, %d bereits vorhanden, Zuordnungen vorher %d, nachher %d', $label, $report['copied'][$key], $report['already'][$key], $report['before'][$key], $report['after'][$key]);
|
||||
}
|
||||
|
||||
$lines[] = sprintf('Medien (nur Information): %d gespiegelte Zeilen, %d nicht mehr in der Medienzuordnung, %d nur dort. Maßgeblich bleibt die Medienzuordnung.', $report['mirror']['element_rows'], $report['mirror']['missing_in_pivot'], $report['mirror']['only_in_pivot']);
|
||||
|
||||
if ($report['unresolved'] === []) {
|
||||
$lines[] = 'Keine ungeklärten Fälle.';
|
||||
} else {
|
||||
$lines[] = '';
|
||||
$lines[] = 'Ungeklärt, bitte entscheiden (nichts wurde geändert):';
|
||||
|
||||
foreach ($report['unresolved'] as $row) {
|
||||
$lines[] = '- '.json_encode($row, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Säule zu einem alten Wert, oder der Grund, warum es keine belastbare gibt.
|
||||
*/
|
||||
private function pillarFor(object $value): object|string
|
||||
{
|
||||
if (preg_match('/^pfeiler-(\d+)$/', (string) $value->slug, $match) !== 1) {
|
||||
return 'Kennung ist nicht „pfeiler-<Nummer>“, keine belastbare Verknüpfung';
|
||||
}
|
||||
|
||||
$pillar = DB::table('pillars')->where('id', (int) $match[1])->first();
|
||||
|
||||
if ($pillar === null) {
|
||||
return 'Die Säule zur Kennung existiert nicht mehr';
|
||||
}
|
||||
|
||||
if ($value->pillar_id !== null && (int) $value->pillar_id !== (int) $pillar->id) {
|
||||
return 'Gespeicherte Verknüpfung (Säule '.$value->pillar_id.') und Kennung (Säule '.$pillar->id.') widersprechen sich';
|
||||
}
|
||||
|
||||
if ($pillar->created_at !== null && $value->created_at !== null && $pillar->created_at > $value->created_at) {
|
||||
return 'Die Säule ist jünger als der Wert; die Kennung kann nicht aus ihr entstanden sein';
|
||||
}
|
||||
|
||||
return $pillar;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> Objektart wie gespeichert => Ziel
|
||||
*/
|
||||
private function subjectTypes(): array
|
||||
{
|
||||
$types = [];
|
||||
|
||||
foreach ([
|
||||
'composition' => [Composition::class],
|
||||
'license_article' => [LicenseArticle::class],
|
||||
'content_element' => [ContentElement::class],
|
||||
] as $target => $classes) {
|
||||
foreach ($classes as $class) {
|
||||
$types[$class] = $target;
|
||||
$types[(new $class)->getMorphClass()] = $target;
|
||||
}
|
||||
}
|
||||
|
||||
return $types;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
private function counts(): array
|
||||
{
|
||||
return [
|
||||
'composition' => DB::table('composition_pillar')->count(),
|
||||
'license_article' => DB::table('license_article_pillar')->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $resolved
|
||||
* @return array{missing_in_pivot: int, only_in_pivot: int}
|
||||
*/
|
||||
private function mirrorDivergence(int $dimensionId, array $resolved): array
|
||||
{
|
||||
$mirrored = [];
|
||||
|
||||
foreach (DB::table('identity_dimension_values')
|
||||
->whereIn('subject_type', array_unique([ContentElement::class, (new ContentElement)->getMorphClass()]))
|
||||
->whereIn('editorial_dimension_value_id', array_keys($resolved) ?: [0])
|
||||
->get() as $row) {
|
||||
$mirrored[$row->subject_id.':'.$resolved[(int) $row->editorial_dimension_value_id]] = true;
|
||||
}
|
||||
|
||||
$pivot = [];
|
||||
|
||||
foreach (DB::table('content_element_pillar')->get() as $row) {
|
||||
$pivot[$row->content_element_id.':'.$row->pillar_id] = true;
|
||||
}
|
||||
|
||||
return [
|
||||
'missing_in_pivot' => count(array_diff_key($mirrored, $pivot)),
|
||||
'only_in_pivot' => count(array_diff_key($pivot, $mirrored)),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Berechtigter Nutzerkreis einer Lizenzoption: Einzellizenz (ein Trainer) oder Mehrfachlizenz (festgelegte Zahl von
|
||||
* Trainern). Das ist eine vertragliche Angabe der Lizenzoption. Sie ist unabhängig vom Lizenzinhaber (Person oder
|
||||
* Verein), vom technischen Downloadzugriff (nur das bestellende Konto) und vom Nutzungszweck (ehrenamtlich,
|
||||
* kommerziell, institutionell). Sie wird weder aus dem Zweck noch aus dem Preis abgeleitet.
|
||||
*/
|
||||
final class LicenceScope
|
||||
{
|
||||
public const SINGLE = 'einzel';
|
||||
|
||||
public const MULTI = 'mehrfach';
|
||||
|
||||
/** Obergrenze der Trainerzahl einer Mehrfachlizenz (Eingabeschutz). */
|
||||
public const MAX_TRAINERS = 999;
|
||||
|
||||
/**
|
||||
* @return array{0: ?string, 1: ?int} Nutzerkreis und Trainerzahl, geprüft und vereinheitlicht
|
||||
*/
|
||||
public static function normalise(?string $scope, mixed $trainers): array
|
||||
{
|
||||
$scope = filled($scope) ? (string) $scope : null;
|
||||
|
||||
if ($scope === null) {
|
||||
if (filled($trainers)) {
|
||||
throw new DomainRuleException('Die Trainerzahl gehört zu einer Einzel- oder Mehrfachlizenz. Wähle zuerst den Nutzerkreis.');
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
if ($scope === self::SINGLE) {
|
||||
if (filled($trainers) && (int) $trainers !== 1) {
|
||||
throw new DomainRuleException('Eine Einzellizenz gilt für genau einen Trainer.');
|
||||
}
|
||||
|
||||
return [self::SINGLE, 1];
|
||||
}
|
||||
|
||||
if ($scope === self::MULTI) {
|
||||
$count = filled($trainers) ? (int) $trainers : 0;
|
||||
|
||||
if ($count < 2 || $count > self::MAX_TRAINERS) {
|
||||
throw new DomainRuleException('Eine Mehrfachlizenz gilt für mindestens 2 und höchstens '.self::MAX_TRAINERS.' Trainer. Gib die Zahl der Trainer an.');
|
||||
}
|
||||
|
||||
return [self::MULTI, $count];
|
||||
}
|
||||
|
||||
throw new DomainRuleException('Der Nutzerkreis ist Einzellizenz oder Mehrfachlizenz.');
|
||||
}
|
||||
|
||||
/** Kurzform: „Einzellizenz · 1 Trainer“, „Mehrfachlizenz · bis zu 5 Trainer“ oder „keine Angabe“. */
|
||||
public static function label(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Einzellizenz · 1 Trainer',
|
||||
self::MULTI => 'Mehrfachlizenz · bis zu '.(int) $trainers.' Trainer',
|
||||
default => 'Nutzerkreis nicht festgelegt',
|
||||
};
|
||||
}
|
||||
|
||||
/** Erklärung für Käufer: was der Umfang bedeutet und was er nicht bedeutet. */
|
||||
public static function explanation(?string $scope, ?int $trainers): ?string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Die Inhalte dürfen von einem Trainer eingesetzt werden.',
|
||||
self::MULTI => 'Die Inhalte dürfen von bis zu '.(int) $trainers.' Trainern eingesetzt werden. Zugriff und Download erhält zum Start nur das bestellende Konto.',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Wert für Vergleich identischer Lizenzen („Bereits erworben“). */
|
||||
public static function key(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return ($scope ?? '-').'|'.($trainers ?? 0);
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public static function options(): array
|
||||
{
|
||||
return [
|
||||
self::SINGLE => 'Einzellizenz (ein Trainer)',
|
||||
self::MULTI => 'Mehrfachlizenz (mehrere Trainer)',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class LicenseArticle extends Model
|
||||
@@ -49,4 +50,10 @@ public function editorialContentKind(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EditorialContentKind::class);
|
||||
}
|
||||
|
||||
/** Direkt zugeordnete fachliche Säulen (zentrale Säulenverwaltung). */
|
||||
public function pillars(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Pillar::class)->orderBy('pillars.sort_order')->orderBy('pillars.name');
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,37 @@
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Offer extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'composition_id',
|
||||
'option_label',
|
||||
'standalone_bundle',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'standalone_bundle' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
/** Bezeichnung der Option auf der Produktseite. */
|
||||
public function optionName(): string
|
||||
{
|
||||
return filled($this->option_label) ? (string) $this->option_label : (string) $this->name;
|
||||
}
|
||||
|
||||
public function versions(): HasMany
|
||||
{
|
||||
return $this->hasMany(OfferVersion::class);
|
||||
|
||||
@@ -6,6 +6,27 @@ class OfferCoverage
|
||||
{
|
||||
public function __construct(private readonly ContentResolver $resolver) {}
|
||||
|
||||
/**
|
||||
* Bestandteile der Fassung, deren Medienfassung gesperrt ist. Ein Angebot soll nicht aktiviert werden, solange sein
|
||||
* Umfang gesperrte Bestandteile enthält; die Prüfung nennt sie vorab.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function blockedLeaves(CompositionVersion $version): array
|
||||
{
|
||||
$rows = $this->resolver->expand($version);
|
||||
$blocked = ContentElementVersion::query()
|
||||
->whereIn('id', array_column($rows, 'version_id'))
|
||||
->where('status', ContentVersionStatus::Gesperrt->value)
|
||||
->pluck('id')
|
||||
->all();
|
||||
|
||||
return array_values(array_map(
|
||||
fn (array $row): string => $row['path'],
|
||||
array_filter($rows, fn (array $row): bool => in_array($row['version_id'], $blocked, true)),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<LicenseArticle> $articles
|
||||
* @return list<string>
|
||||
|
||||
@@ -22,6 +22,23 @@ public function currentActiveVersion(Offer $offer): OfferVersion
|
||||
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
|
||||
@@ -85,10 +102,18 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
'dynamic' => false,
|
||||
'grant_kind' => 'kauf',
|
||||
'holder_kind' => 'person',
|
||||
'licence_scope' => null,
|
||||
'trainer_count' => null,
|
||||
], $attributes);
|
||||
|
||||
if ($offer->standalone_bundle && (count($lines) !== 1 || ! $lines[0]['target'] instanceof BundleVersion)) {
|
||||
throw new DomainRuleException('Ein Angebot mit eigener Paketseite besteht aus genau einer Paketfassung. Wähle eine Paketfassung oder ordne das Angebot der Seite eines Programms zu.');
|
||||
}
|
||||
|
||||
$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 {
|
||||
@@ -109,6 +134,8 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
'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) {
|
||||
@@ -138,6 +165,45 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Produktzuordnung der Option: Die Komposition bestimmt die öffentliche Produktseite und die Alternativgruppe,
|
||||
* die Bezeichnung benennt die Option auf dieser Seite. Beides sind keine bindenden Konditionen.
|
||||
*/
|
||||
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel, bool $ownBundlePage = false): Offer
|
||||
{
|
||||
if ($compositionId !== null) {
|
||||
Composition::query()->findOrFail($compositionId);
|
||||
}
|
||||
|
||||
if ($ownBundlePage && $compositionId !== null) {
|
||||
throw new DomainRuleException('Ein Paket hat entweder eine eigene Paketseite oder die Seite eines Programms, nicht beides.');
|
||||
}
|
||||
|
||||
$offer->composition_id = $compositionId;
|
||||
$offer->standalone_bundle = $ownBundlePage;
|
||||
$offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null;
|
||||
$offer->save();
|
||||
|
||||
return $offer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<int>
|
||||
*/
|
||||
@@ -168,6 +234,32 @@ private function assertAttributes(array $attributes): void
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}>
|
||||
@@ -185,6 +277,10 @@ private function assertCoverage(array $lines, array $attributes): void
|
||||
}
|
||||
|
||||
$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) {
|
||||
@@ -193,6 +289,12 @@ private function assertCoverage(array $lines, array $attributes): void
|
||||
}
|
||||
}
|
||||
|
||||
$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 !== []) {
|
||||
|
||||
@@ -19,6 +19,8 @@ class OfferVersion extends Model
|
||||
'dynamic',
|
||||
'grant_kind',
|
||||
'holder_kind',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'activated_at',
|
||||
];
|
||||
|
||||
|
||||
@@ -34,6 +34,16 @@ public function pages(): BelongsToMany
|
||||
return $this->belongsToMany(Page::class);
|
||||
}
|
||||
|
||||
public function compositions(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Composition::class);
|
||||
}
|
||||
|
||||
public function licenseArticles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(LicenseArticle::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Pillar> $query
|
||||
* @return Builder<Pillar>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Alte Filteradressen: Vor der Vereinheitlichung war „Fachliche Säule“ ein Wert der redaktionellen Einordnung
|
||||
* (`?einordnung=…`, `?pillar=…`, `dimension[]=…`). Verweist ein solcher Wert über `pillar_id` auf eine zentrale Säule,
|
||||
* gilt der Filter jetzt für diese Säule, statt stillschweigend zu entfallen.
|
||||
*/
|
||||
final class PillarFilterCompat
|
||||
{
|
||||
/**
|
||||
* @return int|null|false Kennung der Säule; null: alter Säulenwert ohne belastbare Verknüpfung; false: kein Säulenwert
|
||||
*/
|
||||
public static function pillarOfLegacyValue(int $valueId): int|false|null
|
||||
{
|
||||
$row = DB::table('editorial_dimension_values')
|
||||
->join('editorial_dimensions', 'editorial_dimensions.id', '=', 'editorial_dimension_values.editorial_dimension_id')
|
||||
->where('editorial_dimension_values.id', $valueId)
|
||||
->where('editorial_dimensions.slug', EditorialDimension::PILLAR_SLUG)
|
||||
->first(['editorial_dimension_values.pillar_id']);
|
||||
|
||||
if ($row === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $row->pillar_id === null ? null : (int) $row->pillar_id;
|
||||
}
|
||||
}
|
||||
@@ -40,19 +40,55 @@ public function present(Pillar $pillar, string $name, string $slug, ?string $sum
|
||||
|
||||
public function delete(Pillar $pillar): void
|
||||
{
|
||||
if ($pillar->elements()->exists() || $pillar->pages()->exists()) {
|
||||
throw new DomainRuleException('Eine Säule mit zugeordneten Medien oder Seiten wird nicht gelöscht.');
|
||||
$usage = $this->usage($pillar);
|
||||
|
||||
if (array_sum($usage) > 0) {
|
||||
throw new DomainRuleException('Eine Säule mit zugeordneten Objekten wird nicht gelöscht ('.$this->usageText($usage).'). Ordnen Sie sie zuerst anders zu.');
|
||||
}
|
||||
|
||||
$pillar->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $pillarIds
|
||||
* Zuordnungen je Objektart: Medien, Module und Programme, Lizenzartikel, Seiten.
|
||||
*
|
||||
* @return array{medien: int, zusammenstellungen: int, lizenzartikel: int, seiten: int}
|
||||
*/
|
||||
public function assign(ContentElement $element, array $pillarIds): void
|
||||
public function usage(Pillar $pillar): array
|
||||
{
|
||||
$element->pillars()->sync($this->ids($pillarIds));
|
||||
return [
|
||||
'medien' => $pillar->elements()->count(),
|
||||
'zusammenstellungen' => $pillar->compositions()->count(),
|
||||
'lizenzartikel' => $pillar->licenseArticles()->count(),
|
||||
'seiten' => $pillar->pages()->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{medien: int, zusammenstellungen: int, lizenzartikel: int, seiten: int} $usage
|
||||
*/
|
||||
public function usageText(array $usage): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
foreach (['medien' => ['Medium', 'Medien'], 'zusammenstellungen' => ['Modul oder Programm', 'Module und Programme'], 'lizenzartikel' => ['Lizenzartikel', 'Lizenzartikel'], 'seiten' => ['Seite', 'Seiten']] as $key => [$one, $many]) {
|
||||
if ($usage[$key] > 0) {
|
||||
$parts[] = $usage[$key].' '.($usage[$key] === 1 ? $one : $many);
|
||||
}
|
||||
}
|
||||
|
||||
return $parts === [] ? 'nirgends zugeordnet' : implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordnet einem Medium, Modul, Programm, Lizenzartikel oder einer Seite Säulen zu. Alle Objektarten verwenden
|
||||
* dieselbe zentrale Säule und dieselbe Speicherregel; die Zuordnung ersetzt die bisherige vollständig.
|
||||
*
|
||||
* @param list<int|string> $pillarIds
|
||||
*/
|
||||
public function assign(ContentElement|Composition|LicenseArticle|Page $subject, array $pillarIds): void
|
||||
{
|
||||
$subject->pillars()->sync($this->ids($pillarIds));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,7 +96,7 @@ public function assign(ContentElement $element, array $pillarIds): void
|
||||
*/
|
||||
public function assignPages(Page $page, array $pillarIds): void
|
||||
{
|
||||
$page->pillars()->sync($this->ids($pillarIds));
|
||||
$this->assign($page, $pillarIds);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,6 +13,8 @@ class ReleaseContent extends Model
|
||||
'content_element_version_id',
|
||||
'role',
|
||||
'path',
|
||||
'requirement',
|
||||
'variant_key',
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Übernahme von Übungen aus dem Shinkan-Katalog (`GET /api/distribution/v1/catalog` und Detailroute) in denselben
|
||||
* Übungsbestand wie die lokalen Übungen.
|
||||
*
|
||||
* Grundsätze:
|
||||
* - Die Quellübung ist an ihre stabile Kennung gebunden. Jeder Inhaltsstand (Prüfsumme der Quelle) wird genau einmal
|
||||
* festgehalten; ein wiederholter Abruf erzeugt nichts Neues.
|
||||
* - Eine lokale Fassung entsteht nur durch die bewusste Übernahme ({@see adopt}) und ist danach unveränderlich. Lokale
|
||||
* Ergänzungen (Herkunft „lokal“) bleiben bei einer neuen Quellfassung erhalten.
|
||||
* - Das Ausblenden an der Quelle setzt nur die Verfügbarkeit. Lokale Fassungen und Verwendungen bleiben unberührt; eine
|
||||
* rechtliche Sperre ist der lokale `block`.
|
||||
* - Medien des Katalogs sind Metadaten ohne Datei. Sie begründen weder eine Ausgabe noch eine Nutzungsberechtigung und
|
||||
* stehen nie in einem Artikel-Stand.
|
||||
* - Ein fehlgeschlagener Abruf verändert den gespeicherten Stand nicht und rückt den Cursor nicht vor.
|
||||
*/
|
||||
class ShinkanImport
|
||||
{
|
||||
/** Abschnitte der Quelle in Lesereihenfolge: Feld => [Bezeichnung, Rolle]. */
|
||||
private const SECTIONS = [
|
||||
'preparation' => 'Vorbereitung',
|
||||
'execution' => 'Durchführung',
|
||||
'trainer_notes' => 'Trainerhinweise',
|
||||
];
|
||||
|
||||
public function configured(): bool
|
||||
{
|
||||
return filled(config('services.shinkan.url')) && filled(config('services.shinkan.key'));
|
||||
}
|
||||
|
||||
public function fetch(): ExerciseImportRun
|
||||
{
|
||||
$run = ExerciseImportRun::query()->create(['status' => 'laeuft', 'started_at' => now()]);
|
||||
|
||||
if (! $this->configured()) {
|
||||
return $this->finish($run, 'fehler', error: 'Die Anbindung ist nicht eingerichtet. Adresse und Schlüssel fehlen in der Umgebung.');
|
||||
}
|
||||
|
||||
$previous = ExerciseImportRun::query()->where('status', 'ok')->orderByDesc('id')->value('cursor');
|
||||
$counts = ['added' => 0, 'updated' => 0, 'removed' => 0];
|
||||
|
||||
try {
|
||||
try {
|
||||
$catalog = $this->get('/catalog', $previous === null ? [] : ['cursor' => $previous]);
|
||||
} catch (RequestException $exception) {
|
||||
// Ein ungültiger Cursor heißt nur: ganz neu abgleichen.
|
||||
if ($previous === null || $exception->response->status() !== 400) {
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$catalog = $this->get('/catalog');
|
||||
}
|
||||
|
||||
foreach ((array) ($catalog['changes'] ?? []) as $change) {
|
||||
$id = (string) ($change['source_id'] ?? '');
|
||||
$kind = (string) ($change['change'] ?? '');
|
||||
|
||||
if ($id === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($kind === 'removed') {
|
||||
ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', $id)
|
||||
->update(['availability' => ExerciseSource::WITHDRAWN]);
|
||||
$counts['removed']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$document = $this->get('/catalog/'.$id);
|
||||
$this->record($document);
|
||||
$counts[$kind === 'added' ? 'added' : 'updated']++;
|
||||
}
|
||||
|
||||
foreach ((array) ($catalog['exercises'] ?? []) as $listed) {
|
||||
ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', (string) ($listed['source_id'] ?? ''))
|
||||
->update(['availability' => ExerciseSource::PROVIDED, 'last_seen_at' => now()]);
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
return $this->finish($run, 'fehler', $counts, 'Der Abruf ist fehlgeschlagen: '.$this->plain($exception).' Der gespeicherte Stand blieb unverändert.');
|
||||
}
|
||||
|
||||
return $this->finish($run, 'ok', $counts, null, (string) ($catalog['next_cursor'] ?? $previous));
|
||||
}
|
||||
|
||||
/**
|
||||
* Hält einen abgerufenen Inhaltsstand fest. Derselbe Stand (Quelle und Prüfsumme) wird nie doppelt gespeichert.
|
||||
*
|
||||
* @param array<string, mixed> $document Detail der Quelle mit `source_id`, `content_hash` und den Feldern
|
||||
*/
|
||||
public function record(array $document): ExerciseSourceSnapshot
|
||||
{
|
||||
$id = (string) ($document['source_id'] ?? '');
|
||||
$hash = (string) ($document['content_hash'] ?? '');
|
||||
|
||||
if ($id === '' || $hash === '') {
|
||||
throw new DomainRuleException('Der Abruf liefert keine Quellkennung oder Prüfsumme.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($id, $hash, $document): ExerciseSourceSnapshot {
|
||||
$source = ExerciseSource::query()->firstOrCreate(
|
||||
['source_system' => 'shinkan', 'source_id' => $id],
|
||||
['title' => (string) ($document['title'] ?? '')],
|
||||
);
|
||||
$source->update([
|
||||
'title' => (string) ($document['title'] ?? $source->title),
|
||||
'availability' => ExerciseSource::PROVIDED,
|
||||
'last_hash' => $hash,
|
||||
'last_seen_at' => now(),
|
||||
]);
|
||||
|
||||
return $source->snapshots()->firstOrCreate(
|
||||
['content_hash' => $hash],
|
||||
['payload' => $document, 'fetched_at' => now()],
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand einer Quellübung für die Redaktion.
|
||||
*/
|
||||
public function state(ExerciseSource $source): string
|
||||
{
|
||||
$latest = $source->latestSnapshot();
|
||||
|
||||
return match (true) {
|
||||
$source->availability === ExerciseSource::WITHDRAWN => 'nicht_mehr_bereitgestellt',
|
||||
$latest === null => 'neu',
|
||||
$latest->adopted_version_id !== null => 'uebernommen',
|
||||
$source->composition_id !== null => 'geaendert',
|
||||
default => 'neu',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Die bewusste Übernahme: aus dem Inhaltsstand wird eine neue, unveränderliche lokale Fassung. Wiederholt man sie,
|
||||
* entsteht keine zweite Fassung. Lokale Ergänzungen der bisherigen Fassung werden übernommen.
|
||||
*/
|
||||
public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null): CompositionVersion
|
||||
{
|
||||
$snapshot->refresh();
|
||||
|
||||
if ($snapshot->adopted_version_id !== null) {
|
||||
return $snapshot->adoptedVersion;
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($snapshot, $actor): CompositionVersion {
|
||||
$source = $snapshot->source;
|
||||
$document = $snapshot->payload;
|
||||
$content = app(ContentService::class);
|
||||
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
|
||||
$composition = $source->composition ?? $this->createComposition($title, (string) ($document['summary'] ?? ''));
|
||||
$previous = $composition->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
||||
|
||||
$variants = [];
|
||||
$members = [];
|
||||
|
||||
foreach (self::SECTIONS as $field => $label) {
|
||||
$text = trim((string) ($document[$field] ?? ''));
|
||||
|
||||
if ($text !== '') {
|
||||
$members[] = [
|
||||
'role' => $label,
|
||||
'target' => $this->section($source, $field, $title.' · '.$label, $text),
|
||||
'origin' => 'quelle',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ((array) ($document['variants'] ?? []) as $variant) {
|
||||
$key = (string) ($variant['id'] ?? '');
|
||||
|
||||
if ($key === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$variants[] = [
|
||||
'key' => $key,
|
||||
'name' => (string) ($variant['name'] ?? '') ?: 'Variante',
|
||||
'description' => (string) ($variant['description'] ?? ''),
|
||||
'origin' => 'quelle',
|
||||
];
|
||||
$changes = trim((string) ($variant['execution_changes'] ?? ''));
|
||||
|
||||
if ($changes !== '') {
|
||||
$members[] = [
|
||||
'role' => 'Abweichung der Durchführung',
|
||||
'target' => $this->section($source, 'variant:'.$key, $title.' · '.($variant['name'] ?? 'Variante').' · Abweichung', $changes),
|
||||
'variant' => $key,
|
||||
'origin' => 'quelle',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
[$localMembers, $localVariants] = $this->localAdditions($previous, array_column($variants, 'key'));
|
||||
$version = $content->publishComposition(
|
||||
$composition,
|
||||
[...$members, ...$localMembers],
|
||||
$actor,
|
||||
'Übernahme aus Shinkan',
|
||||
[
|
||||
'learning_goal' => $document['goal'] ?? null,
|
||||
'duration_minutes' => $document['duration_min'] ?? null,
|
||||
'duration_max' => $document['duration_max'] ?? null,
|
||||
'material_note' => $document['equipment'] ?? null,
|
||||
'source_snapshot_id' => $snapshot->id,
|
||||
],
|
||||
[...$variants, ...$localVariants],
|
||||
);
|
||||
|
||||
$snapshot->update(['adopted_version_id' => $version->id]);
|
||||
$source->update(['composition_id' => $composition->id]);
|
||||
|
||||
return $version;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Was die Redaktion lokal ergänzt hat, bleibt bei einer neuen Quellfassung erhalten. Eine lokale Zuordnung zu einer
|
||||
* Quellvariante, die es nicht mehr gibt, wandert in den gemeinsamen Teil, damit nichts verloren geht.
|
||||
*
|
||||
* @param list<string> $sourceVariantKeys
|
||||
* @return array{0: list<array<string, mixed>>, 1: list<array<string, mixed>>}
|
||||
*/
|
||||
private function localAdditions(?CompositionVersion $previous, array $sourceVariantKeys): array
|
||||
{
|
||||
if ($previous === null) {
|
||||
return [[], []];
|
||||
}
|
||||
|
||||
$localVariants = $previous->variants->where('origin', 'lokal')->map(fn (CompositionVersionVariant $variant): array => [
|
||||
'key' => $variant->key, 'name' => $variant->name, 'description' => $variant->description, 'origin' => 'lokal',
|
||||
])->values()->all();
|
||||
$known = [...$sourceVariantKeys, ...array_column($localVariants, 'key')];
|
||||
$members = [];
|
||||
|
||||
foreach ($previous->members->where('origin', 'lokal') as $member) {
|
||||
$variant = $member->variant?->key;
|
||||
$members[] = [
|
||||
'role' => $member->role,
|
||||
'note' => $member->placement_note,
|
||||
'target' => $member->content_element_version_id !== null ? $member->contentElementVersion : $member->nestedCompositionVersion,
|
||||
'variant' => $variant !== null && in_array($variant, $known, true) ? $variant : null,
|
||||
'requirement' => $member->requirement,
|
||||
'selection' => $member->variant_selection,
|
||||
'origin' => 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
return [$members, $localVariants];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Textfassung eines Abschnitts der Quelle. Unveränderter Text bleibt dieselbe Fassung.
|
||||
*/
|
||||
private function section(ExerciseSource $source, string $field, string $title, string $text): ContentElementVersion
|
||||
{
|
||||
$content = app(ContentService::class);
|
||||
$ref = 'shinkan:'.$source->source_id.':'.$field;
|
||||
$element = ContentElement::query()->where('source_ref', $ref)->first();
|
||||
|
||||
if ($element === null) {
|
||||
$element = $content->createElement('text', 'text', $title);
|
||||
$element->source_ref = $ref;
|
||||
$element->save();
|
||||
}
|
||||
|
||||
$latest = $element->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
|
||||
|
||||
return $latest !== null && trim((string) $latest->body) === $text
|
||||
? $latest
|
||||
: $content->publishElementVersion($element, $text, [], 'Übernahme aus Shinkan');
|
||||
}
|
||||
|
||||
private function createComposition(string $title, string $summary): Composition
|
||||
{
|
||||
$composition = app(ContentService::class)->createComposition($title, CompositionKind::Exercise);
|
||||
$composition->editorial_content_kind_id = EditorialContentKind::query()->where('slug', 'uebung')->value('id');
|
||||
|
||||
if ($summary !== '') {
|
||||
$composition->summary = $summary;
|
||||
}
|
||||
|
||||
$composition->save();
|
||||
|
||||
return $composition;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $query
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function get(string $path, array $query = []): array
|
||||
{
|
||||
$response = Http::withToken((string) config('services.shinkan.key'))
|
||||
->acceptJson()
|
||||
->timeout(20)
|
||||
->get(rtrim((string) config('services.shinkan.url'), '/').'/api/distribution/v1'.$path, $query)
|
||||
->throw();
|
||||
|
||||
$json = $response->json();
|
||||
|
||||
if (! is_array($json)) {
|
||||
throw new DomainRuleException('Die Antwort der Quelle ist kein gültiges JSON.');
|
||||
}
|
||||
|
||||
return $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{added?: int, updated?: int, removed?: int} $counts
|
||||
*/
|
||||
private function finish(ExerciseImportRun $run, string $status, array $counts = [], ?string $error = null, ?string $cursor = null): ExerciseImportRun
|
||||
{
|
||||
$run->update([
|
||||
'status' => $status,
|
||||
'cursor' => $cursor,
|
||||
'added' => $counts['added'] ?? 0,
|
||||
'updated' => $counts['updated'] ?? 0,
|
||||
'removed' => $counts['removed'] ?? 0,
|
||||
'error' => $error,
|
||||
'finished_at' => now(),
|
||||
]);
|
||||
|
||||
return $run;
|
||||
}
|
||||
|
||||
/** Fehlertext ohne Adresse und Schlüssel. */
|
||||
private function plain(Throwable $exception): string
|
||||
{
|
||||
if ($exception instanceof RequestException) {
|
||||
return 'Die Quelle antwortete mit Status '.$exception->response->status().'.';
|
||||
}
|
||||
|
||||
return $exception instanceof DomainRuleException ? $exception->getMessage() : 'Die Quelle ist nicht erreichbar.';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Scope;
|
||||
|
||||
/**
|
||||
* Rückfallschutz: Dieser Code kennt nur die Kompositionsarten aus {@see CompositionKind}. Eine Komposition mit einem
|
||||
* Wert, den erst eine neuere Programmversion einführt, gilt hier als nicht vorhanden. Sie wird weder geladen (der
|
||||
* Enum-Zugriff würde sonst abstürzen) noch angezeigt, bearbeitet oder veröffentlicht. Eine neuere Programmversion
|
||||
* kennt den Wert und sieht die Zeile wieder.
|
||||
*/
|
||||
class SupportedKindScope implements Scope
|
||||
{
|
||||
public function apply(Builder $builder, Model $model): void
|
||||
{
|
||||
$builder->whereIn($model->qualifyColumn('kind'), CompositionKind::values());
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@
|
||||
* Redaktionsvorschau (Route editorial.card, nur für angemeldete Redaktion); öffentlich nie ausgegeben, weil es
|
||||
* keine Freigabe für die Website hat.
|
||||
* - missing: was für eine vollständige Karte fehlt, als Hinweis nur in der Redaktionsvorschau.
|
||||
* - texts: die zentralen Texte des Fachobjekts, aus denen die Karte einen wählen kann (teaser, summary, description).
|
||||
* summary bleibt der Text der Vorgabe („Automatisch“); texts wird nur gelesen, wenn die Redaktion einen wählt.
|
||||
*/
|
||||
final readonly class CardSubject
|
||||
{
|
||||
@@ -36,24 +38,39 @@ public function __construct(
|
||||
public ?string $previewImage = null,
|
||||
public array $missing = [],
|
||||
public ?string $style = null,
|
||||
public array $texts = [],
|
||||
) {}
|
||||
|
||||
public function withText(?string $title, ?string $summary): self
|
||||
{
|
||||
return new self(
|
||||
title: $title ?? $this->title,
|
||||
summary: $summary ?? $this->summary,
|
||||
kind: $this->kind,
|
||||
badge: $this->badge,
|
||||
meta: $this->meta,
|
||||
url: $this->url,
|
||||
public: $this->public,
|
||||
notice: $this->notice,
|
||||
visual: $this->visual,
|
||||
visualLabel: $this->visualLabel,
|
||||
previewImage: $this->previewImage,
|
||||
missing: $this->missing,
|
||||
style: $this->style,
|
||||
);
|
||||
return $this->copy(['title' => $title ?? $this->title, 'summary' => $summary ?? $this->summary]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Text der Karte aus einem zentralen Text des Fachobjekts. Ist er nicht gepflegt, bleibt die Karte ohne Text
|
||||
* (kein stiller Ersatz aus einem anderen Feld); in der Redaktionsvorschau steht dann ein Hinweis.
|
||||
*/
|
||||
public function withTextChoice(string $field, string $missingHint): self
|
||||
{
|
||||
if (! array_key_exists($field, $this->texts)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$text = $this->texts[$field];
|
||||
$missing = array_values(array_filter($this->missing, fn (string $hint): bool => ! str_contains($hint, 'Kurzbeschreibung')));
|
||||
|
||||
if ($text === null) {
|
||||
$missing[] = $missingHint;
|
||||
}
|
||||
|
||||
return $this->copy(['summary' => $text, 'missing' => $missing]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $changes
|
||||
*/
|
||||
private function copy(array $changes): self
|
||||
{
|
||||
return new self(...array_merge(get_object_vars($this), $changes));
|
||||
}
|
||||
}
|
||||
@@ -265,6 +265,13 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
|
||||
$profile = app(EditorialProfileReader::class)->read($composition, 'kachel');
|
||||
$summary = $profile->value('teaser') ?: $profile->value('summary');
|
||||
$goal = filled($version?->learning_goal) ? trim((string) $version->learning_goal) : null;
|
||||
// Zentrale Texte, aus denen die Redaktion den Kartentext wählen kann (Zielgruppe „Öffentliche Kachel“).
|
||||
$texts = [
|
||||
'teaser' => $profile->value('teaser'),
|
||||
'summary' => $profile->value('summary'),
|
||||
'description' => $profile->value('description'),
|
||||
'goal' => $goal,
|
||||
];
|
||||
$missing = [];
|
||||
|
||||
if ($summary === null) {
|
||||
@@ -313,6 +320,7 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
|
||||
visualLabel: $kind,
|
||||
previewImage: $includeNonPublic ? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path) : null,
|
||||
missing: $missing,
|
||||
texts: $texts,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,11 +8,13 @@
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
|
||||
/**
|
||||
* Lesesicht „Medien und Materialien“ für Premium-Karten (Website-CMS-Zielarchitektur 6.2).
|
||||
*
|
||||
* Auswahl in der Redaktion: jedes nicht archivierte Inhaltselement mit mindestens einer nicht gesperrten Fassung.
|
||||
* Auswahl in der Redaktion: jedes nicht archivierte Inhaltselement mit mindestens einer nicht gesperrten Fassung, dazu
|
||||
* jeder Film, der nur aus einer Website-Datei besteht (Medium ohne Inhaltsfassung, z. B. ein Teaser).
|
||||
*
|
||||
* Öffentliche Sichtbarkeit (Übergangsregel, solange öffentliche Fachobjektprofile nach ADR-29 fehlen):
|
||||
* Ein Medium hat keine eigene öffentliche Seite. Öffentlich genannt wird es heute nur als Bestandteil der gezeigten
|
||||
@@ -20,10 +22,17 @@
|
||||
* öffentlich, mit Verweis auf diese Programmseite, und nur mit bereitgestellter Fassung. Traineranleitungen erscheinen
|
||||
* nie öffentlich (vertraulich für Trainerinnen und Trainer).
|
||||
*
|
||||
* Öffentlich gelesen werden Anzeigetitel (sonst Arbeitstitel), Kurzbeschreibung, Inhaltsart und Ausgabeart. Nie:
|
||||
* Beschreibung, Einsatzhinweis, Lizenzvermerk, Dateien, Lehrtexte, Ausgabeadressen. Das Vorschaubild (Filmstandbild)
|
||||
* der Bibliothek ist nicht für die Website freigegeben; es erscheint nur in der Redaktionsvorschau.
|
||||
* Eine Karte spielt nichts ab, bietet keinen Download und gibt kein Medium frei.
|
||||
* Ein Film nur mit Website-Datei hat weder Fassung noch Programm. Er erscheint öffentlich, sobald seine Website-Datei
|
||||
* für die Website freigegeben ist (die Freigabe ist die ausdrückliche Entscheidung der Redaktion), ohne Verweis auf
|
||||
* eine Programmseite und damit ohne Aktion. Ohne Freigabe bleibt er auf die Redaktionsvorschau beschränkt.
|
||||
*
|
||||
* Öffentlich gelesen werden Anzeigetitel (sonst Arbeitstitel), Inhaltsart und Ausgabeart sowie einer der Texte
|
||||
* Teaser, Kurzbeschreibung oder ausführliche Beschreibung. Welcher Text erscheint, entscheidet die Redaktion je Karte
|
||||
* (Einstellung „Text der Karte“); ohne Wahl gilt die Kurzbeschreibung, sonst der Teaser. Die ausführliche Beschreibung
|
||||
* erscheint nur, wenn die Redaktion sie ausdrücklich wählt. Nie: Einsatzhinweis, Lizenzvermerk, Dateien, Lehrtexte,
|
||||
* Ausgabeadressen. Das Vorschaubild der Bibliothek ist nicht für die Website freigegeben; es erscheint nur in der
|
||||
* Redaktionsvorschau und kann in der Karte ausdrücklich als Website-Bild übernommen werden (FilmStill).
|
||||
* Eine Karte spielt höchstens den für die Website freigegebenen Trailer ab (CardClip), bietet keinen Download und gibt kein Medium frei.
|
||||
*/
|
||||
class PublicMaterialReader
|
||||
{
|
||||
@@ -41,14 +50,36 @@ public function __construct(
|
||||
public function isSelectable(ContentElement $element): bool
|
||||
{
|
||||
return $element->archived_at === null
|
||||
&& $element->versions()->where('status', '!=', ContentVersionStatus::Gesperrt->value)->exists();
|
||||
&& ($element->versions()->where('status', '!=', ContentVersionStatus::Gesperrt->value)->exists()
|
||||
|| $this->isWebsiteOnlyFilm($element));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Film ohne jede Inhaltsfassung, der nur die Website-Datei (`teaser/…`) hat, zum Beispiel ein Teaser. Er kann
|
||||
* auf der Medienkarte gewählt werden; was daraus öffentlich wird, bestimmt allein die Freigabe der Datei.
|
||||
*/
|
||||
public function isWebsiteOnlyFilm(ContentElement $element): bool
|
||||
{
|
||||
return $element->output_class === 'film'
|
||||
&& filled($element->preview_path)
|
||||
&& ! $element->versions()->exists();
|
||||
}
|
||||
|
||||
public function isReady(ContentElement $element): bool
|
||||
{
|
||||
if ($this->isWebsiteOnlyFilm($element)) {
|
||||
return $this->isWebsiteReleased($element);
|
||||
}
|
||||
|
||||
return $element->versions()->where('status', ContentVersionStatus::Bereit->value)->exists();
|
||||
}
|
||||
|
||||
/** Die Website-Datei des Films ist freigegeben und wird tatsächlich ausgeliefert (WebsiteMedia). */
|
||||
private function isWebsiteReleased(ContentElement $element): bool
|
||||
{
|
||||
return app(WebsiteMedia::class)->present($element)?->kind === 'film';
|
||||
}
|
||||
|
||||
/**
|
||||
* Öffentliches Programm, in dessen gezeigter Fassung das Element vorkommt, sonst null.
|
||||
*
|
||||
@@ -64,7 +95,7 @@ public function isPublic(ContentElement $element): bool
|
||||
return $this->isSelectable($element)
|
||||
&& $this->isReady($element)
|
||||
&& ! in_array($element->editorialContentKind?->slug, self::CONFIDENTIAL_KINDS, true)
|
||||
&& $this->publicProgramFor($element) !== null;
|
||||
&& ($this->publicProgramFor($element) !== null || $this->isWebsiteOnlyFilm($element));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,7 +108,13 @@ public function search(?string $term, int $limit = 25): array
|
||||
$candidates = ContentElement::query()
|
||||
->with('editorialContentKind')
|
||||
->whereNull('archived_at')
|
||||
->whereHas('versions', fn ($query) => $query->where('status', '!=', ContentVersionStatus::Gesperrt->value))
|
||||
->where(fn ($selectable) => $selectable
|
||||
->whereHas('versions', fn ($query) => $query->where('status', '!=', ContentVersionStatus::Gesperrt->value))
|
||||
->orWhere(fn ($websiteOnly) => $websiteOnly
|
||||
->where('output_class', 'film')
|
||||
->whereNotNull('preview_path')
|
||||
->where('preview_path', '!=', '')
|
||||
->whereDoesntHave('versions')))
|
||||
->when($term !== '', function ($query) use ($term): void {
|
||||
$like = '%'.mb_strtolower($term).'%';
|
||||
$query->where(fn ($inner) => $inner
|
||||
@@ -124,7 +161,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
|
||||
$shown = clone $element;
|
||||
|
||||
foreach (['working_title', 'display_title', 'summary', 'thumbnail_path', 'thumbnail_alt'] as $field) {
|
||||
foreach (['working_title', 'display_title', 'teaser', 'summary', 'description', 'thumbnail_path', 'thumbnail_alt'] as $field) {
|
||||
if (! array_key_exists($field, $draft)) {
|
||||
continue;
|
||||
}
|
||||
@@ -146,17 +183,30 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
$summary = trim((string) $shown->teaser);
|
||||
}
|
||||
|
||||
$texts = [];
|
||||
|
||||
foreach (['teaser', 'summary', 'description'] as $field) {
|
||||
$own = filled($shown->getAttribute($field)) ? trim((string) $shown->getAttribute($field)) : null;
|
||||
|
||||
if (! array_key_exists($field, $draft) && $profile->origin($field) === 'variante') {
|
||||
$own = $profile->value($field);
|
||||
}
|
||||
|
||||
$texts[$field] = $own;
|
||||
}
|
||||
|
||||
$title = (string) ($shown->display_title ?: $shown->working_title);
|
||||
|
||||
if (! array_key_exists('display_title', $draft) && $profile->origin('display_title') === 'variante') {
|
||||
$title = (string) $profile->value('display_title');
|
||||
}
|
||||
|
||||
$websiteOnly = $this->isWebsiteOnlyFilm($element);
|
||||
$meta = [$output];
|
||||
if ($program !== null) {
|
||||
$meta[] = 'Im Programm „'.$program['title'].'“';
|
||||
}
|
||||
if ($film) {
|
||||
if ($film && ! $websiteOnly) {
|
||||
$meta[] = 'Vollständiger Film nur mit Lizenz im Mitgliederbereich';
|
||||
}
|
||||
|
||||
@@ -184,6 +234,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
previewImage: $previewImage,
|
||||
missing: $missing,
|
||||
style: $film ? 'media' : 'material',
|
||||
texts: $texts,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -204,7 +255,11 @@ public function visibilityNote(ContentElement $element): string
|
||||
if ($this->isPublic($element)) {
|
||||
$program = $this->publicProgramFor($element);
|
||||
|
||||
return 'Öffentlich nur als Teil der Programmseite „'.($program['title'] ?? '').'“. Die Mediendatei wird dabei nicht ausgeliefert.';
|
||||
if ($program === null) {
|
||||
return 'Öffentlich mit der für die Website freigegebenen Datei, ohne Verweis auf eine Programmseite. Die Originaldatei wird nie ausgeliefert.';
|
||||
}
|
||||
|
||||
return 'Öffentlich nur als Teil der Programmseite „'.$program['title'].'“. Die Mediendatei wird dabei nicht ausgeliefert.';
|
||||
}
|
||||
|
||||
return $this->notice($element, $this->publicProgramFor($element));
|
||||
@@ -217,6 +272,7 @@ private function notice(ContentElement $element, ?array $program): string
|
||||
{
|
||||
$reason = match (true) {
|
||||
in_array($element->editorialContentKind?->slug, self::CONFIDENTIAL_KINDS, true) => 'Traineranleitungen erscheinen nie öffentlich.',
|
||||
$this->isWebsiteOnlyFilm($element) => 'Die Website-Datei ist nicht für die Website freigegeben (Medium öffnen → Reiter „Website“ → freigeben).',
|
||||
! $this->isReady($element) => 'Das Medium hat noch keine bereitgestellte Fassung.',
|
||||
$program === null => 'Das Medium gehört zu keinem öffentlich gezeigten Programm. Medien haben noch keine eigene öffentliche Freigabe (öffentliches Profil, ADR-29).',
|
||||
default => 'Das Medium ist nicht öffentlich.',
|
||||
@@ -227,9 +283,14 @@ private function notice(ContentElement $element, ?array $program): string
|
||||
|
||||
private function optionLabel(ContentElement $element): string
|
||||
{
|
||||
$visibility = $this->isPublic($element)
|
||||
? 'öffentlich über Programmseite'
|
||||
: ($this->isReady($element) ? 'nur Redaktionsvorschau' : 'Entwurf, nur Redaktionsvorschau');
|
||||
$visibility = match (true) {
|
||||
$this->isWebsiteOnlyFilm($element) => $this->isPublic($element)
|
||||
? 'öffentlich mit Website-Datei'
|
||||
: 'Website-Datei nicht freigegeben, nur Redaktionsvorschau',
|
||||
$this->isPublic($element) => 'öffentlich über Programmseite',
|
||||
$this->isReady($element) => 'nur Redaktionsvorschau',
|
||||
default => 'Entwurf, nur Redaktionsvorschau',
|
||||
};
|
||||
$kind = $element->editorialContentKind?->label ?: self::outputLabel((string) $element->output_class);
|
||||
|
||||
return (string) ($element->display_title ?: $element->working_title).' · '.$kind.' · '.$visibility;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Support;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\PresentationAssignment;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Der kurze Clip, den eine Premium-Karte beim Überfahren oder Antippen abspielt.
|
||||
*
|
||||
* Gelesen wird nur, was die Redaktion ohnehin für die Website freigegeben hat (WebsiteMedia, Route website.media):
|
||||
* 1. der Trailer des Fachobjekts (Präsentationsrolle „Trailer“), sonst der Vorschauclip,
|
||||
* 2. bei einem Film ersatzweise dessen eigener freigegebener Teaser.
|
||||
* Der vollständige Film, die Originaldatei und nicht freigegebene Clips kommen nie über die Karte. Die Karte gibt
|
||||
* nichts frei; ohne freigegebenen Clip bleibt es beim Kartenbild.
|
||||
*
|
||||
* In der Redaktionsvorschau erklärt `notice`, warum kein Clip läuft (zugeordnet, aber nicht freigegeben).
|
||||
*/
|
||||
class CardClip
|
||||
{
|
||||
/** Rollen in der Reihenfolge, in der ein Clip gesucht wird. */
|
||||
public const ROLES = ['trailer', 'vorschauclip'];
|
||||
|
||||
public function __construct(private readonly WebsiteMedia $media) {}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, source: string, notice: string|null, hint: string|null}
|
||||
*/
|
||||
public function for(Model $subject, bool $preview): array
|
||||
{
|
||||
$assigned = PresentationAssignment::query()
|
||||
->with(['role', 'element'])
|
||||
->where('subject_type', $subject->getMorphClass())
|
||||
->where('subject_id', $subject->getKey())
|
||||
->whereHas('role', fn ($query) => $query->whereIn('slug', self::ROLES))
|
||||
->orderBy('position')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->sortBy(fn (PresentationAssignment $row): int => (int) array_search($row->role?->slug, self::ROLES, true))
|
||||
->values();
|
||||
|
||||
$unreleased = null;
|
||||
|
||||
foreach ($assigned as $assignment) {
|
||||
$element = $assignment->element;
|
||||
|
||||
if (! $element instanceof ContentElement || $element->archived_at !== null || $element->output_class !== 'film') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$present = $this->media->present($element);
|
||||
|
||||
if ($present !== null && $present->kind === 'film') {
|
||||
return $this->found($present->url, $present->title, $assignment->role?->slug === 'trailer' ? 'trailer' : 'vorschauclip');
|
||||
}
|
||||
|
||||
$unreleased ??= $element;
|
||||
}
|
||||
|
||||
if ($subject instanceof ContentElement && $subject->output_class === 'film') {
|
||||
$own = $this->media->present($subject);
|
||||
|
||||
if ($own !== null && $own->kind === 'film') {
|
||||
return $this->found($own->url, $own->title, 'teaser');
|
||||
}
|
||||
}
|
||||
|
||||
if (! $preview) {
|
||||
return $this->none();
|
||||
}
|
||||
|
||||
if ($unreleased instanceof ContentElement) {
|
||||
$title = (string) ($unreleased->display_title ?: $unreleased->working_title);
|
||||
|
||||
return $this->none('Der Trailer „'.$title.'“ ist nicht für die Website freigegeben; öffentlich bleibt es beim Kartenbild (Medium öffnen → Reiter „Website“ → freigeben).');
|
||||
}
|
||||
|
||||
return $this->none(null, 'Kein Trailer zugeordnet; die Karte zeigt nur das Bild (Rolle „Trailer“ in der Präsentation des Mediums).');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, source: string, notice: string|null, hint: string|null}
|
||||
*/
|
||||
private function found(string $url, string $title, string $source): array
|
||||
{
|
||||
return ['url' => $url, 'title' => $title, 'source' => $source, 'notice' => null, 'hint' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, source: string, notice: string|null, hint: string|null}
|
||||
*/
|
||||
private function none(?string $notice = null, ?string $hint = null): array
|
||||
{
|
||||
return ['url' => null, 'title' => '', 'source' => 'none', 'notice' => $notice, 'hint' => $hint];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Support;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
|
||||
/**
|
||||
* Das Video des Einstiegs (Hero): ein stummer Clip auf der Fläche des Fotos.
|
||||
*
|
||||
* Gewählt wird ein Film aus dem Medienmanager. Abgespielt wird nur, was die Redaktion für die Website freigegeben hat,
|
||||
* und zwar nach derselben Regel wie auf der Karte (CardClip): Trailer des Films, sonst sein Vorschauclip, sonst seine
|
||||
* eigene freigegebene Website-Datei. Der vollständige Film, die Originaldatei und nicht freigegebene Clips kommen nie
|
||||
* über den Einstieg. Ohne freigegebenen Clip bleibt es beim Foto; die Auswahl gibt nichts frei.
|
||||
*/
|
||||
final class HeroVideo
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CardClip $clips,
|
||||
private readonly PublicMaterialReader $materials,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Auswahlliste: Filme, die auf der Website gezeigt werden dürfen, mit dem Stand ihrer Freigabe.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function options(?string $term, int $limit = 25): array
|
||||
{
|
||||
$term = trim((string) $term);
|
||||
|
||||
$candidates = ContentElement::query()
|
||||
->with('editorialContentKind')
|
||||
->where('output_class', 'film')
|
||||
->whereNull('archived_at')
|
||||
->when($term !== '', function ($query) use ($term): void {
|
||||
$like = '%'.mb_strtolower($term).'%';
|
||||
$query->where(fn ($inner) => $inner
|
||||
->whereRaw('LOWER(working_title) LIKE ?', [$like])
|
||||
->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like]));
|
||||
})
|
||||
->orderBy('working_title')
|
||||
->limit($limit * 2)
|
||||
->get();
|
||||
|
||||
$options = [];
|
||||
|
||||
foreach ($candidates as $element) {
|
||||
if (! $this->allowed($element)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$options[$element->id] = $this->label($element);
|
||||
|
||||
if (count($options) >= $limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
public function labelFor(mixed $id): ?string
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
return $element instanceof ContentElement ? $this->label($element) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die gewählte Kennung. Gibt die Kennung zurück oder null, wenn keine gewählt ist oder die Wahl ungültig ist.
|
||||
*/
|
||||
public function clean(mixed $value, WidgetErrors $errors, string $key = 'refs.video'): ?int
|
||||
{
|
||||
if ($value === null || $value === '' || $value === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$element = is_numeric($value) ? ContentElement::query()->with('editorialContentKind')->find((int) $value) : null;
|
||||
|
||||
if (! $element instanceof ContentElement || ! $this->allowed($element)) {
|
||||
$errors->add($key, 'Bitte einen Film aus dem Medienmanager wählen (nicht archiviert, nicht gesperrt, keine Traineranleitung).');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $element->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, notice: string|null}
|
||||
*/
|
||||
public function resolve(mixed $id, bool $preview): array
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
if (! $element instanceof ContentElement) {
|
||||
return ['url' => null, 'title' => '', 'notice' => null];
|
||||
}
|
||||
|
||||
$title = (string) ($element->display_title ?: $element->working_title);
|
||||
|
||||
if (! $this->allowed($element)) {
|
||||
return ['url' => null, 'title' => $title, 'notice' => $preview ? 'Das gewählte Medium „'.$title.'“ ist archiviert oder gesperrt; es erscheint kein Video.' : null];
|
||||
}
|
||||
|
||||
$clip = $this->clips->for($element, $preview);
|
||||
|
||||
if ($clip['url'] !== null) {
|
||||
return ['url' => $clip['url'], 'title' => $clip['title'] !== '' ? $clip['title'] : $title, 'notice' => null];
|
||||
}
|
||||
|
||||
return [
|
||||
'url' => null,
|
||||
'title' => $title,
|
||||
'notice' => $preview
|
||||
? 'Für „'.$title.'“ gibt es kein für die Website freigegebenes Video (Trailer, Vorschauclip oder freigegebene Website-Datei des Mediums); öffentlich bleibt es beim Foto. Freigabe: Medium öffnen → Reiter „Website“.'
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
/** Ein Film, der nicht archiviert, nicht gesperrt und keine Traineranleitung ist. */
|
||||
private function allowed(ContentElement $element): bool
|
||||
{
|
||||
return $element->output_class === 'film'
|
||||
&& $this->materials->isSelectable($element)
|
||||
&& ! in_array($element->editorialContentKind?->slug, PublicMaterialReader::CONFIDENTIAL_KINDS, true);
|
||||
}
|
||||
|
||||
private function label(ContentElement $element): string
|
||||
{
|
||||
$state = $this->clips->for($element, false)['url'] !== null ? 'Video freigegeben' : 'noch kein freigegebenes Video';
|
||||
|
||||
return (string) ($element->display_title ?: $element->working_title).' · '.$state;
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,10 @@ public function url(mixed $value, bool $preview = false): ?string
|
||||
|
||||
$legacy = self::normalize($value);
|
||||
|
||||
if (is_string($legacy) && WebsiteMediaAlias::isRetired($legacy)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return is_string($legacy) ? PublicMedia::url($legacy) : null;
|
||||
}
|
||||
|
||||
@@ -175,6 +179,10 @@ public function status(mixed $value): ?array
|
||||
|
||||
$id = $this->elementId($value);
|
||||
|
||||
if ($id === null && WebsiteMediaAlias::isRetired($value)) {
|
||||
return ['public' => false, 'state' => 'missing', 'title' => basename((string) $value), 'note' => 'Das Medium wurde gelöscht.', 'thumb' => null, 'manageUrl' => null];
|
||||
}
|
||||
|
||||
if ($id === null) {
|
||||
return [
|
||||
'public' => true,
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeroVideo;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Components\Group;
|
||||
@@ -20,6 +22,10 @@
|
||||
* Containerbreite), Label, Überschriftenebene, Bildfokus in Prozent, Akzent, zwei Schaltflächen.
|
||||
* Die data-Schlüssel der Version 1 (heading, text, cta_*, alt) bleiben unverändert, damit ältere Revisionen und ein
|
||||
* Code-Rollback darstellbar bleiben.
|
||||
*
|
||||
* Optional ein Video (refs.video, ein Film aus dem Medienmanager): In der Variante „Foto mit Textfläche“ läuft ein
|
||||
* stummer, für die Website freigegebener Clip auf der Fläche des Fotos (HeroVideo, resources/js/hero-video.js). Neuer
|
||||
* Schlüssel ohne Versionssprung; ältere Revisionen ohne `video` bleiben unverändert darstellbar.
|
||||
*/
|
||||
class HeroWidget extends WidgetType
|
||||
{
|
||||
@@ -64,9 +70,9 @@ public function narrowBehavior(): string
|
||||
public function heights(): array
|
||||
{
|
||||
return [
|
||||
'compact' => 'Kompakt (mind. 400 px)',
|
||||
'normal' => 'Normal (mind. 512 px)',
|
||||
'large' => 'Groß (mind. 640 px)',
|
||||
'compact' => 'Kompakt (niedriger, 75 % der Standardhöhe)',
|
||||
'normal' => 'Standard',
|
||||
'large' => 'Großzügig (höher, 130 % der Standardhöhe)',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -109,10 +115,18 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['accent'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'heading_level' => ['Überschriftenebene', 'Der erste Einstieg einer Seite ist immer die Hauptüberschrift (H1).'],
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Der erste Einstieg einer Seite ist immer die Hauptüberschrift (H1).'],
|
||||
'accent' => ['Markenakzent', 'Freigegebene Akzente aus dem Brand-UI-Kit. Vorgabe: gelbe Unterstreichung.'],
|
||||
];
|
||||
}
|
||||
@@ -152,7 +166,7 @@ public function dataRules(): array
|
||||
|
||||
public function refRules(): array
|
||||
{
|
||||
return ImageRefFields::rules();
|
||||
return ImageRefFields::rules() + ['video' => ['nullable']];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
@@ -169,7 +183,19 @@ public function dataFields(): array
|
||||
|
||||
public function refFields(): array
|
||||
{
|
||||
return ImageRefFields::fields(live: true);
|
||||
return [...ImageRefFields::fields(live: true), $this->videoField()];
|
||||
}
|
||||
|
||||
private function videoField(): Select
|
||||
{
|
||||
return Select::make('video')
|
||||
->label('Video (optional)')
|
||||
->helperText('Ein Film aus dem Medienmanager. Läuft stumm auf der Fläche des Fotos, nur in der Variante „Foto mit Textfläche“ und nur, wenn ein Trailer, Vorschauclip oder die Website-Datei des Films für die Website freigegeben ist. Das Foto bleibt als Rückfall, bei „reduzierte Bewegung“ und im Datensparmodus startet das Video nur auf Wunsch. Die Auswahl gibt nichts frei.')
|
||||
->live()
|
||||
->searchable()
|
||||
->getSearchResultsUsing(fn (?string $search): array => app(HeroVideo::class)->options($search))
|
||||
->getOptionLabelUsing(fn (mixed $value): ?string => app(HeroVideo::class)->labelFor($value))
|
||||
->options(fn (): array => app(HeroVideo::class)->options(null));
|
||||
}
|
||||
|
||||
public function editorSchema(): array
|
||||
@@ -192,6 +218,8 @@ public function mediaSchema(): array
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
$refs = ImageRefFields::clean($refs, $errors);
|
||||
$video = app(HeroVideo::class)->clean($refs['video'] ?? null, $errors);
|
||||
$video === null ? $refs = array_diff_key($refs, ['video' => true]) : $refs['video'] = $video;
|
||||
$data['heading'] = trim((string) ($data['heading'] ?? ''));
|
||||
$data['text'] = filled($data['text'] ?? null) ? trim((string) $data['text']) : null;
|
||||
$data = PremiumFields::clean($data, $errors, $refs['image'] !== null);
|
||||
@@ -205,8 +233,15 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
|
||||
$images = app(WebsiteImage::class);
|
||||
$image = $widget['refs']['image'] ?? null;
|
||||
$video = app(HeroVideo::class)->resolve($widget['refs']['video'] ?? null, $context->preview);
|
||||
$photoSplit = ($widget['variant'] ?? 'photo_split') !== 'editorial_solid';
|
||||
|
||||
if (! $photoSplit && $video['title'] !== '') {
|
||||
$video = ['url' => null, 'title' => $video['title'], 'notice' => $context->preview ? 'Das Video erscheint nur in der Variante „Foto mit Textfläche“; die Markenfläche zeigt kein Video.' : null];
|
||||
}
|
||||
|
||||
return [
|
||||
'video' => $video,
|
||||
'imageUrl' => $images->url($image, $context->preview),
|
||||
'imageAlt' => $images->alt($image, $widget['data']['alt'] ?? null),
|
||||
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
|
||||
|
||||
@@ -73,7 +73,7 @@ public function heights(): array
|
||||
{
|
||||
return [
|
||||
'compact' => 'Kompakt (flacheres Bild, engere Abstände)',
|
||||
'normal' => 'Normal',
|
||||
'normal' => 'Standard',
|
||||
'spacious' => 'Großzügig (höheres Bild, mehr Abstand)',
|
||||
];
|
||||
}
|
||||
@@ -117,11 +117,19 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['surface'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Steht das Widget als erstes auf der Seite, ist die Überschrift immer H1.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Steht das Widget als erstes auf der Seite, ist die Überschrift immer H1.'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,17 @@
|
||||
use App\Domain\Cms\Catalog\CardSubject;
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Media\FilmStill;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use Filament\Forms\Components\ViewField;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Medien- und Materialkarte (Kit v1.7 „media“): ein Inhaltselement mit Anzeigetitel, Kurzbeschreibung, Inhaltsart und
|
||||
* Ausgabeart. Filme erscheinen als Medienkarte (grüne Aktion, Filmtafel ohne freigegebenes Bild), Dokumente und andere
|
||||
* Materialien als Materialkarte (Materialsymbol). Öffentlich nur nach den Regeln von PublicMaterialReader; die Aktion
|
||||
* führt auf die öffentliche Programmseite. Die Karte spielt nichts ab, bietet keinen Download und gibt kein Medium frei.
|
||||
* führt auf die öffentliche Programmseite. Die Karte spielt höchstens den für die Website freigegebenen Trailer ab (CardClip), bietet keinen Download und gibt kein Medium frei.
|
||||
*/
|
||||
class MediaCardWidget extends PremiumCardWidget
|
||||
{
|
||||
@@ -28,7 +33,7 @@ public function label(): string
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Karte zu einem Film oder Material aus der Bibliothek; Titel und Art kommen aus den Fachdaten, kein Abspielen, kein Download.';
|
||||
return 'Karte zu einem Film oder Material aus der Bibliothek; Titel und Art kommen aus den Fachdaten, Trailer nur wenn freigegeben, kein Download.';
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
@@ -53,7 +58,7 @@ protected function refLabel(): string
|
||||
|
||||
protected function refHelp(): string
|
||||
{
|
||||
return 'Wählbar sind alle nicht archivierten, nicht gesperrten Filme und Materialien. Öffentlich erscheint die Karte nur mit bereitgestellter Fassung und wenn der Inhalt zu einem öffentlich gezeigten Programm gehört; Traineranleitungen nie. Titel und Kurzbeschreibung pflegen Sie im Medium.';
|
||||
return 'Wählbar sind alle nicht archivierten, nicht gesperrten Filme und Materialien. Öffentlich erscheint die Karte nur mit bereitgestellter Fassung und wenn der Inhalt zu einem öffentlich gezeigten Programm gehört; ein Film nur mit Website-Datei (zum Beispiel ein Teaser) erscheint, sobald diese Datei für die Website freigegeben ist. Traineranleitungen nie. Titel, Teaser, Kurzbeschreibung und Beschreibung pflegen Sie im Medium; welcher Text auf der Karte erscheint, wählen Sie unter „Darstellung“.';
|
||||
}
|
||||
|
||||
protected function searchSubjects(?string $term): array
|
||||
@@ -90,6 +95,80 @@ protected function cardStyle(): string
|
||||
return 'media';
|
||||
}
|
||||
|
||||
/**
|
||||
* Bei einem Film: das Vorschaubild des Films oder eine Stelle des Films als Kartenbild übernehmen. Das Bild wird
|
||||
* einmal als Bild-Medium abgelegt (FilmStill) und wie jedes andere Bild ausgewählt; die Karte liest nur diese Datei.
|
||||
*/
|
||||
protected function imageSourceFields(): array
|
||||
{
|
||||
return [
|
||||
ViewField::make('_filmbild')
|
||||
->label('Bild aus dem Film')
|
||||
->view('filament.cms.filmbild-feld')
|
||||
->dehydrated(false)
|
||||
->visible(fn (Get $get): bool => $this->filmFor($get('element')) !== null)
|
||||
->viewData(fn (Get $get): array => $this->filmFieldData($this->filmFor($get('element')))),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Anzeigedaten des Felds „Bild aus dem Film“. Die Stelle kommt aus der bereitgestellten Fassung, bei einem Film
|
||||
* nur mit Website-Datei aus dieser (Route content.website-frame).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function filmFieldData(?ContentElement $film): array
|
||||
{
|
||||
$stills = app(FilmStill::class);
|
||||
$version = $film instanceof ContentElement ? $stills->version($film) : null;
|
||||
|
||||
return [
|
||||
'film' => $film,
|
||||
'filmTitle' => $film instanceof ContentElement ? (string) ($film->display_title ?: $film->working_title) : '',
|
||||
'filmVersionId' => $version?->id,
|
||||
'filmWebsiteFrameUrl' => $film instanceof ContentElement && $version === null && $stills->websiteFile($film) !== null
|
||||
? route('content.website-frame', ['element' => $film])
|
||||
: null,
|
||||
'filmHasThumbnail' => $film instanceof ContentElement && is_string($film->thumbnail_path) && $film->thumbnail_path !== '',
|
||||
'filmThumbnailUrl' => $film instanceof ContentElement ? ThumbnailRef::url('editorial.card', 'element', (int) $film->id, $film->thumbnail_path) : null,
|
||||
'filmStartSecond' => $film instanceof ContentElement ? ($stills->thumbnailSecond($film) ?? '0') : '0',
|
||||
];
|
||||
}
|
||||
|
||||
private function filmFor(mixed $id): ?ContentElement
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
return $element instanceof ContentElement && app(FilmStill::class)->refusal($element) === null ? $element : null;
|
||||
}
|
||||
|
||||
protected function subjectNoun(): string
|
||||
{
|
||||
return 'Medium';
|
||||
}
|
||||
|
||||
protected function textChoices(): array
|
||||
{
|
||||
return [
|
||||
'auto' => 'Automatisch (Kurzbeschreibung, sonst Teaser)',
|
||||
'teaser' => 'Teaser',
|
||||
'summary' => 'Kurzbeschreibung',
|
||||
'description' => 'Ausführliche Beschreibung (erscheint öffentlich)',
|
||||
];
|
||||
}
|
||||
|
||||
protected function supportsClip(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function clipSubject(mixed $id): ?Model
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->find((int) $id) : null;
|
||||
|
||||
return $element instanceof ContentElement ? $element : null;
|
||||
}
|
||||
|
||||
protected function centralCoverId(mixed $id): ?int
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->find((int) $id) : null;
|
||||
|
||||
@@ -4,16 +4,19 @@
|
||||
|
||||
use App\Domain\Cms\Catalog\CardSubject;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\CardClip;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Field;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
@@ -56,6 +59,56 @@ abstract protected function defaultActionLabel(): string;
|
||||
/** Gestaltungsvariante des Kits: editorial, media oder catalog. */
|
||||
abstract protected function cardStyle(): string;
|
||||
|
||||
/**
|
||||
* Weitere Wege zum Kartenbild im Reiter „Medien“, zum Beispiel ein Bild aus dem Film. Standard: keine.
|
||||
*
|
||||
* @return list<Field>
|
||||
*/
|
||||
protected function imageSourceFields(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fachobjekt, dessen Trailer die Karte beim Überfahren oder Antippen abspielt (Medium, Programm, Modul).
|
||||
* Null: diese Karte hat keinen Clip (Thema). Der Clip kommt aus der Präsentation des Objekts (CardClip).
|
||||
*/
|
||||
protected function clipSubject(mixed $id): ?Model
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zentrale Texte des Fachobjekts, aus denen die Redaktion den Kartentext wählen kann: Wert => Bezeichnung.
|
||||
* Leer: keine Wahl (die Karte nimmt den Text ihrer Vorgabe). Mit Wahl gilt „auto“ als Vorgabe.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function textChoices(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Was die Redaktion bearbeitet, um einen Text zu pflegen („Medium“, „Programm oder Modul“); für Hinweise. */
|
||||
protected function subjectNoun(): string
|
||||
{
|
||||
return 'Objekt';
|
||||
}
|
||||
|
||||
/** Hinweis der Redaktionsvorschau, wenn der gewählte zentrale Text nicht gepflegt ist. */
|
||||
private function missingTextHint(string $field): string
|
||||
{
|
||||
$noun = $this->subjectNoun();
|
||||
|
||||
return match ($field) {
|
||||
'teaser' => 'Kein Teaser gepflegt ('.$noun.' bearbeiten → Teaser).',
|
||||
'summary' => 'Keine Kurzbeschreibung gepflegt ('.$noun.' bearbeiten → Kurzbeschreibung).',
|
||||
'description' => 'Keine ausführliche Beschreibung gepflegt ('.$noun.' bearbeiten → Beschreibung).',
|
||||
'goal' => 'Kein Lernziel gepflegt ('.$noun.' bearbeiten → Lernziel der Fassung).',
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
|
||||
public function view(): string
|
||||
{
|
||||
return 'widgets.premium_card';
|
||||
@@ -110,7 +163,9 @@ public function optionIcons(): array
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
$choices = $this->textChoices();
|
||||
|
||||
return ($choices === [] ? [] : ['text_source' => $choices]) + ($this->supportsClip() ? ['clip' => ['yes' => 'Abspielen', 'no' => 'Nicht abspielen'], 'show_body' => self::SHOW] : []) + [
|
||||
'format' => ['landscape' => 'Querformat 16:9', 'square' => 'Quadrat 1:1', 'portrait' => 'Hochformat 3:4'],
|
||||
'fit' => ['cover' => 'Ausschnitt füllt die Fläche', 'contain' => 'Ganzes Bild zeigen (Dokument, Poster)'],
|
||||
'heading_level' => ['h3' => 'H3', 'h2' => 'H2', 'h4' => 'H4'],
|
||||
@@ -121,16 +176,34 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Bild und Video' => ['format', 'fit', 'clip'],
|
||||
'Texte auf der Karte' => ['show_body', 'text_source', 'show_summary', 'show_kind', 'show_meta', 'show_action'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingHiddenWhen(): array
|
||||
{
|
||||
// „Texte auf der Karte: Ausblenden“ macht die Einzelschalter wirkungslos; sie bleiben gespeichert, aber unsichtbar.
|
||||
return array_fill_keys(['text_source', 'show_summary', 'show_kind', 'show_meta', 'show_action'], ['show_body', 'no']);
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'format' => ['Bildformat', 'Vorgabe: Querformat 16:9. Gilt auch neben dem Text; das Motiv wird nicht nachträglich hochkant beschnitten.'],
|
||||
'fit' => ['Bilddarstellung', 'Vorgabe: Ausschnitt. „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Vorgabe: H3, passend unter einer Abschnittsüberschrift (H2).'],
|
||||
'show_summary' => ['Kurzbeschreibung', 'Aus den Fachdaten. Vorgabe: anzeigen.'],
|
||||
'show_kind' => ['Art oder Label', 'Zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: anzeigen.'],
|
||||
'show_meta' => ['Zusatzangaben', 'Aus den Fachdaten, zum Beispiel Ausgabeart oder Programmzugehörigkeit. Vorgabe: anzeigen.'],
|
||||
'show_action' => ['Aktion', 'Verweis auf die öffentliche Seite des Fachobjekts, falls es eine gibt. Vorgabe: anzeigen.'],
|
||||
'format' => ['Bildformat', 'Seitenverhältnis des Bildes oder Videos. Vorgabe: Querformat 16:9. Gilt auch neben dem Text; das Motiv wird nicht nachträglich hochkant beschnitten.'],
|
||||
'fit' => ['Bildausschnitt', 'Ausschnitt füllt die ganze Fläche; „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche. Vorgabe: Ausschnitt.'],
|
||||
'clip' => ['Trailer auf der Karte', 'Spielt den freigegebenen Trailer als stumme Vorschau, solange die Maus auf der Karte steht; ein Klick oder Tipp auf das Bild oder die kleine Schaltfläche (auch per Tastatur) spielt ihn mit Ton. Gewählt wird der Trailer (sonst der Vorschauclip) in der Präsentation des Objekts, bei einem Film ersatzweise sein freigegebener Teaser. Ohne freigegebenen Clip bleibt das Kartenbild. Vorgabe: Abspielen.'],
|
||||
'show_body' => ['Texte auf der Karte', 'Hauptschalter für alle Texte neben dem Bild. „Ausblenden“ zeigt nur Bild und Video, ohne Titel, Beschreibung, Art, Zusatzangaben und Schaltfläche; die Einzelschalter darunter verschwinden dann. Für Hilfstechnik bleibt der Titel unsichtbar erhalten. Sinnvoll, wenn das Video allein erklärt. Vorgabe: Anzeigen.'],
|
||||
'text_source' => ['Quelle der Beschreibung', 'Welche Angabe aus der Redaktion als Beschreibung erscheint. Vorgabe: Automatisch. Der Text erscheint öffentlich, wenn die Karte öffentlich ist; ist er nicht gepflegt, bleibt die Karte ohne Beschreibung.'],
|
||||
'show_summary' => ['Beschreibung', 'Der Beschreibungstext unter dem Titel, aus den Fachdaten. Vorgabe: Anzeigen.'],
|
||||
'show_kind' => ['Art-Label', 'Kleines Label über dem Titel, zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: Anzeigen.'],
|
||||
'show_meta' => ['Zusatzangaben', 'Angaben aus den Fachdaten, zum Beispiel Ausgabeart oder Programmzugehörigkeit. Vorgabe: Anzeigen.'],
|
||||
'show_action' => ['Schaltfläche', 'Verweis auf die öffentliche Seite des Fachobjekts, falls es eine gibt. Vorgabe: Anzeigen.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Vorgabe: H3, passend unter einer Abschnittsüberschrift (H2).'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -195,13 +268,13 @@ public function editorSchema(): array
|
||||
->hintColor(fn (?string $state): string => filled($state) ? 'warning' : 'gray')
|
||||
->helperText('Leer übernimmt den Anzeigenamen des Fachobjekts. Eine Eintragung gilt nur für diese Karte und ändert die Quelle nicht.'),
|
||||
TextInput::make('summary')
|
||||
->label('Teaser nur für diese Karte')
|
||||
->label('Text nur für diese Karte')
|
||||
->maxLength(500)
|
||||
->live(onBlur: true)
|
||||
->placeholder(fn (Get $get): string => $this->centralText($get('../refs.'.$this->refKey()), 'summary') ?? 'Zentraler Teaser oder Kurzbeschreibung')
|
||||
->placeholder(fn (Get $get): string => $this->centralText($get('../refs.'.$this->refKey()), 'summary', $get('../settings.text_source')) ?? 'Zentraler Text aus der Redaktion')
|
||||
->hint(fn (?string $state): string => filled($state) ? 'Eigene Angabe für diese Karte' : 'Aus der Redaktion')
|
||||
->hintColor(fn (?string $state): string => filled($state) ? 'warning' : 'gray')
|
||||
->helperText('Leer übernimmt Teaser oder Kurzbeschreibung. Lehrinhalt, Rechte und Preise bleiben unberührt.'),
|
||||
->helperText('Leer übernimmt den Text, den „Text der Karte“ (Darstellung) wählt. Lehrinhalt, Rechte und Preise bleiben unberührt.'),
|
||||
])->statePath('data'),
|
||||
];
|
||||
}
|
||||
@@ -211,7 +284,7 @@ public function mediaSchema(): array
|
||||
[, , $alt, $focusX, $focusY] = $this->dataFields();
|
||||
|
||||
return [
|
||||
Group::make(ImageRefFields::fields('Kartenbild', live: true))->statePath('refs'),
|
||||
Group::make([...ImageRefFields::fields('Kartenbild', live: true), ...$this->imageSourceFields()])->statePath('refs'),
|
||||
Group::make([$alt, $focusX, $focusY])->statePath('data'),
|
||||
];
|
||||
}
|
||||
@@ -248,6 +321,12 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
$data = $widget['data'];
|
||||
|
||||
$subject = $this->subject($widget['refs'][$this->refKey()] ?? null, $context);
|
||||
$textSource = $option('text_source', 'auto');
|
||||
|
||||
if ($subject instanceof CardSubject && $textSource !== 'auto' && isset($this->textChoices()[$textSource])) {
|
||||
$subject = $subject->withTextChoice($textSource, $this->missingTextHint($textSource));
|
||||
}
|
||||
|
||||
$heading = filled($data['heading'] ?? null) ? trim((string) $data['heading']) : null;
|
||||
$lead = filled($data['summary'] ?? null) ? trim((string) $data['summary']) : null;
|
||||
|
||||
@@ -258,8 +337,16 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
$storedImage = WebsiteImage::normalize($widget['refs']['image'] ?? null);
|
||||
$imageRef = $storedImage ?? $this->centralCoverId($widget['refs'][$this->refKey()] ?? null);
|
||||
|
||||
$clip = null;
|
||||
|
||||
if ($this->supportsClip() && $option('clip', 'yes') === 'yes' && $subject instanceof CardSubject) {
|
||||
$owner = $this->clipSubject($widget['refs'][$this->refKey()] ?? null);
|
||||
$clip = $owner instanceof Model ? app(CardClip::class)->for($owner, $context->preview) : null;
|
||||
}
|
||||
|
||||
return [
|
||||
'subject' => $subject,
|
||||
'clip' => $clip,
|
||||
'cardStyle' => $subject?->style ?? $this->cardStyle(),
|
||||
'imageUrl' => app(WebsiteImage::class)->url($imageRef, $context->preview),
|
||||
'alt' => app(WebsiteImage::class)->alt($imageRef, $data['alt'] ?? null),
|
||||
@@ -277,6 +364,7 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
'actionLabel' => filled($data['action_label'] ?? null) ? (string) $data['action_label'] : $this->defaultActionLabel(),
|
||||
'note' => filled($data['note'] ?? null) ? (string) $data['note'] : null,
|
||||
'stacked' => $widget['variant'] === 'stacked',
|
||||
'bare' => $this->supportsClip() && $option('show_body', 'yes') === 'no',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -299,10 +387,15 @@ protected function centralCoverId(mixed $id): ?int
|
||||
return null;
|
||||
}
|
||||
|
||||
protected function supportsClip(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zentraler Anzeigename oder Teaser des gewählten Objekts (Redaktionsstand) für Platzhalter im Editor.
|
||||
*/
|
||||
private function centralText(mixed $id, string $field): ?string
|
||||
private function centralText(mixed $id, string $field, mixed $textSource = null): ?string
|
||||
{
|
||||
if (blank($id)) {
|
||||
return null;
|
||||
@@ -314,6 +407,10 @@ private function centralText(mixed $id, string $field): ?string
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($subject instanceof CardSubject && is_string($textSource) && isset($this->textChoices()[$textSource]) && $textSource !== 'auto') {
|
||||
$subject = $subject->withTextChoice($textSource, $this->missingTextHint($textSource));
|
||||
}
|
||||
|
||||
$text = $subject?->{$field};
|
||||
|
||||
return is_string($text) && trim($text) !== '' ? Str::limit(trim($text), 120) : null;
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
use App\Domain\Cms\Catalog\CardSubject;
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Media\CompositionStill;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use Filament\Forms\Components\ViewField;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Modul- und Programmkarte (Kit v1.7 „catalog“): ein Programm oder Modul über PublicCatalogReader, dieselbe
|
||||
@@ -41,6 +46,59 @@ public function schematic(): array
|
||||
return [[2, 2, 56, 32, 'line'], [5, 5, 22, 26, 'ink'], [8, 24, 10, 2, 'accent'], [31, 8, 10, 2, 'line'], [31, 13, 22, 4, 'ink'], [31, 25, 14, 5, 'ink']];
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Vorschaubild des Programms oder Moduls als Kartenbild übernehmen. Es wird einmal als Bild-Medium abgelegt
|
||||
* (CompositionStill) und wie jedes andere Bild ausgewählt; die Karte liest nur diese Datei.
|
||||
*/
|
||||
protected function imageSourceFields(): array
|
||||
{
|
||||
return [
|
||||
ViewField::make('_programmbild')
|
||||
->label('Bild aus dem Programm oder Modul')
|
||||
->view('filament.cms.kompositionsbild-feld')
|
||||
->dehydrated(false)
|
||||
->visible(fn (Get $get): bool => $this->compositionFor($get('composition')) !== null)
|
||||
->viewData(function (Get $get): array {
|
||||
$composition = $this->compositionFor($get('composition'));
|
||||
|
||||
return [
|
||||
'composition' => $composition,
|
||||
'compositionTitle' => $composition instanceof Composition ? (string) ($composition->display_title ?: $composition->designation) : '',
|
||||
'compositionThumbnailUrl' => $composition instanceof Composition && app(CompositionStill::class)->hasThumbnail($composition)
|
||||
? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path)
|
||||
: null,
|
||||
];
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
private function compositionFor(mixed $id): ?Composition
|
||||
{
|
||||
$composition = is_numeric($id) ? Composition::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
return $composition instanceof Composition && app(PublicCatalogReader::class)->isCardSelectable($composition) ? $composition : null;
|
||||
}
|
||||
|
||||
protected function subjectNoun(): string
|
||||
{
|
||||
return 'Programm oder Modul';
|
||||
}
|
||||
|
||||
/**
|
||||
* Wählbare Texte: die zentralen Texte des Programms oder Moduls und das Lernziel der Fassung. „Automatisch“ bleibt
|
||||
* wie bisher: Teaser, sonst Kurzbeschreibung, sonst Lernziel. Die ausführliche Beschreibung erscheint nur auf Wahl.
|
||||
*/
|
||||
protected function textChoices(): array
|
||||
{
|
||||
return [
|
||||
'auto' => 'Automatisch (Teaser, sonst Kurzbeschreibung, sonst Lernziel)',
|
||||
'teaser' => 'Teaser',
|
||||
'summary' => 'Kurzbeschreibung',
|
||||
'description' => 'Ausführliche Beschreibung (erscheint öffentlich)',
|
||||
'goal' => 'Lernziel der Fassung',
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
// Die Art (Programm oder Modul) bleibt immer sichtbar; sie lässt sich nicht ausblenden.
|
||||
@@ -99,6 +157,18 @@ protected function cardStyle(): string
|
||||
return 'catalog';
|
||||
}
|
||||
|
||||
protected function supportsClip(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function clipSubject(mixed $id): ?Model
|
||||
{
|
||||
$composition = is_numeric($id) ? Composition::query()->find((int) $id) : null;
|
||||
|
||||
return $composition instanceof Composition ? $composition : null;
|
||||
}
|
||||
|
||||
protected function centralCoverId(mixed $id): ?int
|
||||
{
|
||||
$composition = is_numeric($id) ? Composition::query()->find((int) $id) : null;
|
||||
|
||||
@@ -41,7 +41,7 @@ public function version(): int
|
||||
public const HEIGHTS = [
|
||||
'auto' => 'Automatisch',
|
||||
'compact' => 'Kompakt',
|
||||
'normal' => 'Normal',
|
||||
'normal' => 'Standard',
|
||||
'large' => 'Groß',
|
||||
'spacious' => 'Großzügig',
|
||||
'fill' => 'Abschnittshöhe füllen',
|
||||
@@ -194,6 +194,29 @@ public function settingLabels(): array
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gliederung der Einstellungen im Reiter „Darstellung“: Gruppentitel => Schlüssel der Einstellungen in der
|
||||
* Reihenfolge der Anzeige. Variante und Höhe stehen immer in der ersten Gruppe „Aufbau“. Einstellungen ohne
|
||||
* Gruppe erscheinen unter „Weitere Einstellungen“, so geht keine verloren.
|
||||
*
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Einstellungen, die im Editor ausgeblendet werden, solange eine andere Einstellung einen bestimmten Wert hat:
|
||||
* Schlüssel => [steuernde Einstellung, Wert, bei dem ausgeblendet wird]. Die Werte bleiben dabei erhalten.
|
||||
*
|
||||
* @return array<string, array{0: string, 1: string}>
|
||||
*/
|
||||
public function settingHiddenWhen(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle zulässigen Einstellungen einschließlich der gemeinsamen Höhe. Registry-Prüfung, Editor und Darstellung
|
||||
* verwenden ausschließlich diese Zusammenführung.
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Discount\DiscountResult;
|
||||
use App\Domain\Commerce\Discount\DiscountService;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Sitzungsgebundener Mehrangebotswarenkorb (Etappe 1). Er bleibt in derselben Browsersitzung über Anmeldung,
|
||||
* Registrierung und E-Mail-Bestätigung erhalten. Je Option gibt es genau eine Position. Optionen derselben Produktseite
|
||||
* (gleiche Komposition) sind Alternativen und werden nur nach ausdrücklichem Wechsel ersetzt.
|
||||
* Der Warenkorb reserviert weder Preis noch Konditionen; er merkt sich, was der Käufer gesehen hat.
|
||||
*/
|
||||
class Cart
|
||||
{
|
||||
public const KEY = 'shop.cart';
|
||||
|
||||
/** Eingelöster Rabattcode (Kennung); höchstens einer je Bestellung. */
|
||||
public const DISCOUNT_KEY = 'shop.discount';
|
||||
|
||||
public const ADDED = 'added';
|
||||
|
||||
public const PRESENT = 'present';
|
||||
|
||||
public const ALTERNATIVE = 'alternative';
|
||||
|
||||
public const UNAVAILABLE = 'unavailable';
|
||||
|
||||
public function __construct(
|
||||
private readonly OwnershipCheck $ownership,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly OfferService $offers,
|
||||
private readonly DiscountService $discounts,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<int, array{version_id: int, price_cents: int}>
|
||||
*/
|
||||
public function items(): array
|
||||
{
|
||||
return (array) session()->get(self::KEY, []);
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->items());
|
||||
}
|
||||
|
||||
public function has(Offer $offer): bool
|
||||
{
|
||||
return isset($this->items()[$offer->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die bereits enthaltene Alternative derselben Produktseite, falls vorhanden.
|
||||
*/
|
||||
public function alternativeTo(Offer $offer): ?Offer
|
||||
{
|
||||
$products = app(ProductOptions::class);
|
||||
$group = $products->groupKey($offer);
|
||||
|
||||
if ($group === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ids = array_diff(array_keys($this->items()), [$offer->id]);
|
||||
|
||||
return $ids === [] ? null : Offer::query()
|
||||
->whereIn('id', $ids)
|
||||
->get()
|
||||
->first(fn (Offer $other): bool => $products->groupKey($other) === $group);
|
||||
}
|
||||
|
||||
public function add(Offer $offer): string
|
||||
{
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version === null) {
|
||||
return self::UNAVAILABLE;
|
||||
}
|
||||
|
||||
if ($this->has($offer)) {
|
||||
return self::PRESENT;
|
||||
}
|
||||
|
||||
if ($this->alternativeTo($offer) !== null) {
|
||||
return self::ALTERNATIVE;
|
||||
}
|
||||
|
||||
$this->put($offer, $version);
|
||||
|
||||
return self::ADDED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ausdrücklicher Wechsel: die Alternative wird durch die gewählte Option ersetzt.
|
||||
*/
|
||||
public function switchTo(Offer $offer): bool
|
||||
{
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$alternative = $this->alternativeTo($offer);
|
||||
|
||||
if ($alternative !== null) {
|
||||
$this->remove($alternative);
|
||||
}
|
||||
|
||||
$this->put($offer, $version);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function remove(Offer $offer): void
|
||||
{
|
||||
$items = $this->items();
|
||||
unset($items[$offer->id]);
|
||||
session()->put(self::KEY, $items);
|
||||
}
|
||||
|
||||
/**
|
||||
* Der Käufer übernimmt Preis und Fassung, die der Shop jetzt zeigt.
|
||||
*/
|
||||
public function acceptCurrent(Offer $offer): void
|
||||
{
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version !== null && $this->has($offer)) {
|
||||
$this->put($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
session()->forget([self::KEY, self::DISCOUNT_KEY]);
|
||||
}
|
||||
|
||||
/** Der im Warenkorb eingelöste Code, auch wenn er gerade nicht (mehr) gilt. */
|
||||
public function discountCode(): ?DiscountCode
|
||||
{
|
||||
$id = session()->get(self::DISCOUNT_KEY);
|
||||
|
||||
return is_numeric($id) ? DiscountCode::query()->with('targets')->find((int) $id) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Löst einen Code ein. Er wird nur vorgemerkt, wenn er für diesen Warenkorb und dieses Konto gilt; sonst bleibt
|
||||
* der bisherige Stand und das Ergebnis nennt den Grund. Ein zweiter Code ersetzt den ersten (höchstens ein Code).
|
||||
*/
|
||||
public function applyCode(string $input, ?User $user, ?int $holderPartyId = null): DiscountResult
|
||||
{
|
||||
$code = $this->discounts->find($input);
|
||||
|
||||
if ($code === null) {
|
||||
return new DiscountResult(null, DiscountResult::UNKNOWN, 'Diesen Code kennen wir nicht. Prüfe die Schreibweise.');
|
||||
}
|
||||
|
||||
$previous = session()->get(self::DISCOUNT_KEY);
|
||||
session()->put(self::DISCOUNT_KEY, $code->id);
|
||||
$result = $this->review($user, $holderPartyId)->discount;
|
||||
|
||||
if ($result === null || ! $result->applied()) {
|
||||
$previous === null ? session()->forget(self::DISCOUNT_KEY) : session()->put(self::DISCOUNT_KEY, $previous);
|
||||
|
||||
return $result ?? new DiscountResult($code, DiscountResult::NO_MATCH, 'Der Code kann auf diese Bestellung nicht angewendet werden.');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function removeCode(): void
|
||||
{
|
||||
session()->forget(self::DISCOUNT_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serverseitige Prüfung: aktuelle Fassung, Preis, Kaufbarkeit, passende Inhaberart, vorhandene Rechte.
|
||||
*/
|
||||
public function review(?User $user = null, ?int $holderPartyId = null, bool $lockDiscount = false): CartReview
|
||||
{
|
||||
$offers = Offer::query()
|
||||
->whereIn('id', array_keys($this->items()))
|
||||
->with('composition')
|
||||
->get()
|
||||
->keyBy('id');
|
||||
$versions = [];
|
||||
|
||||
foreach ($this->items() as $offerId => $item) {
|
||||
$offer = $offers->get($offerId);
|
||||
|
||||
if ($offer !== null) {
|
||||
$versions[$offerId] = $this->purchasable($offer);
|
||||
}
|
||||
}
|
||||
|
||||
$holder = $user === null ? null : $this->holderFor($user, $holderPartyId, $versions);
|
||||
$lines = [];
|
||||
|
||||
foreach ($this->items() as $offerId => $item) {
|
||||
$offer = $offers->get($offerId);
|
||||
|
||||
if ($offer === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$version = $versions[$offerId] ?? null;
|
||||
$seen = (int) $item['price_cents'];
|
||||
|
||||
if ($version === null) {
|
||||
$lines[] = new CartLine($offer, null, CartLine::WITHDRAWN, $seen, null,
|
||||
'Diese Option ist nicht mehr erhältlich. Entferne sie, um mit den übrigen Positionen fortzufahren.');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = (int) $version->price_cents;
|
||||
|
||||
if ($holder !== null && ! $this->suitsHolder($version, $holder)) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::WRONG_HOLDER, $seen, $current,
|
||||
$version->holder_kind === 'organisation'
|
||||
? 'Diese Option ist für Organisationen. Bestelle als Verein oder entferne sie.'
|
||||
: 'Diese Option ist für Privatpersonen. Bestelle als Privatperson oder entferne sie.');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($holder !== null && $this->ownership->covers($holder, $version)) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::OWNED, $seen, $current);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($current !== $seen) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::PRICE_CHANGED, $seen, $current);
|
||||
} elseif ((int) $item['version_id'] !== $version->id) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::TERMS_CHANGED, $seen, $current,
|
||||
'Die Bedingungen dieser Option wurden aktualisiert. Bitte prüfe die Übersicht.');
|
||||
} else {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::OK, $seen, $current);
|
||||
}
|
||||
}
|
||||
|
||||
$code = $this->discountCode();
|
||||
$discount = null;
|
||||
|
||||
if ($code !== null) {
|
||||
$orderable = array_values(array_filter($lines, fn (CartLine $line): bool => $line->orderable()));
|
||||
$discount = $this->discounts->evaluate($code, $user, $orderable, lock: $lockDiscount);
|
||||
}
|
||||
|
||||
return new CartReview($lines, $holder, $discount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die aktive, als Kauf angebotene Fassung der Option; sonst null (nicht kaufbar oder zurückgezogen).
|
||||
*/
|
||||
public function purchasable(Offer $offer): ?OfferVersion
|
||||
{
|
||||
return $this->offers->purchasableVersion($offer);
|
||||
}
|
||||
|
||||
private function put(Offer $offer, OfferVersion $version): void
|
||||
{
|
||||
$items = $this->items();
|
||||
$items[$offer->id] = ['version_id' => $version->id, 'price_cents' => (int) $version->price_cents];
|
||||
session()->put(self::KEY, $items);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, OfferVersion|null> $versions
|
||||
*/
|
||||
private function holderFor(User $user, ?int $partyId, array $versions): ?Party
|
||||
{
|
||||
$onlyOrganisations = $versions !== [] && collect($versions)
|
||||
->filter()
|
||||
->every(fn (OfferVersion $version): bool => $version->holder_kind === 'organisation');
|
||||
|
||||
try {
|
||||
return $this->holders->resolve($user, $partyId, $onlyOrganisations);
|
||||
} catch (DomainRuleException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function suitsHolder(OfferVersion $version, Party $holder): bool
|
||||
{
|
||||
return ($version->holder_kind === 'organisation') === ($holder->type === PartyType::Organisation);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
|
||||
/**
|
||||
* Eine Position des Warenkorbs mit dem Ergebnis der serverseitigen Prüfung.
|
||||
*/
|
||||
final class CartLine
|
||||
{
|
||||
public const OK = 'ok';
|
||||
|
||||
public const PRICE_CHANGED = 'preis_geaendert';
|
||||
|
||||
public const TERMS_CHANGED = 'bedingungen_geaendert';
|
||||
|
||||
public const WITHDRAWN = 'zurueckgezogen';
|
||||
|
||||
public const OWNED = 'bereits_erworben';
|
||||
|
||||
public const WRONG_HOLDER = 'falscher_inhaber';
|
||||
|
||||
public function __construct(
|
||||
public readonly Offer $offer,
|
||||
public readonly ?OfferVersion $version,
|
||||
public readonly string $state,
|
||||
public readonly int $seenPriceCents,
|
||||
public readonly ?int $currentPriceCents,
|
||||
public readonly ?string $note = null,
|
||||
) {}
|
||||
|
||||
/** Geht in Summe und Bestellung ein. */
|
||||
public function orderable(): bool
|
||||
{
|
||||
return in_array($this->state, [self::OK, self::PRICE_CHANGED, self::TERMS_CHANGED], true);
|
||||
}
|
||||
|
||||
/** Verhindert den Abschluss, bis der Käufer die Position selbst entfernt oder den Inhaber wechselt. */
|
||||
public function blocks(): bool
|
||||
{
|
||||
return in_array($this->state, [self::WITHDRAWN, self::WRONG_HOLDER], true);
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
if ($this->offer->standalone_bundle && $this->version !== null) {
|
||||
$bundle = app(ProductOptions::class)->bundleOf($this->version);
|
||||
|
||||
if ($bundle !== null) {
|
||||
return (string) $bundle->name;
|
||||
}
|
||||
}
|
||||
|
||||
$composition = $this->offer->composition;
|
||||
|
||||
return $composition !== null
|
||||
? (string) ($composition->display_title ?: $composition->designation)
|
||||
: (string) $this->offer->name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Commerce\Discount\DiscountResult;
|
||||
use App\Domain\Identity\Party;
|
||||
|
||||
/**
|
||||
* Prüfergebnis des Warenkorbs für einen vorgesehenen Lizenzinhaber. Die Prüfsumme bindet die Bestellung an genau
|
||||
* diese Übersicht: Inhaber, Fassung und Preis jeder Position samt Zustand, auch der ausgeschlossenen.
|
||||
*/
|
||||
final class CartReview
|
||||
{
|
||||
/**
|
||||
* @param list<CartLine> $lines
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly array $lines,
|
||||
public readonly ?Party $holder,
|
||||
public readonly ?DiscountResult $discount = null,
|
||||
) {}
|
||||
|
||||
/** @return list<CartLine> */
|
||||
public function orderable(): array
|
||||
{
|
||||
return array_values(array_filter($this->lines, fn (CartLine $line): bool => $line->orderable()));
|
||||
}
|
||||
|
||||
/** Summe der Listenpreise der Positionen, die in die Bestellung eingehen. */
|
||||
public function subtotalCents(): int
|
||||
{
|
||||
return array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $this->orderable()));
|
||||
}
|
||||
|
||||
public function discountCents(): int
|
||||
{
|
||||
return $this->discount?->totalCents() ?? 0;
|
||||
}
|
||||
|
||||
/** Endgültiger Zahlbetrag: Listenpreise abzüglich Rabatt. */
|
||||
public function totalCents(): int
|
||||
{
|
||||
return $this->subtotalCents() - $this->discountCents();
|
||||
}
|
||||
|
||||
/** Rabatt einer Position in Cent. */
|
||||
public function discountFor(CartLine $line): int
|
||||
{
|
||||
return $this->discount?->forOffer($line->offer->id) ?? 0;
|
||||
}
|
||||
|
||||
/** Ein vorgemerkter Code, der jetzt nicht gilt, hält die Bestellung an, bis er entfernt wird. */
|
||||
public function discountBlocks(): bool
|
||||
{
|
||||
return $this->discount !== null && ! $this->discount->applied();
|
||||
}
|
||||
|
||||
public function blocked(): bool
|
||||
{
|
||||
foreach ($this->lines as $line) {
|
||||
if ($line->blocks()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function empty(): bool
|
||||
{
|
||||
return $this->orderable() === [];
|
||||
}
|
||||
|
||||
public function canOrder(): bool
|
||||
{
|
||||
return $this->holder !== null && ! $this->blocked() && ! $this->empty() && ! $this->discountBlocks();
|
||||
}
|
||||
|
||||
public function digest(): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
foreach ($this->lines as $line) {
|
||||
$parts[] = $line->offer->id.':'.($line->version?->id ?? 0).':'.$line->currentPriceCents.':'.$line->state;
|
||||
}
|
||||
|
||||
sort($parts);
|
||||
|
||||
return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts).'|'.($this->discount?->digestPart() ?? '-'));
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,19 @@
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Stripe\StripeGateway;
|
||||
use App\Domain\Entitlement\Acquisition;
|
||||
use App\Domain\Entitlement\AcquisitionType;
|
||||
use App\Domain\Entitlement\GrantIssuer;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Domain\Identity\AccountStatus;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Mail\OrderConfirmed;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
@@ -20,12 +26,21 @@ class Checkout
|
||||
public function __construct(
|
||||
private readonly GrantIssuer $grants,
|
||||
private readonly OfferService $offers,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly PaymentJournal $journal,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Einzelkauf einer Option als Person (bestehender Weg, ohne Warenkorb).
|
||||
*/
|
||||
public function place(User $user, Offer $offer): Order
|
||||
{
|
||||
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
||||
$this->assertActive($user);
|
||||
|
||||
// Dieser Einzelkauf kennt weder Zustimmungen noch „Zahlungspflichtig bestellen“. Im Livebetrieb gibt es nur den
|
||||
// Weg über die Kasse mit Pflichtangaben.
|
||||
if (Shop::live()) {
|
||||
throw new DomainRuleException('Bestelle über den Warenkorb und die Kasse.');
|
||||
}
|
||||
|
||||
$version = $this->offers->currentActiveVersion($offer);
|
||||
@@ -38,20 +53,114 @@ public function place(User $user, Offer $offer): Order
|
||||
throw new DomainRuleException('Der Kauf braucht einen Preis an der Angebotsfassung.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($user, $offer, $version): Order {
|
||||
$order = Order::query()->create([
|
||||
'user_id' => $user->id,
|
||||
'party_id' => $user->party_id,
|
||||
'status' => 'offen',
|
||||
'holder_kind' => 'person',
|
||||
]);
|
||||
$holder = $this->holders->resolve($user, null);
|
||||
|
||||
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]], null, null, Shop::driver() === 'stripe' ? 'stripe' : 'test'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bestellung aus dem Warenkorb, erst nach serverseitiger Prüfung. Die Prüfsumme bindet die Bestellung an die
|
||||
* Übersicht, die der Käufer gesehen hat: Hat sich Preis, Fassung oder Bedingung seither geändert, entsteht keine
|
||||
* Bestellung und der Käufer sieht zuerst die aktualisierte Übersicht. Positionen, deren Umfang der Inhaber bereits
|
||||
* mit denselben Rechten besitzt, erzeugen keine Bestellposition.
|
||||
*/
|
||||
public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, string $digest, ?array $consent = null, ?string $paymentMethod = null): Order
|
||||
{
|
||||
$this->assertActive($user);
|
||||
|
||||
if ($consent === null && Shop::live()) {
|
||||
throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.');
|
||||
}
|
||||
|
||||
$order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest, $consent, $paymentMethod): Order {
|
||||
// Optionen und den Rabattcode sperren, damit eine gleichzeitige Aktivierung, Deaktivierung oder ein Entzug
|
||||
// der Freigabe die Prüfung nicht unterläuft.
|
||||
Offer::query()->whereIn('id', array_keys($cart->items()))->orderBy('id')->lockForUpdate()->get();
|
||||
$discountId = session()->get(Cart::DISCOUNT_KEY);
|
||||
|
||||
if (is_numeric($discountId)) {
|
||||
DiscountCode::query()->whereKey((int) $discountId)->lockForUpdate()->first();
|
||||
}
|
||||
|
||||
$review = $cart->review($user, $holderPartyId, lockDiscount: true);
|
||||
|
||||
if ($review->holder === null) {
|
||||
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
|
||||
}
|
||||
|
||||
if (! hash_equals($review->digest(), $digest)) {
|
||||
throw new StaleOverview('Die Übersicht hat sich geändert. Bitte prüfe die aktualisierte Bestellübersicht.');
|
||||
}
|
||||
|
||||
if ($review->blocked()) {
|
||||
throw new DomainRuleException('Entferne zuerst die Positionen, die nicht bestellt werden können.');
|
||||
}
|
||||
|
||||
if ($review->empty()) {
|
||||
throw new DomainRuleException('Es gibt nichts zu bestellen. Alle Positionen sind bereits erworben.');
|
||||
}
|
||||
|
||||
if ($review->discountBlocks()) {
|
||||
throw new DomainRuleException(($review->discount?->message ?? 'Der Rabattcode gilt nicht.').' Entferne den Code, um ohne Rabatt zu bestellen.');
|
||||
}
|
||||
|
||||
$method = $paymentMethod ?? (Shop::driver() === 'stripe' ? 'stripe' : 'test');
|
||||
|
||||
if ($method === 'rechnung' && ! ($review->holder->type === PartyType::Organisation && Shop::invoice())) {
|
||||
throw new DomainRuleException('Der Kauf auf Rechnung ist nur für Vereine und Organisationen auf Anfrage möglich.');
|
||||
}
|
||||
|
||||
$pairs = array_map(fn (CartLine $line): array => [$line->offer, $line->version], $review->orderable());
|
||||
|
||||
return $this->createOrder($user, $review->holder, $pairs, $review, $consent === null ? null : SalesTerms::proof($consent), $method);
|
||||
});
|
||||
|
||||
$cart->clear();
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{0: Offer, 1: OfferVersion}> $pairs
|
||||
* @param array<string, mixed>|null $terms Nachweis der Zustimmungen (SalesTerms::proof)
|
||||
*/
|
||||
private function createOrder(User $user, Party $holder, array $pairs, ?CartReview $review, ?array $terms, string $method): Order
|
||||
{
|
||||
$subtotal = array_sum(array_map(fn (array $pair): int => (int) $pair[1]->price_cents, $pairs));
|
||||
$discount = $review?->discount;
|
||||
$discountCents = $review?->discountCents() ?? 0;
|
||||
|
||||
$order = Order::query()->create([
|
||||
'user_id' => $user->id,
|
||||
'party_id' => $holder->id,
|
||||
'status' => 'offen',
|
||||
'holder_kind' => $holder->type->value,
|
||||
'subtotal_cents' => $subtotal,
|
||||
'discount_cents' => $discountCents,
|
||||
'total_cents' => $subtotal - $discountCents,
|
||||
'currency' => 'EUR',
|
||||
'discount_code_id' => $discountCents > 0 ? $discount?->code?->id : null,
|
||||
'discount_snapshot' => $discountCents > 0 ? $discount?->snapshot() : null,
|
||||
'payment_method' => $method,
|
||||
'terms_accepted_at' => $terms === null ? null : now(),
|
||||
'terms_snapshot' => $terms,
|
||||
]);
|
||||
|
||||
foreach ($pairs as [$offer, $version]) {
|
||||
$line = $order->lines()->create([
|
||||
'offer_version_id' => $version->id,
|
||||
'offer_name' => $offer->name,
|
||||
'price_cents' => $version->price_cents,
|
||||
'currency' => 'EUR',
|
||||
'term_rule' => $version->term_rule,
|
||||
'update_promise' => $version->update_promise,
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'tax_class' => $version->tax_class,
|
||||
'grant_kind' => $version->grant_kind,
|
||||
'holder_party_id' => $holder->id,
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
'discount_cents' => $discountCents > 0 ? $discount->forOffer($offer->id) : 0,
|
||||
]);
|
||||
$version->load('resolvedScopes.rights');
|
||||
|
||||
@@ -66,14 +175,62 @@ public function place(User $user, Offer $offer): Order
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $order->load('lines.scopeItems');
|
||||
});
|
||||
return $order->load('lines.scopeItems');
|
||||
}
|
||||
|
||||
/**
|
||||
* Freischaltung nach bestätigter Testzahlung: alle Bestellpositionen aus ihrem festgehaltenen Umfang, in einer
|
||||
* Transaktion. Wiederholte Bestätigung ist wirkungslos; ein Fehler hinterlässt weder Zahlung noch Rechte.
|
||||
*/
|
||||
public function confirmTestPayment(Order $order, string $reference): Order
|
||||
{
|
||||
$this->assertTestDriver();
|
||||
$this->assertTestOrder($order);
|
||||
|
||||
return $this->settle($order, 'test', $reference, null, now(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die
|
||||
* Bestellung. Wiederholte Meldungen sind wirkungslos. `$live` sagt, ob echtes Geld geflossen ist (Stripe meldet
|
||||
* es je Ereignis); ohne Angabe gilt der Betriebszustand des Shops. `$occurredAt` ist der Zeitpunkt der Zahlung
|
||||
* laut Anbieter, sonst jetzt.
|
||||
*/
|
||||
public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency, ?bool $live = null, ?CarbonInterface $occurredAt = null, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents') - $order->lines()->sum('discount_cents'));
|
||||
|
||||
if ($amountCents !== $expected || strtoupper($currency) !== strtoupper((string) ($order->currency ?? 'EUR'))) {
|
||||
throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.');
|
||||
}
|
||||
|
||||
return $this->settle($order, $provider, $reference, null, $occurredAt ?? now(), $live ?? Shop::live(), $paymentIntent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kauf auf Rechnung (PAY-006): Der Betreiber hat die Rechnung manuell erstellt und bestätigt den Zahlungseingang.
|
||||
* Nur für Bestellungen mit Zahlungsweg „Rechnung“; das Mitglied kann das nicht selbst auslösen. Die Referenz
|
||||
* (Rechnungsnummer oder Buchung) wird an der Zahlung festgehalten. `$receivedOn` ist der Tag, an dem das Geld auf
|
||||
* dem Konto einging (nicht in der Zukunft, nicht vor der Bestellung); ohne Angabe gilt heute. Er bestimmt, in
|
||||
* welchen Zeitraum die Einnahme fällt.
|
||||
*/
|
||||
public function confirmInvoicePayment(Order $order, string $reference, User $actor, string|CarbonInterface|null $receivedOn = null): Order
|
||||
{
|
||||
$order->refresh();
|
||||
|
||||
if ($order->payment_method !== 'rechnung') {
|
||||
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
|
||||
}
|
||||
|
||||
$day = PaymentJournal::dayOf($receivedOn ?? now(PaymentJournal::TIMEZONE), $order->created_at);
|
||||
|
||||
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor, $day, Shop::live());
|
||||
}
|
||||
|
||||
private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy, CarbonInterface $occurredAt, bool $live, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$reference = trim($reference);
|
||||
|
||||
if ($reference === '') {
|
||||
@@ -81,7 +238,7 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
}
|
||||
|
||||
$paidNow = false;
|
||||
$order = DB::transaction(function () use ($order, $reference, &$paidNow): Order {
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, $occurredAt, $live, $paymentIntent, &$paidNow): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status === 'bezahlt') {
|
||||
@@ -92,22 +249,24 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
||||
}
|
||||
|
||||
$order->payments()->create([
|
||||
'provider' => 'test',
|
||||
'status' => 'bestaetigt',
|
||||
'provider_reference' => $reference,
|
||||
]);
|
||||
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
|
||||
$payment = $order->payments()->updateOrCreate(
|
||||
['provider_reference' => $reference],
|
||||
array_filter(
|
||||
['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id, 'provider_payment_ref' => $paymentIntent],
|
||||
fn (mixed $value): bool => $value !== null,
|
||||
),
|
||||
);
|
||||
$this->journal->recordPayment($order, $payment, $occurredAt, $confirmedBy, $live);
|
||||
$order->status = 'bezahlt';
|
||||
$order->save();
|
||||
$paidNow = true;
|
||||
$line = $order->lines()->firstOrFail();
|
||||
$this->grants->issue(
|
||||
$order->user,
|
||||
$line->offerVersion,
|
||||
AcquisitionType::Bestellposition,
|
||||
'order_line',
|
||||
$line->id,
|
||||
);
|
||||
$actor = User::query()->findOrFail($order->user_id);
|
||||
|
||||
foreach ($order->lines()->orderBy('id')->get() as $line) {
|
||||
$holder = Party::query()->findOrFail($line->holder_party_id ?? $order->party_id);
|
||||
$this->grants->issueFromOrderLine($line, $holder, $actor);
|
||||
}
|
||||
|
||||
return $order->load('lines', 'payments');
|
||||
});
|
||||
@@ -122,6 +281,7 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
public function failTestPayment(Order $order, string $reference): Order
|
||||
{
|
||||
$this->assertTestDriver();
|
||||
$this->assertTestOrder($order);
|
||||
|
||||
return DB::transaction(function () use ($order, $reference): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
@@ -142,7 +302,16 @@ public function failTestPayment(Order $order, string $reference): Order
|
||||
});
|
||||
}
|
||||
|
||||
public function refund(Order $order, string $reason): Order
|
||||
/**
|
||||
* Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen
|
||||
* (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Bundles sind Rückgabeeinheiten; freiwillige
|
||||
* Teilerstattungen gibt es zum Start nicht. Bei einer Zahlung über Stripe wird die Rückzahlung zuerst bei Stripe
|
||||
* veranlasst; erst wenn Stripe sie annimmt, werden Rechte entzogen. Wirkt sie dort nicht, bleibt alles unverändert.
|
||||
* Jede Erstattung wird im Zahlungsjournal gegengebucht, in derselben Transaktion: Bei Stripe mit Rückzahlungs-ID
|
||||
* und Zeitpunkt von Stripe, sonst (Überweisung, Testzahlung) mit `$refundedOn` (Tag der Rückzahlung, ohne Angabe
|
||||
* jetzt) und `$reference` (Überweisungsreferenz o. ä., sonst eine feste Kennung der Bestellung).
|
||||
*/
|
||||
public function refund(Order $order, string $reason, ?StripeGateway $stripe = null, ?User $actor = null, string|CarbonInterface|null $refundedOn = null, ?string $reference = null): Order
|
||||
{
|
||||
$reason = trim($reason);
|
||||
|
||||
@@ -150,22 +319,31 @@ public function refund(Order $order, string $reason): Order
|
||||
throw new DomainRuleException('Eine Erstattung braucht eine Begründung.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $reason): Order {
|
||||
$current = Order::query()->findOrFail($order->id);
|
||||
$stripePayment = $current->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->latest('id')->first();
|
||||
$manualAt = $refundedOn === null ? now() : PaymentJournal::dayOf($refundedOn, $current->created_at);
|
||||
$booking = null;
|
||||
|
||||
if ($current->status === 'bezahlt' && $stripePayment !== null) {
|
||||
$result = ($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
|
||||
$booking = ['reference' => $result['id'], 'status' => $result['status'], 'at' => $result['created'] ?? now()];
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $reason, $actor, $manualAt, $reference, $booking): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status !== 'bezahlt') {
|
||||
throw new DomainRuleException('Nur eine bezahlte Bestellung kann erstattet werden.');
|
||||
}
|
||||
|
||||
$line = $order->lines()->firstOrFail();
|
||||
$acquisition = Acquisition::query()->where([
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
])->first();
|
||||
foreach ($order->lines()->orderBy('id')->get() as $line) {
|
||||
$acquisition = Acquisition::query()->where([
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
])->first();
|
||||
|
||||
if ($acquisition !== null) {
|
||||
foreach ($acquisition->grants as $grant) {
|
||||
foreach ($acquisition?->grants ?? [] as $grant) {
|
||||
if ($grant->status === GrantStatus::Aktiv) {
|
||||
$grant->status = GrantStatus::Widerrufen;
|
||||
$grant->status_reason = $reason;
|
||||
@@ -174,6 +352,16 @@ public function refund(Order $order, string $reason): Order
|
||||
}
|
||||
}
|
||||
|
||||
$payment = $order->payments()->where('status', 'bestaetigt')->latest('id')->first();
|
||||
$this->journal->recordRefund(
|
||||
$order,
|
||||
$payment,
|
||||
$booking['at'] ?? $manualAt,
|
||||
$actor,
|
||||
$reason,
|
||||
$booking['reference'] ?? (filled($reference) ? 'erstattung-'.trim((string) $reference) : 'erstattung-bestellung-'.$order->id),
|
||||
$booking['status'] ?? null,
|
||||
);
|
||||
$order->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']);
|
||||
$order->status = 'erstattet';
|
||||
$order->save();
|
||||
@@ -182,6 +370,43 @@ public function refund(Order $order, string $reason): Order
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Mitglied erklärt den Widerruf (Verkaufsstart: kein Selbstbedienungs-Widerruf). Es entzieht nichts und
|
||||
* erstattet nichts; der Betreiber prüft den Fall (Erlöschen des Widerrufsrechts bei sofortiger Bereitstellung mit
|
||||
* ausdrücklicher Zustimmung) und erstattet bei Bedarf in der Bestellverwaltung.
|
||||
*/
|
||||
public function requestWithdrawal(Order $order, string $note): Order
|
||||
{
|
||||
if (! in_array($order->status, ['bezahlt', 'offen'], true)) {
|
||||
throw new DomainRuleException('Für diese Bestellung kann kein Widerruf erklärt werden.');
|
||||
}
|
||||
|
||||
if ($order->withdrawal_requested_at !== null) {
|
||||
return $order;
|
||||
}
|
||||
|
||||
$order->withdrawal_requested_at = now();
|
||||
$order->withdrawal_note = trim($note) !== '' ? trim($note) : null;
|
||||
$order->save();
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
private function assertActive(User $user): void
|
||||
{
|
||||
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
||||
}
|
||||
}
|
||||
|
||||
/** Eine Bestellung auf Rechnung oder über Stripe wird nie mit der Testzahlung bestätigt. */
|
||||
private function assertTestOrder(Order $order): void
|
||||
{
|
||||
if (in_array(Order::query()->whereKey($order->id)->value('payment_method'), ['rechnung', 'stripe'], true)) {
|
||||
throw new DomainRuleException('Diese Bestellung wird nicht mit der Testzahlung bezahlt.');
|
||||
}
|
||||
}
|
||||
|
||||
private function assertTestDriver(): void
|
||||
{
|
||||
if (app()->isProduction() || config('services.payment.driver') !== 'test') {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
/**
|
||||
* Reine Rechenregel für den Rabatt je Position (ganze Cent, keine Datenbank, keine Uhr).
|
||||
*
|
||||
* Prozent: je Position gerundet (kaufmännisch, ab 0,5 Cent nach oben), höchstens der Positionspreis. Die Summe ist
|
||||
* die Summe der gerundeten Positionsrabatte. Das kann um bis zu einen Cent je Position von der Rundung auf der
|
||||
* Warenkorbsumme abweichen (Rechenbeispiel in der Abnahme zum Verkaufsstart, Fachfrage).
|
||||
*
|
||||
* Betrag: Der Festbetrag gilt je Bestellung, höchstens bis zur Summe der betroffenen Positionen. Er wird anteilig
|
||||
* zum Positionspreis verteilt; verbleibende Cent erhalten die Positionen mit dem größten Rest, bei Gleichstand die
|
||||
* frühere Position.
|
||||
*/
|
||||
final class DiscountCalculator
|
||||
{
|
||||
/**
|
||||
* @param array<int|string, int> $prices Schlüssel der Position => Preis in Cent (nur betroffene Positionen)
|
||||
* @return array<int|string, int> Schlüssel => Rabatt in Cent
|
||||
*/
|
||||
public static function allocate(string $kind, ?int $percent, ?int $amountCents, array $prices): array
|
||||
{
|
||||
$discounts = array_fill_keys(array_keys($prices), 0);
|
||||
|
||||
if ($prices === []) {
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
if ($kind === DiscountCode::PERCENT) {
|
||||
$percent = max(0, min(100, (int) $percent));
|
||||
|
||||
foreach ($prices as $key => $price) {
|
||||
$discounts[$key] = min($price, intdiv($price * $percent + 50, 100));
|
||||
}
|
||||
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
$sum = array_sum($prices);
|
||||
$total = min(max(0, (int) $amountCents), $sum);
|
||||
|
||||
if ($total === 0 || $sum === 0) {
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
$remainders = [];
|
||||
$given = 0;
|
||||
|
||||
foreach ($prices as $key => $price) {
|
||||
$share = intdiv($total * $price, $sum);
|
||||
$discounts[$key] = $share;
|
||||
$remainders[$key] = ($total * $price) % $sum;
|
||||
$given += $share;
|
||||
}
|
||||
|
||||
$rest = $total - $given;
|
||||
$order = array_keys($prices);
|
||||
usort($order, fn ($left, $right): int => $remainders[$right] <=> $remainders[$left]);
|
||||
|
||||
foreach ($order as $key) {
|
||||
if ($rest === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
if ($discounts[$key] < $prices[$key]) {
|
||||
$discounts[$key]++;
|
||||
$rest--;
|
||||
}
|
||||
}
|
||||
|
||||
return $discounts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Domain\Commerce\Money;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Rabattcode (PAY-008, FACH-14). Zwei voneinander unabhängige Einstellungen:
|
||||
* - Geltungsbereich: gesamter Warenkorb oder nur ausdrücklich gewählte Ziele (Angebot, Lizenzartikel, Paket);
|
||||
* - Einlösungsberechtigung: allgemein oder nur für ausdrücklich freigeschaltete Konten (Freigabe gilt nur für diesen Code).
|
||||
* Der Rabatt ändert den Preis, nie den Nutzungsumfang.
|
||||
*/
|
||||
class DiscountCode extends Model
|
||||
{
|
||||
public const PERCENT = 'prozent';
|
||||
|
||||
public const AMOUNT = 'betrag';
|
||||
|
||||
public const SCOPE_CART = 'warenkorb';
|
||||
|
||||
public const SCOPE_SELECTED = 'auswahl';
|
||||
|
||||
public const OPEN = 'allgemein';
|
||||
|
||||
public const RESTRICTED = 'freigabe';
|
||||
|
||||
public const TARGET_OFFER = 'angebot';
|
||||
|
||||
public const TARGET_ARTICLE = 'lizenzartikel';
|
||||
|
||||
public const TARGET_BUNDLE = 'paket';
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'label',
|
||||
'kind',
|
||||
'percent',
|
||||
'amount_cents',
|
||||
'scope',
|
||||
'eligibility',
|
||||
'valid_from',
|
||||
'valid_until',
|
||||
'active',
|
||||
'note',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'valid_from' => 'datetime',
|
||||
'valid_until' => 'datetime',
|
||||
'active' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** Eingabe und Speicherung vereinheitlicht: ohne Leerzeichen, Großschreibung. */
|
||||
public static function normalise(string $input): string
|
||||
{
|
||||
return mb_strtoupper((string) preg_replace('/\s+/u', '', $input));
|
||||
}
|
||||
|
||||
public function targets(): HasMany
|
||||
{
|
||||
return $this->hasMany(DiscountCodeTarget::class);
|
||||
}
|
||||
|
||||
public function releases(): HasMany
|
||||
{
|
||||
return $this->hasMany(DiscountRelease::class)->latest('id');
|
||||
}
|
||||
|
||||
public function restricted(): bool
|
||||
{
|
||||
return $this->eligibility === self::RESTRICTED;
|
||||
}
|
||||
|
||||
public function forSelection(): bool
|
||||
{
|
||||
return $this->scope === self::SCOPE_SELECTED;
|
||||
}
|
||||
|
||||
/** Lesbare Höhe: „10 %“ oder „5,00 €“. */
|
||||
public function valueLabel(): string
|
||||
{
|
||||
return $this->kind === self::PERCENT
|
||||
? (int) $this->percent.' %'
|
||||
: Money::format((int) $this->amount_cents);
|
||||
}
|
||||
|
||||
/** Zeitlicher Zustand zum Zeitpunkt: 'aktiv', 'abgelaufen', 'noch_nicht' oder 'deaktiviert'. */
|
||||
public function stateAt(CarbonInterface $now): string
|
||||
{
|
||||
return match (true) {
|
||||
! $this->active => 'deaktiviert',
|
||||
$this->valid_from !== null && $this->valid_from->greaterThan($now) => 'noch_nicht',
|
||||
$this->valid_until !== null && ! $this->valid_until->greaterThan($now) => 'abgelaufen',
|
||||
default => 'aktiv',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Ausdrücklich gewähltes Ziel eines Codes mit Geltungsbereich „Auswahl“. Ein Paket ist ein eigenes Ziel; seine
|
||||
* Rabattfähigkeit folgt nie aus einem enthaltenen Lizenzartikel und umgekehrt.
|
||||
*/
|
||||
class DiscountCodeTarget extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'discount_code_id',
|
||||
'target_type',
|
||||
'target_id',
|
||||
];
|
||||
|
||||
public function code(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Freigabe eines Mitgliedskontos für genau einen Code. Freigaben werden nie gelöscht, nur entzogen; Verlauf und
|
||||
* Begründung bleiben erhalten. Eine Freigabe für Code X berechtigt nicht zur Nutzung von Code Y.
|
||||
*/
|
||||
class DiscountRelease extends Model
|
||||
{
|
||||
protected $table = 'discount_code_releases';
|
||||
|
||||
protected $fillable = [
|
||||
'discount_code_id',
|
||||
'user_id',
|
||||
'granted_by',
|
||||
'granted_at',
|
||||
'valid_until',
|
||||
'revoked_by',
|
||||
'revoked_at',
|
||||
'reason',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'granted_at' => 'datetime',
|
||||
'valid_until' => 'datetime',
|
||||
'revoked_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function code(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function grantor(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'granted_by');
|
||||
}
|
||||
|
||||
public function isActiveAt(CarbonInterface $now): bool
|
||||
{
|
||||
return $this->revoked_at === null
|
||||
&& $this->granted_at->lessThanOrEqualTo($now)
|
||||
&& ($this->valid_until === null || $this->valid_until->greaterThan($now));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
/**
|
||||
* Ergebnis der Prüfung eines Codes gegen einen Warenkorb: angewandt (Rabatt je Option) oder nicht angewandt mit
|
||||
* einer verständlichen Begründung. Ein Code, der gerade nicht gilt, bleibt als Ergebnis sichtbar, damit der Käufer
|
||||
* den Grund erfährt.
|
||||
*/
|
||||
final class DiscountResult
|
||||
{
|
||||
public const OK = 'ok';
|
||||
|
||||
public const UNKNOWN = 'unbekannt';
|
||||
|
||||
public const INACTIVE = 'deaktiviert';
|
||||
|
||||
public const NOT_YET = 'noch_nicht';
|
||||
|
||||
public const EXPIRED = 'abgelaufen';
|
||||
|
||||
public const LOGIN = 'anmeldung';
|
||||
|
||||
public const NO_RELEASE = 'keine_freigabe';
|
||||
|
||||
public const NO_MATCH = 'keine_position';
|
||||
|
||||
public const TOO_HIGH = 'zu_hoch';
|
||||
|
||||
/**
|
||||
* @param array<int, int> $perOffer Kennung der Option => Rabatt in Cent
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly ?DiscountCode $code,
|
||||
public readonly string $state,
|
||||
public readonly ?string $message = null,
|
||||
public readonly array $perOffer = [],
|
||||
) {}
|
||||
|
||||
public function applied(): bool
|
||||
{
|
||||
return $this->state === self::OK && $this->totalCents() > 0;
|
||||
}
|
||||
|
||||
public function totalCents(): int
|
||||
{
|
||||
return $this->state === self::OK ? array_sum($this->perOffer) : 0;
|
||||
}
|
||||
|
||||
public function forOffer(int $offerId): int
|
||||
{
|
||||
return $this->state === self::OK ? (int) ($this->perOffer[$offerId] ?? 0) : 0;
|
||||
}
|
||||
|
||||
/** Für die Bestellung festgehaltene Angaben zum Zeitpunkt der Bestellung. */
|
||||
public function snapshot(): array
|
||||
{
|
||||
return [
|
||||
'code' => $this->code?->code,
|
||||
'label' => $this->code?->label,
|
||||
'kind' => $this->code?->kind,
|
||||
'percent' => $this->code?->percent,
|
||||
'amount_cents' => $this->code?->amount_cents,
|
||||
'scope' => $this->code?->scope,
|
||||
'eligibility' => $this->code?->eligibility,
|
||||
'discount_cents' => $this->totalCents(),
|
||||
];
|
||||
}
|
||||
|
||||
/** Teil der Prüfsumme der Bestellübersicht. */
|
||||
public function digestPart(): string
|
||||
{
|
||||
$parts = [];
|
||||
$perOffer = $this->perOffer;
|
||||
ksort($perOffer);
|
||||
|
||||
foreach ($perOffer as $offerId => $cents) {
|
||||
$parts[] = $offerId.'='.$cents;
|
||||
}
|
||||
|
||||
return ($this->code?->id ?? 0).':'.$this->state.':'.implode(',', $parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\CartLine;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Prüfung und Pflege von Rabattcodes. Die Prüfung läuft serverseitig bei der Eingabe, in jeder Übersicht und
|
||||
* unmittelbar vor Bestellabschluss (unter Sperre); sie liest nur und ändert keine Bestellung.
|
||||
*/
|
||||
class DiscountService
|
||||
{
|
||||
/** Kleinster Zahlbetrag einer Bestellung mit Rabatt (Mindestbetrag der Kartenzahlung bei Stripe: 0,50 EUR). */
|
||||
public const MIN_PAYABLE_CENTS = 50;
|
||||
|
||||
public function find(string $input): ?DiscountCode
|
||||
{
|
||||
$code = DiscountCode::normalise($input);
|
||||
|
||||
return $code === '' ? null : DiscountCode::query()->where('code', $code)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<CartLine> $lines nur Positionen, die in die Bestellung eingehen
|
||||
*/
|
||||
public function evaluate(DiscountCode $code, ?User $user, array $lines, ?CarbonInterface $now = null, bool $lock = false): DiscountResult
|
||||
{
|
||||
$now ??= now();
|
||||
|
||||
$timing = $code->stateAt($now);
|
||||
|
||||
if ($timing !== 'aktiv') {
|
||||
return new DiscountResult($code, $timing, match ($timing) {
|
||||
'deaktiviert' => 'Dieser Code ist nicht mehr gültig, der Betreiber hat ihn deaktiviert.',
|
||||
'noch_nicht' => 'Dieser Code gilt erst ab dem '.$code->valid_from?->timezone(config('app.timezone'))->format('d.m.Y').'.',
|
||||
default => 'Dieser Code ist abgelaufen (gültig bis '.$code->valid_until?->timezone(config('app.timezone'))->format('d.m.Y').').',
|
||||
});
|
||||
}
|
||||
|
||||
if ($code->restricted()) {
|
||||
if ($user === null) {
|
||||
return new DiscountResult($code, DiscountResult::LOGIN, 'Dieser Code gilt nur für freigeschaltete Konten. Melde dich an, damit wir prüfen können, ob er für dein Konto gilt.');
|
||||
}
|
||||
|
||||
if ($this->activeRelease($code, $user, $now, $lock) === null) {
|
||||
return new DiscountResult($code, DiscountResult::NO_RELEASE, 'Dieser Code ist für dein Konto nicht freigeschaltet. Er gilt nur für Konten, die der Betreiber ausdrücklich dafür freigegeben hat. Wenn du denkst, dass dir die Freigabe zusteht, wende dich an den Betreiber.');
|
||||
}
|
||||
}
|
||||
|
||||
$matching = [];
|
||||
|
||||
foreach ($lines as $line) {
|
||||
if ($line->version !== null && $this->matches($code, $line->offer, $line->version)) {
|
||||
$matching[$line->offer->id] = (int) $line->currentPriceCents;
|
||||
}
|
||||
}
|
||||
|
||||
if ($matching === []) {
|
||||
return new DiscountResult($code, DiscountResult::NO_MATCH, $code->forSelection()
|
||||
? 'Dieser Code gilt nur für bestimmte Angebote, und keines davon liegt in deiner Bestellung.'
|
||||
: 'In deiner Bestellung gibt es keine Position, auf die der Code angewendet werden kann.');
|
||||
}
|
||||
|
||||
$perOffer = DiscountCalculator::allocate($code->kind, $code->percent, $code->amount_cents, $matching);
|
||||
$payable = array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $lines)) - array_sum($perOffer);
|
||||
|
||||
if ($payable < self::MIN_PAYABLE_CENTS) {
|
||||
return new DiscountResult($code, DiscountResult::TOO_HIGH, 'Mit diesem Code läge der Zahlbetrag unter '.Money::format(self::MIN_PAYABLE_CENTS).'. Das ist beim Start nicht vorgesehen. Wähle zusätzlich eine weitere Position oder verzichte auf den Code.');
|
||||
}
|
||||
|
||||
return new DiscountResult($code, DiscountResult::OK, null, $perOffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Passt die Position? Verglichen werden nur die ausdrücklich gewählten Ziele mit den unmittelbaren Positionen der
|
||||
* Angebotsfassung. Ein Paket gilt nur, wenn es selbst gewählt ist; ein enthaltener Artikel macht es nicht
|
||||
* rabattfähig, und ein Artikel in einem Paket macht das Angebot nicht rabattfähig.
|
||||
*/
|
||||
public function matches(DiscountCode $code, Offer $offer, OfferVersion $version): bool
|
||||
{
|
||||
if (! $code->forSelection()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$targets = $code->targets->groupBy('target_type')->map(fn ($rows) => $rows->pluck('target_id')->map(fn ($id): int => (int) $id)->all());
|
||||
|
||||
if (in_array($offer->id, $targets->get(DiscountCode::TARGET_OFFER, []), true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$version->loadMissing('lines.bundleVersion');
|
||||
|
||||
foreach ($version->lines as $line) {
|
||||
if ($line->license_article_id !== null && in_array((int) $line->license_article_id, $targets->get(DiscountCode::TARGET_ARTICLE, []), true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($line->bundleVersion !== null && in_array((int) $line->bundleVersion->bundle_id, $targets->get(DiscountCode::TARGET_BUNDLE, []), true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function activeRelease(DiscountCode $code, User $user, ?CarbonInterface $now = null, bool $lock = false): ?DiscountRelease
|
||||
{
|
||||
$now ??= now();
|
||||
$query = DiscountRelease::query()->where('discount_code_id', $code->id)->where('user_id', $user->id)->whereNull('revoked_at');
|
||||
|
||||
if ($lock) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
return $query->get()->first(fn (DiscountRelease $release): bool => $release->isActiveAt($now));
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt einen Code an oder ändert ihn. Gleiche Prüfung für Anlegen und Bearbeiten.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @param list<array{type: string, id: int}> $targets
|
||||
*/
|
||||
public function save(array $data, array $targets, ?DiscountCode $existing = null): DiscountCode
|
||||
{
|
||||
$code = DiscountCode::normalise((string) ($data['code'] ?? ''));
|
||||
$label = trim((string) ($data['label'] ?? ''));
|
||||
|
||||
if (preg_match('/^[A-Z0-9][A-Z0-9_-]{2,39}$/', $code) !== 1) {
|
||||
throw new DomainRuleException('Der Code besteht aus 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich oder Unterstrich, ohne Leerzeichen.');
|
||||
}
|
||||
|
||||
if ($label === '') {
|
||||
throw new DomainRuleException('Der Name des Codes fehlt. Er ist nur für die Verwaltung und erscheint nicht im Shop.');
|
||||
}
|
||||
|
||||
if (DiscountCode::query()->where('code', $code)->when($existing !== null, fn ($query) => $query->whereKeyNot($existing->id))->exists()) {
|
||||
throw new DomainRuleException('Diesen Code gibt es schon.');
|
||||
}
|
||||
|
||||
$kind = (string) ($data['kind'] ?? '');
|
||||
$percent = null;
|
||||
$amount = null;
|
||||
|
||||
if ($kind === DiscountCode::PERCENT) {
|
||||
$percent = (int) ($data['percent'] ?? 0);
|
||||
|
||||
if ($percent < 1 || $percent > 100) {
|
||||
throw new DomainRuleException('Der Prozentsatz liegt zwischen 1 und 100.');
|
||||
}
|
||||
} elseif ($kind === DiscountCode::AMOUNT) {
|
||||
$amount = Money::parse($data['amount_euro'] ?? ($data['amount_cents'] ?? null));
|
||||
|
||||
if ($amount === null || $amount <= 0) {
|
||||
throw new DomainRuleException('Der Rabattbetrag ist ein Eurobetrag über 0,00 €.');
|
||||
}
|
||||
} else {
|
||||
throw new DomainRuleException('Die Art des Rabatts ist Prozent oder fester Betrag.');
|
||||
}
|
||||
|
||||
$scope = (string) ($data['scope'] ?? '');
|
||||
$eligibility = (string) ($data['eligibility'] ?? '');
|
||||
|
||||
if (! in_array($scope, [DiscountCode::SCOPE_CART, DiscountCode::SCOPE_SELECTED], true)) {
|
||||
throw new DomainRuleException('Der Geltungsbereich ist der gesamte Warenkorb oder eine Auswahl.');
|
||||
}
|
||||
|
||||
if (! in_array($eligibility, [DiscountCode::OPEN, DiscountCode::RESTRICTED], true)) {
|
||||
throw new DomainRuleException('Die Einlösung ist allgemein oder auf freigeschaltete Konten beschränkt.');
|
||||
}
|
||||
|
||||
$targets = $this->cleanTargets($targets);
|
||||
|
||||
if ($scope === DiscountCode::SCOPE_SELECTED && $targets === []) {
|
||||
throw new DomainRuleException('Wähle mindestens ein Angebot, einen Lizenzartikel oder ein Paket, für das der Code gilt, oder lass ihn für den gesamten Warenkorb gelten.');
|
||||
}
|
||||
|
||||
$from = $this->date($data['valid_from'] ?? null);
|
||||
$until = $this->date($data['valid_until'] ?? null, true);
|
||||
|
||||
if ($from !== null && $until !== null && $until->lessThanOrEqualTo($from)) {
|
||||
throw new DomainRuleException('Das Ende der Gültigkeit liegt vor dem Beginn.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($existing, $code, $label, $kind, $percent, $amount, $scope, $eligibility, $from, $until, $data, $targets): DiscountCode {
|
||||
$model = $existing ?? new DiscountCode;
|
||||
$model->fill([
|
||||
'code' => $code,
|
||||
'label' => $label,
|
||||
'kind' => $kind,
|
||||
'percent' => $percent,
|
||||
'amount_cents' => $amount,
|
||||
'scope' => $scope,
|
||||
'eligibility' => $eligibility,
|
||||
'valid_from' => $from,
|
||||
'valid_until' => $until,
|
||||
'active' => (bool) ($data['active'] ?? true),
|
||||
'note' => filled($data['note'] ?? null) ? trim((string) $data['note']) : null,
|
||||
]);
|
||||
$model->save();
|
||||
|
||||
$model->targets()->delete();
|
||||
|
||||
if ($scope === DiscountCode::SCOPE_SELECTED) {
|
||||
foreach ($targets as $target) {
|
||||
$model->targets()->create(['target_type' => $target['type'], 'target_id' => $target['id']]);
|
||||
}
|
||||
}
|
||||
|
||||
return $model->load('targets');
|
||||
});
|
||||
}
|
||||
|
||||
public function setActive(DiscountCode $code, bool $active): DiscountCode
|
||||
{
|
||||
$code->active = $active;
|
||||
$code->save();
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schaltet ein Konto für genau diesen Code frei. Eine zweite aktive Freigabe desselben Kontos gibt es nicht.
|
||||
*/
|
||||
public function release(DiscountCode $code, User $member, ?User $actor, ?CarbonInterface $until = null, ?string $reason = null): DiscountRelease
|
||||
{
|
||||
if (! $code->restricted()) {
|
||||
throw new DomainRuleException('Dieser Code ist allgemein einlösbar. Freigaben gibt es nur für Codes mit beschränkter Einlösung.');
|
||||
}
|
||||
|
||||
if ($member->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein Mitgliedskonto kann für einen Code freigeschaltet werden.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($code, $member, $actor, $until, $reason): DiscountRelease {
|
||||
DiscountCode::query()->whereKey($code->id)->lockForUpdate()->firstOrFail();
|
||||
|
||||
if ($this->activeRelease($code, $member) !== null) {
|
||||
throw new DomainRuleException('Dieses Konto ist für den Code bereits freigeschaltet.');
|
||||
}
|
||||
|
||||
if ($until !== null && $until->lessThanOrEqualTo(now())) {
|
||||
throw new DomainRuleException('Das Ende der Freigabe liegt in der Vergangenheit.');
|
||||
}
|
||||
|
||||
return DiscountRelease::query()->create([
|
||||
'discount_code_id' => $code->id,
|
||||
'user_id' => $member->id,
|
||||
'granted_by' => $actor?->id,
|
||||
'granted_at' => now(),
|
||||
'valid_until' => $until,
|
||||
'reason' => filled($reason) ? trim((string) $reason) : null,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Entzieht die Freigabe. Sie bleibt mit Zeitpunkt, Person und Begründung gespeichert.
|
||||
*/
|
||||
public function revoke(DiscountRelease $release, ?User $actor, ?string $reason = null): DiscountRelease
|
||||
{
|
||||
return DB::transaction(function () use ($release, $actor, $reason): DiscountRelease {
|
||||
$release = DiscountRelease::query()->lockForUpdate()->findOrFail($release->id);
|
||||
|
||||
if ($release->revoked_at !== null) {
|
||||
throw new DomainRuleException('Diese Freigabe ist bereits entzogen.');
|
||||
}
|
||||
|
||||
$release->revoked_at = now();
|
||||
$release->revoked_by = $actor?->id;
|
||||
$release->reason = filled($reason) ? trim((string) $reason) : $release->reason;
|
||||
$release->save();
|
||||
|
||||
return $release;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{type: string, id: int}> $targets
|
||||
* @return list<array{type: string, id: int}>
|
||||
*/
|
||||
private function cleanTargets(array $targets): array
|
||||
{
|
||||
$clean = [];
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$type = (string) ($target['type'] ?? '');
|
||||
$id = (int) ($target['id'] ?? 0);
|
||||
$exists = match ($type) {
|
||||
DiscountCode::TARGET_OFFER => Offer::query()->whereKey($id)->exists(),
|
||||
DiscountCode::TARGET_ARTICLE => LicenseArticle::query()->whereKey($id)->exists(),
|
||||
DiscountCode::TARGET_BUNDLE => Bundle::query()->whereKey($id)->exists(),
|
||||
default => false,
|
||||
};
|
||||
|
||||
if (! $exists) {
|
||||
throw new DomainRuleException('Ein gewähltes Ziel des Codes gibt es nicht (mehr).');
|
||||
}
|
||||
|
||||
$clean[$type.':'.$id] = ['type' => $type, 'id' => $id];
|
||||
}
|
||||
|
||||
return array_values($clean);
|
||||
}
|
||||
|
||||
/** Ein Datum ohne Uhrzeit gilt als Tag: ab Tagesbeginn, als Ende einschließlich des ganzen Tages. */
|
||||
private function date(mixed $value, bool $endOfDay = false): ?CarbonInterface
|
||||
{
|
||||
if (! filled($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = Carbon::parse((string) $value, config('app.timezone'));
|
||||
|
||||
return $endOfDay && strlen(trim((string) $value)) <= 10 ? $date->endOfDay() : $date;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use LogicException;
|
||||
|
||||
/**
|
||||
* Eine Geldbewegung im Zahlungsjournal (Zahlungseingang oder Erstattung). Unveränderlich: Eine Zeile wird nur
|
||||
* angelegt, nie geändert oder gelöscht. Eine Korrektur ist eine neue Gegenbuchung. Beträge sind vorzeichenbehaftet
|
||||
* (Eingang positiv, Erstattung negativ), sodass die Summe den Saldo ergibt.
|
||||
*/
|
||||
class LedgerEntry extends Model
|
||||
{
|
||||
public const KIND_PAYMENT = 'eingang';
|
||||
|
||||
public const KIND_REFUND = 'erstattung';
|
||||
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
protected $table = 'payment_ledger';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'occurred_at' => 'datetime',
|
||||
'amount_cents' => 'integer',
|
||||
'live' => 'boolean',
|
||||
'derived' => 'boolean',
|
||||
'payer' => 'array',
|
||||
'order_snapshot' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::updating(function (): never {
|
||||
throw new LogicException('Das Zahlungsjournal ist unveränderlich. Korrekturen sind neue Gegenbuchungen.');
|
||||
});
|
||||
static::deleting(function (): never {
|
||||
throw new LogicException('Das Zahlungsjournal ist unveränderlich. Einträge werden nie gelöscht.');
|
||||
});
|
||||
}
|
||||
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
|
||||
public function isRefund(): bool
|
||||
{
|
||||
return $this->kind === self::KIND_REFUND;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
|
||||
/**
|
||||
* Beträge werden als ganze Cent gespeichert und in Euro angezeigt und eingegeben (deutsches Format).
|
||||
*/
|
||||
final class Money
|
||||
{
|
||||
/** Obergrenze eines Preises (1.000.000 €), weit unter dem Wertebereich der Datenbank. */
|
||||
public const MAX_CENTS = 100_000_000;
|
||||
|
||||
public static function format(?int $cents): string
|
||||
{
|
||||
return $cents === null ? '–' : number_format($cents / 100, 2, ',', '.').' €';
|
||||
}
|
||||
|
||||
/**
|
||||
* Euro-Eingabe („12,50“, „1.299“, „5“) als Cent. Leere Eingabe ergibt null.
|
||||
*/
|
||||
public static function parse(string|int|float|null $input): ?int
|
||||
{
|
||||
if ($input === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$text = trim((string) $input);
|
||||
|
||||
if ($text === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$text = str_replace([' ', '€'], '', $text);
|
||||
|
||||
if (str_contains($text, ',')) {
|
||||
$text = str_replace('.', '', $text);
|
||||
$text = str_replace(',', '.', $text);
|
||||
} elseif (preg_match('/^\d{1,3}(\.\d{3})+$/', $text) === 1) {
|
||||
$text = str_replace('.', '', $text);
|
||||
}
|
||||
|
||||
if (preg_match('/^\d+(\.\d{1,2})?$/', $text) !== 1) {
|
||||
throw new DomainRuleException('Der Preis ist kein gültiger Eurobetrag, zum Beispiel 12,50.');
|
||||
}
|
||||
|
||||
$cents = (int) round(((float) $text) * 100);
|
||||
|
||||
if ($cents > self::MAX_CENTS) {
|
||||
throw new DomainRuleException('Der Preis ist zu hoch. Zulässig sind höchstens '.self::format(self::MAX_CENTS).'.');
|
||||
}
|
||||
|
||||
return $cents;
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,41 @@ class Order extends Model
|
||||
'party_id',
|
||||
'status',
|
||||
'holder_kind',
|
||||
'total_cents',
|
||||
'currency',
|
||||
'subtotal_cents',
|
||||
'discount_cents',
|
||||
'discount_code_id',
|
||||
'discount_snapshot',
|
||||
'payment_method',
|
||||
'terms_accepted_at',
|
||||
'terms_snapshot',
|
||||
'withdrawal_requested_at',
|
||||
'withdrawal_note',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'discount_snapshot' => 'array',
|
||||
'terms_snapshot' => 'array',
|
||||
'terms_accepted_at' => 'datetime',
|
||||
'withdrawal_requested_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** Listenpreise vor Rabatt; bei älteren Bestellungen die Summe der Positionen. */
|
||||
public function subtotal(): int
|
||||
{
|
||||
return (int) ($this->subtotal_cents ?? $this->total_cents ?? $this->lines->sum('price_cents'));
|
||||
}
|
||||
|
||||
/** Endgültiger Zahlbetrag. */
|
||||
public function payable(): int
|
||||
{
|
||||
return (int) ($this->total_cents ?? $this->lines->sum('price_cents'));
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Identity\Membership;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Für wen ein Konto bestellen darf: für sich selbst (Person) und für Organisationen, bei denen es eine aktive
|
||||
* Mitgliedschaft mit Bestellberechtigung hat. Eine Bestellung hat genau einen Lizenzinhaber.
|
||||
*/
|
||||
class OrderHolders
|
||||
{
|
||||
/**
|
||||
* @return Collection<int, Party>
|
||||
*/
|
||||
public function for(User $user): Collection
|
||||
{
|
||||
$holders = collect();
|
||||
|
||||
if ($user->party_id !== null) {
|
||||
$person = Party::query()->find($user->party_id);
|
||||
|
||||
if ($person !== null) {
|
||||
$holders->push($person);
|
||||
}
|
||||
}
|
||||
|
||||
$organisations = Membership::query()
|
||||
->active()
|
||||
->where('user_id', $user->id)
|
||||
->where('may_order', true)
|
||||
->with('organisation')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->map(fn (Membership $membership): ?Party => $membership->organisation)
|
||||
->filter(fn (?Party $party): bool => $party !== null && $party->type === PartyType::Organisation);
|
||||
|
||||
return $holders->concat($organisations)->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Der gewählte Inhaber; ohne Wahl die Person, bei Angeboten nur für Organisationen die erste Organisation.
|
||||
*/
|
||||
public function resolve(User $user, ?int $partyId, bool $preferOrganisation = false): Party
|
||||
{
|
||||
$holders = $this->for($user);
|
||||
|
||||
if ($partyId !== null) {
|
||||
$chosen = $holders->first(fn (Party $party): bool => $party->id === $partyId);
|
||||
|
||||
if ($chosen === null) {
|
||||
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
|
||||
}
|
||||
|
||||
return $chosen;
|
||||
}
|
||||
|
||||
if ($preferOrganisation) {
|
||||
$organisation = $holders->first(fn (Party $party): bool => $party->type === PartyType::Organisation);
|
||||
|
||||
if ($organisation !== null) {
|
||||
return $organisation;
|
||||
}
|
||||
}
|
||||
|
||||
$person = $holders->first(fn (Party $party): bool => $party->type === PartyType::Person);
|
||||
|
||||
return $person ?? throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Identity\Party;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
@@ -17,13 +18,31 @@ class OrderLine extends Model
|
||||
'term_rule',
|
||||
'update_promise',
|
||||
'holder_kind',
|
||||
'currency',
|
||||
'tax_class',
|
||||
'grant_kind',
|
||||
'holder_party_id',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'discount_cents',
|
||||
];
|
||||
|
||||
/** Preis dieser Position nach Rabatt. */
|
||||
public function payable(): int
|
||||
{
|
||||
return (int) $this->price_cents - (int) $this->discount_cents;
|
||||
}
|
||||
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
|
||||
public function holder(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Party::class, 'holder_party_id');
|
||||
}
|
||||
|
||||
public function offerVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(OfferVersion::class);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Domain\Identity\Party;
|
||||
|
||||
/**
|
||||
* „Bereits erworben“ (FACH-59): Der vorgesehene Lizenzinhaber hat bereits eine gültige Lizenz mit demselben Umfang
|
||||
* und denselben Nutzungsrechten. Maßgeblich ist genau ein Erwerb, der jeden Umfangsposten der Angebotsfassung mit
|
||||
* gleichem Zweck, gleichen Fähigkeiten und gleichen Optionen trägt. Rechte mehrerer Erwerbe werden nicht zu einer
|
||||
* neuen Lizenz kombiniert. Alle Erwerbsarten zählen (Kauf, freier Abruf, manuelle Vergabe), sofern aktiv und gültig.
|
||||
*/
|
||||
class OwnershipCheck
|
||||
{
|
||||
public function covers(Party $holder, OfferVersion $version): bool
|
||||
{
|
||||
$needed = $this->needed($version);
|
||||
|
||||
if ($needed === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$now = now();
|
||||
$byAcquisition = Grant::query()
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id))
|
||||
->with('acquisition')
|
||||
->get()
|
||||
->filter(fn (Grant $grant): bool => ($grant->valid_from === null || ! $grant->valid_from->greaterThan($now))
|
||||
&& ($grant->valid_until === null || $grant->valid_until->greaterThan($now)))
|
||||
->groupBy('acquisition_id');
|
||||
|
||||
$wanted = LicenceScope::key($version->licence_scope, $version->trainer_count);
|
||||
|
||||
foreach ($byAcquisition as $grants) {
|
||||
$conditions = (array) ($grants->first()->acquisition?->conditions ?? []);
|
||||
|
||||
// Gleicher Umfang heißt auch gleicher Nutzerkreis: Eine Einzellizenz deckt keine Mehrfachlizenz ab und
|
||||
// umgekehrt (der Nutzerkreis wird nicht aus Zweck oder Preis abgeleitet).
|
||||
if (LicenceScope::key($conditions['licence_scope'] ?? null, isset($conditions['trainer_count']) ? (int) $conditions['trainer_count'] : null) !== $wanted) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$have = [];
|
||||
|
||||
foreach ($grants as $grant) {
|
||||
$have[$grant->license_article_id.'|'.$this->fingerprint($grant->rights_snapshot ?? [])] = true;
|
||||
}
|
||||
|
||||
if (array_diff_key($needed, $have) === []) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, true>
|
||||
*/
|
||||
private function needed(OfferVersion $version): array
|
||||
{
|
||||
$needed = [];
|
||||
$version->loadMissing('resolvedScopes.rights');
|
||||
|
||||
foreach ($version->resolvedScopes as $scope) {
|
||||
$needed[$scope->license_article_id.'|'.$this->fingerprint([
|
||||
'purpose' => $scope->rights->purpose,
|
||||
'capabilities' => $scope->rights->capabilities,
|
||||
'options' => $scope->rights->options ?? [],
|
||||
])] = true;
|
||||
}
|
||||
|
||||
return $needed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reihenfolge von Schlüsseln und Aktionen spielt keine Rolle.
|
||||
*
|
||||
* @param array<string, mixed> $rights
|
||||
*/
|
||||
private function fingerprint(array $rights): string
|
||||
{
|
||||
$capabilities = [];
|
||||
|
||||
foreach ((array) ($rights['capabilities'] ?? []) as $class => $actions) {
|
||||
$actions = array_values(array_unique((array) $actions));
|
||||
sort($actions);
|
||||
$capabilities[(string) $class] = $actions;
|
||||
}
|
||||
|
||||
ksort($capabilities);
|
||||
$options = (array) ($rights['options'] ?? []);
|
||||
ksort($options);
|
||||
|
||||
return md5(json_encode([
|
||||
'purpose' => (string) ($rights['purpose'] ?? ''),
|
||||
'capabilities' => $capabilities,
|
||||
'options' => $options,
|
||||
], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,9 @@ class Payment extends Model
|
||||
'provider',
|
||||
'status',
|
||||
'provider_reference',
|
||||
'provider_payment_ref',
|
||||
'amount_cents',
|
||||
'confirmed_by',
|
||||
];
|
||||
|
||||
public function order(): BelongsTo
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Zahlungsjournal: schreibt und liest die unveränderlichen Geldbewegungen (LedgerEntry). Geschrieben wird nur aus
|
||||
* derselben Transaktion, die die Bestellung auf „bezahlt“ oder „erstattet“ setzt, sodass beides nie auseinanderläuft.
|
||||
* Zeiträume und Datumsangaben gelten in deutscher Zeit (Geschäftsjahr, Monats- und Quartalsgrenzen); gespeichert wird
|
||||
* in UTC. Der Nachweis ist an die Grundsätze der ordnungsmäßigen Buchführung angelehnt (unveränderbar, nachvollziehbar);
|
||||
* ob er den Anforderungen der Steuerberatung genügt, ist dort zu bestätigen.
|
||||
*/
|
||||
final class PaymentJournal
|
||||
{
|
||||
public const TIMEZONE = 'Europe/Berlin';
|
||||
|
||||
/** Höchstzahl der in der Verwaltung gezeigten Zeilen; der Export enthält immer alle des Zeitraums. */
|
||||
public const DISPLAY_LIMIT = 500;
|
||||
|
||||
/**
|
||||
* Zahlungseingang. Wiederholte Meldung derselben Zahlung legt keine zweite Zeile an (Schlüssel: Art, Anbieter,
|
||||
* Referenz).
|
||||
*/
|
||||
public function recordPayment(Order $order, Payment $payment, CarbonInterface $occurredAt, ?User $actor, bool $live): LedgerEntry
|
||||
{
|
||||
return LedgerEntry::query()->firstOrCreate(
|
||||
['kind' => LedgerEntry::KIND_PAYMENT, 'provider' => $payment->provider, 'provider_reference' => $payment->provider_reference],
|
||||
[
|
||||
'order_id' => $order->id,
|
||||
'payment_id' => $payment->id,
|
||||
'occurred_at' => $this->utc($occurredAt),
|
||||
'amount_cents' => $order->payable(),
|
||||
'currency' => (string) ($order->currency ?? 'EUR'),
|
||||
'provider_payment_ref' => $payment->provider_payment_ref,
|
||||
'live' => $live,
|
||||
'actor_id' => $actor?->id,
|
||||
'actor_name' => $actor?->name,
|
||||
'payer' => $this->payer($order),
|
||||
'order_snapshot' => $this->orderSnapshot($order),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstattung: eine Gegenbuchung in Höhe des Zahlbetrags. Das Echt-Kennzeichen folgt dem Zahlungseingang der
|
||||
* Bestellung. `$reference` ist bei Stripe die Rückzahlungs-ID (re_...), sonst eine Referenz der Rückzahlung.
|
||||
*/
|
||||
public function recordRefund(Order $order, ?Payment $payment, CarbonInterface $occurredAt, ?User $actor, string $reason, string $reference, ?string $providerStatus = null): LedgerEntry
|
||||
{
|
||||
$original = LedgerEntry::query()->where('order_id', $order->id)->where('kind', LedgerEntry::KIND_PAYMENT)->orderBy('id')->first();
|
||||
|
||||
return LedgerEntry::query()->firstOrCreate(
|
||||
['kind' => LedgerEntry::KIND_REFUND, 'provider' => $payment?->provider ?? $original?->provider ?? 'unbekannt', 'provider_reference' => $reference],
|
||||
[
|
||||
'order_id' => $order->id,
|
||||
'payment_id' => $payment?->id,
|
||||
'occurred_at' => $this->utc($occurredAt),
|
||||
'amount_cents' => -$order->payable(),
|
||||
'currency' => (string) ($order->currency ?? 'EUR'),
|
||||
'provider_payment_ref' => $payment?->provider_payment_ref,
|
||||
'provider_status' => $providerStatus,
|
||||
'live' => $original?->live ?? false,
|
||||
'actor_id' => $actor?->id,
|
||||
'actor_name' => $actor?->name,
|
||||
'reason' => $reason,
|
||||
'payer' => $original?->payer ?? $this->payer($order),
|
||||
'order_snapshot' => $original?->order_snapshot ?? $this->orderSnapshot($order),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Datum ohne Uhrzeit (Zahlungseingang auf dem Konto): Beginn dieses Tages in deutscher Zeit. Nicht in der
|
||||
* Zukunft; `$notBefore` ist der früheste zulässige Tag (Bestelldatum).
|
||||
*/
|
||||
public static function dayOf(string|CarbonInterface $date, ?CarbonInterface $notBefore = null): CarbonImmutable
|
||||
{
|
||||
$day = CarbonImmutable::parse($date instanceof CarbonInterface ? $date->format('Y-m-d') : $date, self::TIMEZONE)->startOfDay();
|
||||
|
||||
if ($day->greaterThan(CarbonImmutable::now(self::TIMEZONE)->endOfDay())) {
|
||||
throw new DomainRuleException('Das Datum darf nicht in der Zukunft liegen.');
|
||||
}
|
||||
|
||||
if ($notBefore !== null && $day->lessThan(CarbonImmutable::instance($notBefore)->setTimezone(self::TIMEZONE)->startOfDay())) {
|
||||
throw new DomainRuleException('Das Datum liegt vor dem Bestelldatum.');
|
||||
}
|
||||
|
||||
return $day;
|
||||
}
|
||||
|
||||
/**
|
||||
* Von und bis (einschließlich) eines Zeitraums in UTC.
|
||||
*
|
||||
* @param 'monat'|'quartal'|'jahr' $mode
|
||||
* @return array{0: CarbonImmutable, 1: CarbonImmutable}
|
||||
*/
|
||||
public static function range(string $mode, int $year, int $index): array
|
||||
{
|
||||
$from = CarbonImmutable::create($year, 1, 1, 0, 0, 0, self::TIMEZONE);
|
||||
|
||||
$from = match ($mode) {
|
||||
'monat' => $from->setMonth(max(1, min(12, $index)))->startOfMonth(),
|
||||
'quartal' => $from->setMonth((max(1, min(4, $index)) - 1) * 3 + 1)->startOfMonth(),
|
||||
default => $from->startOfYear(),
|
||||
};
|
||||
$to = match ($mode) {
|
||||
'monat' => $from->endOfMonth(),
|
||||
'quartal' => $from->addMonths(2)->endOfMonth(),
|
||||
default => $from->endOfYear(),
|
||||
};
|
||||
|
||||
return [$from->setTimezone('UTC'), $to->setTimezone('UTC')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param 'alle'|'eingang'|'erstattung' $kind
|
||||
* @param 'alle'|'stripe'|'ueberweisung'|'test' $provider
|
||||
* @param 'echt'|'test'|'alle' $operation
|
||||
* @return Collection<int, LedgerEntry>
|
||||
*/
|
||||
public function entries(CarbonInterface $from, CarbonInterface $to, string $kind = 'alle', string $provider = 'alle', string $operation = 'echt', ?int $offerId = null): Collection
|
||||
{
|
||||
return LedgerEntry::query()
|
||||
->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])
|
||||
->when($offerId !== null, fn ($query) => $query->whereHas('order.lines.offerVersion', fn ($versions) => $versions->where('offer_id', $offerId)))
|
||||
->when($kind !== 'alle', fn ($query) => $query->where('kind', $kind))
|
||||
->when($provider !== 'alle', fn ($query) => $query->where('provider', $provider))
|
||||
->when($operation === 'echt', fn ($query) => $query->where('live', true))
|
||||
->when($operation === 'test', fn ($query) => $query->where('live', false))
|
||||
->orderBy('occurred_at')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Anteil eines Angebots an jeder Bewegung: die Positionen dieses Angebots in der Bestellung (Preis nach Rabatt,
|
||||
* wie bei der Bestellung festgehalten), bei einer Erstattung negativ. Eine Buchung trägt den Betrag der ganzen
|
||||
* Bestellung; ohne diese Aufteilung würde eine Bestellung mit mehreren Angeboten den Umsatz des einzelnen
|
||||
* Angebots überzeichnen. Es gibt nur Vollerstattungen, deshalb ist der Anteil der Erstattung der gespiegelte.
|
||||
*
|
||||
* @param Collection<int, LedgerEntry> $entries
|
||||
* @return array<int, int> Buchungsnummer => Anteil in Cent (mit Vorzeichen der Buchung)
|
||||
*/
|
||||
public function shares(Collection $entries, int $offerId): array
|
||||
{
|
||||
$perOrder = OrderLine::query()
|
||||
->whereIn('order_id', $entries->pluck('order_id')->unique()->all())
|
||||
->whereHas('offerVersion', fn ($versions) => $versions->where('offer_id', $offerId))
|
||||
->get()
|
||||
->groupBy('order_id')
|
||||
->map(fn (Collection $lines): int => (int) $lines->sum(fn (OrderLine $line): int => $line->payable()));
|
||||
$shares = [];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$share = (int) ($perOrder[$entry->order_id] ?? 0);
|
||||
$shares[$entry->id] = $entry->isRefund() ? -$share : $share;
|
||||
}
|
||||
|
||||
return $shares;
|
||||
}
|
||||
|
||||
/**
|
||||
* Anzahl der Bewegungen außerhalb des Betriebsfilters, damit ein leerer Echtbetrieb nicht wie „keine Daten“ wirkt.
|
||||
*/
|
||||
public function countByOperation(CarbonInterface $from, CarbonInterface $to): array
|
||||
{
|
||||
$rows = LedgerEntry::query()->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])->get(['live']);
|
||||
|
||||
return ['echt' => $rows->where('live', true)->count(), 'test' => $rows->where('live', false)->count()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, LedgerEntry> $entries
|
||||
* @param array<int, int>|null $shares Anteile eines Angebots (shares), sonst die ganzen Buchungen
|
||||
* @return array{eingang: int, erstattung: int, saldo: int, anzahl_eingang: int, anzahl_erstattung: int}
|
||||
*/
|
||||
public static function totals(Collection $entries, ?array $shares = null): array
|
||||
{
|
||||
$in = $entries->where('kind', LedgerEntry::KIND_PAYMENT);
|
||||
$out = $entries->where('kind', LedgerEntry::KIND_REFUND);
|
||||
$amount = fn (LedgerEntry $entry): int => $shares === null ? $entry->amount_cents : (int) ($shares[$entry->id] ?? 0);
|
||||
|
||||
return [
|
||||
'eingang' => (int) $in->sum($amount),
|
||||
'erstattung' => (int) abs($out->sum($amount)),
|
||||
'saldo' => (int) $entries->sum($amount),
|
||||
'anzahl_eingang' => $in->count(),
|
||||
'anzahl_erstattung' => $out->count(),
|
||||
];
|
||||
}
|
||||
|
||||
public static function providerLabel(string $provider): string
|
||||
{
|
||||
return match ($provider) {
|
||||
'stripe' => 'Stripe',
|
||||
'ueberweisung' => 'Überweisung',
|
||||
'test' => 'Testzahlung',
|
||||
default => $provider,
|
||||
};
|
||||
}
|
||||
|
||||
public static function local(CarbonInterface $moment): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::instance($moment)->setTimezone(self::TIMEZONE);
|
||||
}
|
||||
|
||||
/** Hat die Bewegung eine belegte Uhrzeit? Datumsbuchungen (Überweisung) beginnen um 00:00 deutscher Zeit. */
|
||||
public static function hasTime(LedgerEntry $entry): bool
|
||||
{
|
||||
return self::local($entry->occurred_at)->format('H:i:s') !== '00:00:00';
|
||||
}
|
||||
|
||||
/**
|
||||
* Semikolon-getrennt, Dezimalkomma, UTF-8 mit BOM: öffnet in Excel und bei der Steuerberatung ohne Umweg.
|
||||
*
|
||||
* @param Collection<int, LedgerEntry> $entries
|
||||
* @param array<int, int>|null $shares Mit Angebotsfilter eine zusätzliche Spalte „Anteil des Angebots“
|
||||
*/
|
||||
public static function csv(Collection $entries, ?array $shares = null): string
|
||||
{
|
||||
$header = [
|
||||
'Buchungsnummer', 'Datum', 'Uhrzeit', 'Art', 'Betrag EUR', 'Währung', 'Bestellung', 'Zahlungsweg', 'Betrieb', 'Herkunft',
|
||||
'Referenz', 'Zahlungsvorgang', 'Status beim Anbieter', 'Lizenzinhaber', 'Rechnungsempfänger', 'Zusatz', 'Straße', 'PLZ', 'Ort', 'Land',
|
||||
'Besteller', 'Zwischensumme EUR', 'Rabatt EUR', 'Rabattcode', 'Positionen', 'Begründung', 'Gebucht von', 'Gebucht am',
|
||||
...($shares === null ? [] : ['Anteil des Angebots EUR']),
|
||||
];
|
||||
$rows = [$header];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$local = self::local($entry->occurred_at);
|
||||
$payer = (array) $entry->payer;
|
||||
$billing = (array) ($payer['billing'] ?? []);
|
||||
$snapshot = (array) $entry->order_snapshot;
|
||||
$lines = collect($snapshot['lines'] ?? [])->map(fn (array $line): string => ($line['name'] ?? '').' '.self::decimal((int) ($line['price_cents'] ?? 0) - (int) ($line['discount_cents'] ?? 0)))->implode(' | ');
|
||||
|
||||
$rows[] = [
|
||||
$entry->id,
|
||||
$local->format('d.m.Y'),
|
||||
self::hasTime($entry) ? $local->format('H:i:s') : '',
|
||||
$entry->isRefund() ? 'Erstattung' : 'Zahlungseingang',
|
||||
self::decimal($entry->amount_cents),
|
||||
$entry->currency,
|
||||
$entry->order_id,
|
||||
self::providerLabel($entry->provider),
|
||||
$entry->live ? 'echt' : 'Test',
|
||||
$entry->derived ? 'nachgetragen (Datum abgeleitet)' : 'belegt',
|
||||
$entry->provider_reference,
|
||||
$entry->provider_payment_ref,
|
||||
$entry->provider_status,
|
||||
$payer['holder'] ?? null,
|
||||
$billing['recipient'] ?? null,
|
||||
$billing['line2'] ?? null,
|
||||
$billing['street'] ?? null,
|
||||
$billing['postal_code'] ?? null,
|
||||
$billing['city'] ?? null,
|
||||
$billing['country'] ?? null,
|
||||
$payer['buyer'] ?? null,
|
||||
self::decimal((int) ($snapshot['subtotal_cents'] ?? 0)),
|
||||
self::decimal((int) ($snapshot['discount_cents'] ?? 0)),
|
||||
$snapshot['discount_code'] ?? null,
|
||||
$lines,
|
||||
$entry->reason,
|
||||
$entry->actor_name,
|
||||
self::local($entry->created_at)->format('d.m.Y H:i:s'),
|
||||
...($shares === null ? [] : [self::decimal((int) ($shares[$entry->id] ?? 0))]),
|
||||
];
|
||||
}
|
||||
|
||||
$handle = fopen('php://temp', 'r+');
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($handle, array_map(self::cell(...), $row), ';', '"', '\\', "\r\n");
|
||||
}
|
||||
|
||||
rewind($handle);
|
||||
$csv = (string) stream_get_contents($handle);
|
||||
fclose($handle);
|
||||
|
||||
return "\xEF\xBB\xBF".$csv;
|
||||
}
|
||||
|
||||
public static function decimal(int $cents): string
|
||||
{
|
||||
return number_format($cents / 100, 2, ',', '');
|
||||
}
|
||||
|
||||
/** Verhindert, dass ein Zellinhalt in der Tabellenkalkulation als Formel ausgeführt wird. */
|
||||
private static function cell(mixed $value): string
|
||||
{
|
||||
$text = (string) $value;
|
||||
|
||||
if ($text !== '' && preg_match('/^[=+\-@\t\r]/', $text) === 1 && preg_match('/^-?\d+(,\d+)?$/', $text) !== 1) {
|
||||
return "'".$text;
|
||||
}
|
||||
|
||||
return $text;
|
||||
}
|
||||
|
||||
private function utc(CarbonInterface $moment): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::instance($moment)->setTimezone('UTC');
|
||||
}
|
||||
|
||||
/**
|
||||
* Zahler zum Zeitpunkt der Bewegung. Spätere Änderungen an Profil oder Rechnungsadresse ändern sie nicht.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function payer(Order $order): array
|
||||
{
|
||||
$order->loadMissing('user', 'party.billingAddress');
|
||||
$address = $order->party?->billingAddress;
|
||||
|
||||
return [
|
||||
'holder' => $order->party?->display_name,
|
||||
'holder_kind' => $order->holder_kind,
|
||||
'buyer' => $order->user?->name,
|
||||
'buyer_email' => $order->user?->email,
|
||||
'billing' => $address === null ? null : [
|
||||
'recipient' => $address->recipient,
|
||||
'line2' => $address->line2,
|
||||
'street' => $address->street,
|
||||
'postal_code' => $address->postal_code,
|
||||
'city' => $address->city,
|
||||
'country' => $address->country,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function orderSnapshot(Order $order): array
|
||||
{
|
||||
$order->loadMissing('lines');
|
||||
|
||||
return [
|
||||
'subtotal_cents' => $order->subtotal(),
|
||||
'discount_cents' => (int) $order->discount_cents,
|
||||
'discount_code' => $order->discount_snapshot['code'] ?? null,
|
||||
'lines' => $order->lines->map(fn (OrderLine $line): array => [
|
||||
'name' => $line->offer_name,
|
||||
'price_cents' => (int) $line->price_cents,
|
||||
'discount_cents' => (int) $line->discount_cents,
|
||||
])->values()->all(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Filament\Support\CatalogLabels;
|
||||
|
||||
/**
|
||||
* Kaufbare Lizenzoptionen einer Produktseite aus dem veröffentlichten Katalog: aktive Angebotsfassungen mit Preis,
|
||||
* Eignung, Laufzeit, Umfang und Nutzungsrechten. Die Seite selbst (Titel, Beschreibung, Struktur) kommt aus der
|
||||
* zur Anzeige freigegebenen Komposition; hier entsteht kein zweiter Text.
|
||||
*/
|
||||
class ProductOptions
|
||||
{
|
||||
public function __construct(private readonly OfferService $offers) {}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forComposition(Composition $composition): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (Offer::query()->where('composition_id', $composition->id)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version !== null) {
|
||||
$options[] = $this->describe($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kaufbare Optionen der eigenen Produktseite eines Pakets: Angebote mit eigener Paketseite, deren aktive Fassung
|
||||
* dieses Paket verkauft.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forBundle(Bundle $bundle): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version !== null && $this->bundleOf($version)?->id === $bundle->id) {
|
||||
$options[] = $this->describe($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Paket, das die Fassung unmittelbar verkauft (erste Paketposition), sonst null.
|
||||
*/
|
||||
public function bundleOf(OfferVersion $version): ?Bundle
|
||||
{
|
||||
$version->loadMissing('lines.bundleVersion.bundle');
|
||||
|
||||
return $version->lines->first(fn ($line): bool => $line->bundleVersion !== null)?->bundleVersion?->bundle;
|
||||
}
|
||||
|
||||
/** Gruppenschlüssel der Alternativen: Produktseite eines Programms oder eigene Paketseite. */
|
||||
public function groupKey(Offer $offer): ?string
|
||||
{
|
||||
if ($offer->composition_id !== null) {
|
||||
return 'c:'.$offer->composition_id;
|
||||
}
|
||||
|
||||
if ($offer->standalone_bundle) {
|
||||
$version = $this->offers->purchasableVersion($offer) ?? $offer->versions()->orderByDesc('number')->first();
|
||||
$bundle = $version === null ? null : $this->bundleOf($version);
|
||||
|
||||
return $bundle === null ? null : 'b:'.$bundle->id;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Adresse der Produktseite, auf der die Option angeboten wird, sonst null. */
|
||||
public function pageUrl(Offer $offer): ?string
|
||||
{
|
||||
if ($offer->composition_id !== null) {
|
||||
return route('public.program', $offer->composition_id);
|
||||
}
|
||||
|
||||
$key = $this->groupKey($offer);
|
||||
|
||||
return $key !== null && str_starts_with($key, 'b:') ? route('public.package', (int) substr($key, 2)) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pakete mit eigener Produktseite und kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int}>
|
||||
*/
|
||||
public function bundleSummaries(): array
|
||||
{
|
||||
$summary = [];
|
||||
|
||||
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
$bundle = $version === null ? null : $this->bundleOf($version);
|
||||
|
||||
if ($bundle === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = $summary[$bundle->id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0];
|
||||
$summary[$bundle->id] = [
|
||||
'from_cents' => min($current['from_cents'], (int) $version->price_cents),
|
||||
'count' => $current['count'] + 1,
|
||||
];
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Der tatsächliche Umfang einer Paketseite: die Artikel aller Optionen ohne Doppelte, in der Reihenfolge der
|
||||
* Optionen, mit Name und Kurzbeschreibung aus der Redaktion.
|
||||
*
|
||||
* @param list<array<string, mixed>> $options
|
||||
* @return list<array{title: string, teaser: string}>
|
||||
*/
|
||||
public function bundleContents(array $options): array
|
||||
{
|
||||
$contents = [];
|
||||
|
||||
foreach ($options as $option) {
|
||||
$option['version']->loadMissing('resolvedScopes.article');
|
||||
|
||||
foreach ($option['version']->resolvedScopes as $item) {
|
||||
$article = $item->article;
|
||||
|
||||
if ($article === null || isset($contents[$article->id])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$profile = app(EditorialProfileReader::class)->read($article, 'detail');
|
||||
$contents[$article->id] = [
|
||||
'title' => $this->articleTitle($article),
|
||||
'teaser' => trim((string) ($profile->value('teaser') ?? '')),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($contents);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int}>
|
||||
*/
|
||||
public function summaries(): array
|
||||
{
|
||||
$summary = [];
|
||||
|
||||
foreach (Offer::query()->whereNotNull('composition_id')->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = $summary[$offer->composition_id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0];
|
||||
$summary[$offer->composition_id] = [
|
||||
'from_cents' => min($current['from_cents'], (int) $version->price_cents),
|
||||
'count' => $current['count'] + 1,
|
||||
];
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function describe(Offer $offer, OfferVersion $version): array
|
||||
{
|
||||
$version->loadMissing('resolvedScopes.article', 'resolvedScopes.rights');
|
||||
$scope = [];
|
||||
|
||||
foreach ($version->resolvedScopes as $item) {
|
||||
$faehigkeiten = CatalogLabels::faehigkeiten($item->rights?->capabilities);
|
||||
$scope[] = [
|
||||
'article' => $this->articleTitle($item->article),
|
||||
'purpose' => CatalogLabels::zweck($item->rights?->purpose),
|
||||
'rights' => $faehigkeiten,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'offer' => $offer,
|
||||
'version' => $version,
|
||||
'name' => $offer->optionName(),
|
||||
'price_cents' => (int) $version->price_cents,
|
||||
'price' => Money::format((int) $version->price_cents),
|
||||
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'term' => self::termLabel($version),
|
||||
'licence' => LicenceScope::label($version->licence_scope, $version->trainer_count),
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
'licence_note' => LicenceScope::explanation($version->licence_scope, $version->trainer_count),
|
||||
'scope' => $scope,
|
||||
];
|
||||
}
|
||||
|
||||
public static function termLabel(OfferVersion $version): string
|
||||
{
|
||||
return self::termRuleLabel($version->term_rule);
|
||||
}
|
||||
|
||||
/** Laufzeitregel aus der Angebotsfassung oder aus den Bedingungen eines Erwerbs (gleiche Schlüssel). */
|
||||
public static function termRuleLabel(?string $rule): string
|
||||
{
|
||||
return match ((string) $rule) {
|
||||
'dauerhaft' => 'Dauerhaft nutzbar',
|
||||
'befristet' => 'Befristet',
|
||||
'solange_angebot_aktiv' => 'Solange das Angebot aktiv ist',
|
||||
'periodisch' => 'Laufend, periodisch',
|
||||
default => (string) $rule,
|
||||
};
|
||||
}
|
||||
|
||||
public function articleTitle(?LicenseArticle $article): string
|
||||
{
|
||||
if ($article === null) {
|
||||
return '–';
|
||||
}
|
||||
|
||||
return $this->articleName($article) ?: (string) $article->code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Name wie in der Redaktion: eigener Name, sonst der Name des Inhalts (Anzeigename, Arbeitstitel oder
|
||||
* Bezeichnung), sonst der eigene Arbeitstitel; leer, wenn nichts davon vorhanden ist.
|
||||
*/
|
||||
public function articleName(LicenseArticle $article): string
|
||||
{
|
||||
$profile = app(EditorialProfileReader::class)->read($article, 'detail');
|
||||
$source = $profile->source;
|
||||
$candidates = [
|
||||
$profile->value('display_title'),
|
||||
$article->working_title,
|
||||
$source?->getAttribute('working_title'),
|
||||
$source?->getAttribute('designation'),
|
||||
];
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
if (filled($candidate)) {
|
||||
return trim((string) $candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Receipt;
|
||||
|
||||
use App\Domain\Commerce\LedgerEntry;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\PaymentJournal;
|
||||
use App\Domain\Identity\BillingAddress;
|
||||
|
||||
/**
|
||||
* Zahlungs- oder Erstattungsbeleg zu einer Buchung des Zahlungsjournals als PDF. Gebaut wird ausschließlich aus den
|
||||
* bei der Buchung festgehaltenen Angaben (Zahler, Positionen, Beträge, Zeitpunkt, Beleg beim Anbieter), nie aus dem
|
||||
* heutigen Profil oder der heutigen Bestellung: Spätere Änderungen der Adresse ändern den Beleg nicht, und jeder Abruf
|
||||
* liefert dieselben Bytes. Der Beleg bestätigt die Zahlung. Er enthält weder Rechnungsnummer noch Steuerangaben; ob eine
|
||||
* Rechnung zu stellen ist, ist rechtlich noch nicht geklärt (OPEN-06). Aussteller und Zusatzhinweis kommen aus
|
||||
* `config('shop.receipt')` und werden nur gedruckt, wenn sie gepflegt sind. Zu nachgetragenen Buchungen (abgeleitetes
|
||||
* Datum) gibt es keinen Beleg.
|
||||
*/
|
||||
final class PaymentReceipt
|
||||
{
|
||||
private const LEFT = 50;
|
||||
|
||||
private const RIGHT = 545;
|
||||
|
||||
public static function available(LedgerEntry $entry): bool
|
||||
{
|
||||
return ! $entry->derived;
|
||||
}
|
||||
|
||||
public static function filename(LedgerEntry $entry): string
|
||||
{
|
||||
return ($entry->isRefund() ? 'Erstattungsbeleg' : 'Zahlungsbeleg').'-Bestellung-'.$entry->order_id.'-Buchung-'.$entry->id.'.pdf';
|
||||
}
|
||||
|
||||
public static function render(LedgerEntry $entry): string
|
||||
{
|
||||
$refund = $entry->isRefund();
|
||||
$payer = (array) $entry->payer;
|
||||
$billing = (array) ($payer['billing'] ?? []);
|
||||
$snapshot = (array) $entry->order_snapshot;
|
||||
$money = fn (int $cents): string => Money::format($cents);
|
||||
$when = PaymentJournal::local($entry->occurred_at);
|
||||
$title = $refund ? 'Erstattungsbeleg' : 'Zahlungsbeleg';
|
||||
$pdf = new PdfDocument;
|
||||
$pdf->addPage();
|
||||
$y = 790.0;
|
||||
|
||||
$pdf->text(self::LEFT, $y, $title, 22, true);
|
||||
$issuer = array_values(array_filter(array_map('trim', explode('|', (string) config('shop.receipt.issuer')))));
|
||||
$yIssuer = $y + 4;
|
||||
|
||||
foreach ($issuer as $i => $line) {
|
||||
$pdf->textRight(self::RIGHT, $yIssuer - $i * 12, $line, 9, $i === 0);
|
||||
}
|
||||
|
||||
$y = min($y - 26, $yIssuer - 12 * count($issuer) - 8);
|
||||
|
||||
if (! $entry->live) {
|
||||
$pdf->text(self::LEFT, $y, 'TESTZAHLUNG - kein Umsatz, kein Beleg für eine echte Zahlung', 10, true);
|
||||
$y -= 16;
|
||||
}
|
||||
|
||||
$y -= 6;
|
||||
$meta = [
|
||||
['Bestellung', (string) $entry->order_id],
|
||||
['Buchung', (string) $entry->id],
|
||||
[$refund ? 'Rückzahlung am' : 'Zahlung am', $when->format('d.m.Y').(PaymentJournal::hasTime($entry) ? ', '.$when->format('H:i').' Uhr' : '')],
|
||||
['Zahlungsweg', PaymentJournal::providerLabel($entry->provider)],
|
||||
['Referenz', (string) $entry->provider_reference],
|
||||
];
|
||||
|
||||
foreach ($meta as [$label, $value]) {
|
||||
$pdf->text(self::LEFT, $y, $label, 9);
|
||||
|
||||
foreach (PdfDocument::wrap($value, 330, 10) as $i => $part) {
|
||||
$pdf->text(160, $y - $i * 12, $part, 10);
|
||||
}
|
||||
|
||||
$y -= 14 * max(1, count(PdfDocument::wrap($value, 330, 10)));
|
||||
}
|
||||
|
||||
$y -= 10;
|
||||
$pdf->text(self::LEFT, $y, $refund ? 'Erstattung an' : 'Zahler', 9);
|
||||
$recipient = $billing !== [] ? array_values(array_filter([
|
||||
$billing['recipient'] ?? null,
|
||||
$billing['line2'] ?? null,
|
||||
$billing['street'] ?? null,
|
||||
trim(($billing['postal_code'] ?? '').' '.($billing['city'] ?? '')),
|
||||
($billing['country'] ?? 'DE') !== 'DE' ? (BillingAddress::COUNTRIES[$billing['country']] ?? $billing['country']) : null,
|
||||
])) : array_values(array_filter([$payer['holder'] ?? null, 'Keine Rechnungsadresse hinterlegt']));
|
||||
|
||||
foreach ($recipient as $i => $line) {
|
||||
$pdf->text(160, $y - $i * 13, (string) $line, 10, $i === 0);
|
||||
}
|
||||
|
||||
$y -= 13 * count($recipient);
|
||||
|
||||
if (filled($payer['buyer'] ?? null) && ($payer['buyer'] ?? '') !== ($billing['recipient'] ?? $payer['holder'] ?? '')) {
|
||||
$pdf->text(160, $y, 'Bestellt von '.$payer['buyer'], 9);
|
||||
$y -= 13;
|
||||
}
|
||||
|
||||
$y -= 16;
|
||||
$pdf->line(self::LEFT, $y + 12, self::RIGHT, $y + 12, 0.8);
|
||||
$pdf->text(self::LEFT, $y, 'Position', 9, true);
|
||||
$pdf->textRight(400, $y, 'Preis', 9, true);
|
||||
$pdf->textRight(472, $y, 'Rabatt', 9, true);
|
||||
$pdf->textRight(self::RIGHT, $y, 'Betrag', 9, true);
|
||||
$y -= 6;
|
||||
$pdf->line(self::LEFT, $y, self::RIGHT, $y, 0.4);
|
||||
$y -= 14;
|
||||
|
||||
foreach ((array) ($snapshot['lines'] ?? []) as $line) {
|
||||
$lines = PdfDocument::wrap((string) ($line['name'] ?? 'Angebot'), 270, 10);
|
||||
|
||||
if ($y - 13 * count($lines) < 140) {
|
||||
$pdf->addPage();
|
||||
$y = 790.0;
|
||||
}
|
||||
|
||||
$price = (int) ($line['price_cents'] ?? 0);
|
||||
$discount = (int) ($line['discount_cents'] ?? 0);
|
||||
|
||||
foreach ($lines as $i => $part) {
|
||||
$pdf->text(self::LEFT, $y - $i * 13, $part, 10);
|
||||
}
|
||||
|
||||
$pdf->textRight(400, $y, $money($price), 10);
|
||||
$pdf->textRight(472, $y, $discount > 0 ? '-'.$money($discount) : '', 10);
|
||||
$pdf->textRight(self::RIGHT, $y, $money($price - $discount), 10);
|
||||
$y -= 13 * count($lines) + 4;
|
||||
}
|
||||
|
||||
$y -= 6;
|
||||
$pdf->line(self::LEFT, $y + 10, self::RIGHT, $y + 10, 0.4);
|
||||
$y -= 6;
|
||||
|
||||
if ((int) ($snapshot['discount_cents'] ?? 0) > 0) {
|
||||
$pdf->text(300, $y, 'Zwischensumme', 10);
|
||||
$pdf->textRight(self::RIGHT, $y, $money((int) ($snapshot['subtotal_cents'] ?? 0)), 10);
|
||||
$y -= 14;
|
||||
$pdf->text(300, $y, 'Rabatt'.(filled($snapshot['discount_code'] ?? null) ? ' (Code '.$snapshot['discount_code'].')' : ''), 10);
|
||||
$pdf->textRight(self::RIGHT, $y, '-'.$money((int) $snapshot['discount_cents']), 10);
|
||||
$y -= 14;
|
||||
}
|
||||
|
||||
$pdf->text(300, $y, $refund ? 'Erstatteter Betrag' : 'Gezahlter Betrag', 11, true);
|
||||
$pdf->textRight(self::RIGHT, $y, $money(abs($entry->amount_cents)), 11, true);
|
||||
$y -= 26;
|
||||
|
||||
$notes = [
|
||||
$refund
|
||||
? 'Dieser Beleg bestätigt die Rückzahlung zur genannten Bestellung. Die Berechtigungen aus dieser Bestellung sind widerrufen.'
|
||||
: 'Dieser Beleg bestätigt die Zahlung zur genannten Bestellung.',
|
||||
'Er enthält keine Rechnungsnummer und keine steuerlichen Angaben und wurde aus den bei der Zahlung festgehaltenen Angaben erstellt.',
|
||||
];
|
||||
|
||||
if (filled(config('shop.receipt.note'))) {
|
||||
$notes[] = (string) config('shop.receipt.note');
|
||||
}
|
||||
|
||||
foreach ($notes as $note) {
|
||||
foreach (PdfDocument::wrap($note, self::RIGHT - self::LEFT, 9) as $part) {
|
||||
$pdf->text(self::LEFT, $y, $part, 9);
|
||||
$y -= 12;
|
||||
}
|
||||
|
||||
$y -= 3;
|
||||
}
|
||||
|
||||
return $pdf->output($title.' Bestellung '.$entry->order_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Receipt;
|
||||
|
||||
/**
|
||||
* Minimaler PDF-Schreiber für einseitige bis wenige Seiten Text (DIN A4, Standardschriften Helvetica, Kodierung
|
||||
* WinAnsi). Absichtlich ohne Abhängigkeit: Ein Zahlungsbeleg ist ein Text mit Linien. Der Inhalt ist unkomprimiert und
|
||||
* enthält keinen Zeitstempel, damit dasselbe Dokument bei jedem Abruf byte-gleich ist und Tests den Text prüfen können.
|
||||
* Zeichen außerhalb von Windows-1252 werden durch „?“ ersetzt (das Minuszeichen U+2212 durch „-“).
|
||||
*/
|
||||
final class PdfDocument
|
||||
{
|
||||
public const WIDTH = 595;
|
||||
|
||||
public const HEIGHT = 842;
|
||||
|
||||
/** @var list<string> */
|
||||
private array $pages = [];
|
||||
|
||||
public function addPage(): void
|
||||
{
|
||||
$this->pages[] = '';
|
||||
}
|
||||
|
||||
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false): void
|
||||
{
|
||||
$this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $bold ? 'F2' : 'F1', $this->n($size), $this->n($x), $this->n($y), self::escape($text)));
|
||||
}
|
||||
|
||||
public function textRight(float $xRight, float $y, string $text, float $size = 10, bool $bold = false): void
|
||||
{
|
||||
$this->text($xRight - self::width($text, $size, $bold), $y, $text, $size, $bold);
|
||||
}
|
||||
|
||||
public function line(float $x1, float $y1, float $x2, float $y2, float $width = 0.5): void
|
||||
{
|
||||
$this->append(sprintf("%s w %s %s m %s %s l S\n", $this->n($width), $this->n($x1), $this->n($y1), $this->n($x2), $this->n($y2)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilenumbruch nach Wörtern. Die Breite ist eine bewusst großzügige Schätzung der Helvetica-Breiten, damit nichts
|
||||
* über den Rand läuft; ein einzelnes zu langes Wort wird hart getrennt.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function wrap(string $text, float $maxWidth, float $size = 10, bool $bold = false): array
|
||||
{
|
||||
$lines = [];
|
||||
|
||||
foreach (preg_split('/\R/u', trim($text)) ?: [''] as $paragraph) {
|
||||
$current = '';
|
||||
|
||||
foreach (preg_split('/\s+/u', trim($paragraph)) ?: [] as $word) {
|
||||
while (mb_strlen($word) > 1 && self::width($word, $size, $bold) > $maxWidth) {
|
||||
$cut = mb_strlen($word) - 1;
|
||||
|
||||
while ($cut > 1 && self::width(mb_substr($word, 0, $cut), $size, $bold) > $maxWidth) {
|
||||
$cut--;
|
||||
}
|
||||
|
||||
if ($current !== '') {
|
||||
$lines[] = $current;
|
||||
$current = '';
|
||||
}
|
||||
|
||||
$lines[] = mb_substr($word, 0, $cut);
|
||||
$word = mb_substr($word, $cut);
|
||||
}
|
||||
|
||||
$candidate = $current === '' ? $word : $current.' '.$word;
|
||||
|
||||
if ($current !== '' && self::width($candidate, $size, $bold) > $maxWidth) {
|
||||
$lines[] = $current;
|
||||
$current = $word;
|
||||
} else {
|
||||
$current = $candidate;
|
||||
}
|
||||
}
|
||||
|
||||
$lines[] = $current;
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/** Geschätzte Textbreite in Punkt (Helvetica; Ziffern und Währung exakt, Buchstaben großzügig). */
|
||||
public static function width(string $text, float $size = 10, bool $bold = false): float
|
||||
{
|
||||
$units = 0.0;
|
||||
|
||||
foreach (mb_str_split($text) as $char) {
|
||||
$width = match (true) {
|
||||
$char === ' ', $char === ',', $char === '.', $char === ':', $char === ';', $char === "'", $char === '|', $char === 'i', $char === 'l', $char === 'I', $char === 'j', $char === 't', $char === 'f' => 0.3,
|
||||
$char === '-', $char === '(', $char === ')', $char === '/', $char === 'r' => 0.35,
|
||||
ctype_digit($char), $char === '€' => 0.556,
|
||||
mb_strtoupper($char) === $char && $char !== mb_strtolower($char) => 0.75,
|
||||
$char === 'm', $char === 'w', $char === 'M', $char === 'W' => 0.85,
|
||||
default => 0.57,
|
||||
};
|
||||
// Fette Ziffern, Währung und Satzzeichen sind in Helvetica so breit wie normale; nur Buchstaben werden breiter.
|
||||
$units += $bold && ctype_alpha($char) ? $width * 1.08 : $width;
|
||||
}
|
||||
|
||||
return $units * $size;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $title Nur ASCII (Dokumenttitel)
|
||||
*/
|
||||
public function output(string $title, ?string $keywords = null): string
|
||||
{
|
||||
$pages = $this->pages === [] ? [''] : $this->pages;
|
||||
$objects = [];
|
||||
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
|
||||
$kids = [];
|
||||
$next = 6;
|
||||
|
||||
foreach ($pages as $stream) {
|
||||
$kids[] = $next.' 0 R';
|
||||
$objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents '.($next + 1).' 0 R >>';
|
||||
$objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream';
|
||||
$next += 2;
|
||||
}
|
||||
|
||||
$objects[2] = '<< /Type /Pages /Kids ['.implode(' ', $kids).'] /Count '.count($pages).' >>';
|
||||
$objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
|
||||
$objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
|
||||
$ascii = fn (string $value): string => (string) preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $value));
|
||||
$objects[5] = '<< /Title ('.$ascii($title).')'.($keywords === null ? '' : ' /Keywords ('.$ascii($keywords).')').' /Producer (Lara und Felix) >>';
|
||||
ksort($objects);
|
||||
|
||||
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
|
||||
$offsets = [];
|
||||
|
||||
foreach ($objects as $number => $body) {
|
||||
$offsets[$number] = strlen($pdf);
|
||||
$pdf .= $number." 0 obj\n".$body."\nendobj\n";
|
||||
}
|
||||
|
||||
$xref = strlen($pdf);
|
||||
$pdf .= 'xref'."\n0 ".(count($objects) + 1)."\n0000000000 65535 f \n";
|
||||
|
||||
foreach ($offsets as $offset) {
|
||||
$pdf .= sprintf("%010d 00000 n \n", $offset);
|
||||
}
|
||||
|
||||
return $pdf.'trailer'."\n<< /Size ".(count($objects) + 1).' /Root 1 0 R /Info 5 0 R >>'."\nstartxref\n".$xref."\n%%EOF\n";
|
||||
}
|
||||
|
||||
private function append(string $operators): void
|
||||
{
|
||||
if ($this->pages === []) {
|
||||
$this->addPage();
|
||||
}
|
||||
|
||||
$this->pages[array_key_last($this->pages)] .= $operators;
|
||||
}
|
||||
|
||||
private function n(float $value): string
|
||||
{
|
||||
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.') ?: '0';
|
||||
}
|
||||
|
||||
/** Windows-1252, geklammert für PDF-Zeichenketten. */
|
||||
private static function escape(string $text): string
|
||||
{
|
||||
$text = strtr($text, ["\u{2212}" => '-', "\u{2019}" => "'", "\u{2026}" => '...', "\u{00A0}" => ' ', "\u{202F}" => ' ']);
|
||||
$text = (string) preg_replace('/[\x00-\x08\x0B-\x1F\x7F]/u', '', $text);
|
||||
$encoded = mb_convert_encoding($text, 'Windows-1252', 'UTF-8');
|
||||
|
||||
return str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $encoded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Cms\Page;
|
||||
|
||||
/**
|
||||
* Pflichtangaben und Zustimmungen im Bestellablauf (Verkaufsstart Deutschland, PAY-005, PAY-009).
|
||||
*
|
||||
* Die finalen Rechtstexte (AGB, Lizenzbedingungen, Widerrufsbelehrung, Impressum, Datenschutz) liegen als Seiten im
|
||||
* CMS und werden hier nur verlinkt. Der Wortlaut der Zustimmungen unten ist ein ENTWURF zur Prüfung durch die
|
||||
* Rechtsberatung. Er ist nicht rechtlich freigegeben; `VERSION` hält fest, welcher Wortlaut galt, damit die Zustimmung
|
||||
* je Bestellung nachvollziehbar bleibt.
|
||||
*/
|
||||
final class SalesTerms
|
||||
{
|
||||
public const VERSION = '2026-11-24-entwurf';
|
||||
|
||||
/** Schaltfläche zum verbindlichen Abschluss (Button-Lösung, § 312j Abs. 3 BGB). */
|
||||
public const ORDER_BUTTON = 'Zahlungspflichtig bestellen';
|
||||
|
||||
public const ORDER_BUTTON_INVOICE = 'Zahlungspflichtig auf Rechnung bestellen';
|
||||
|
||||
/**
|
||||
* Seiten der Rechtstexte: Schlüssel => Bezeichnung und mögliche Pfade im CMS (erste veröffentlichte Seite gilt).
|
||||
*
|
||||
* @return array<string, array{label: string, paths: list<string>, required: bool}>
|
||||
*/
|
||||
public static function pages(): array
|
||||
{
|
||||
return [
|
||||
'agb' => ['label' => 'Allgemeine Geschäftsbedingungen', 'paths' => ['/agb'], 'required' => true],
|
||||
'lizenz' => ['label' => 'Lizenzbedingungen', 'paths' => ['/lizenzbedingungen', '/lizenz'], 'required' => true],
|
||||
'widerruf' => ['label' => 'Widerrufsbelehrung', 'paths' => ['/widerruf', '/widerrufsbelehrung'], 'required' => true],
|
||||
'impressum' => ['label' => 'Impressum', 'paths' => ['/impressum'], 'required' => true],
|
||||
'datenschutz' => ['label' => 'Datenschutzerklärung', 'paths' => ['/datenschutz'], 'required' => true],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Veröffentlichte Seite des Rechtstextes oder null.
|
||||
*/
|
||||
public static function page(string $key): ?Page
|
||||
{
|
||||
$definition = self::pages()[$key] ?? null;
|
||||
|
||||
if ($definition === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Page::query()
|
||||
->whereIn('path', $definition['paths'])
|
||||
->whereNotNull('published_revision_id')
|
||||
->orderBy('id')
|
||||
->first();
|
||||
}
|
||||
|
||||
public static function url(string $key): ?string
|
||||
{
|
||||
return self::page($key)?->publicUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fehlende oder unveröffentlichte Rechtstexte (Schlüssel => Bezeichnung).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function missingPages(): array
|
||||
{
|
||||
$missing = [];
|
||||
|
||||
foreach (self::pages() as $key => $definition) {
|
||||
if ($definition['required'] && self::page($key) === null) {
|
||||
$missing[$key] = $definition['label'];
|
||||
}
|
||||
}
|
||||
|
||||
return $missing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustimmungen im Checkout: Schlüssel => Wortlaut (ENTWURF).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function consents(): array
|
||||
{
|
||||
return [
|
||||
'agb' => 'Ich habe die Allgemeinen Geschäftsbedingungen und die Lizenzbedingungen gelesen und stimme ihnen zu.',
|
||||
'sofort' => 'Ich verlange ausdrücklich, dass mit der Ausführung des Vertrags vor Ablauf der Widerrufsfrist begonnen wird und die digitalen Inhalte sofort nach Zahlungseingang bereitgestellt werden. Mir ist bekannt, dass ich mein Widerrufsrecht verliere, sobald die Ausführung begonnen hat.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die Zustimmungen und liefert den Nachweis für die Bestellung (Wortlaut, Fassung, Seiten, Zeit).
|
||||
*
|
||||
* @param array<string, mixed> $accepted Schlüssel => angekreuzt
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function proof(array $accepted): array
|
||||
{
|
||||
$texts = [];
|
||||
|
||||
foreach (self::consents() as $key => $wording) {
|
||||
if (empty($accepted[$key])) {
|
||||
throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.');
|
||||
}
|
||||
|
||||
$texts[$key] = $wording;
|
||||
}
|
||||
|
||||
$pages = [];
|
||||
|
||||
foreach (array_keys(self::pages()) as $key) {
|
||||
$page = self::page($key);
|
||||
$pages[$key] = $page === null ? null : ['path' => $page->path, 'revision_id' => $page->published_revision_id];
|
||||
}
|
||||
|
||||
return [
|
||||
'version' => self::VERSION,
|
||||
'consents' => $texts,
|
||||
'pages' => $pages,
|
||||
'recorded_at' => now()->toIso8601String(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
/**
|
||||
* Wann der Shop (Warenkorb, Kasse, Kopflink) aktiv ist.
|
||||
*
|
||||
* Test und Sandbox: nicht in Produktion, Zahlungstreiber „test“ oder „stripe“ (Testschlüssel).
|
||||
* Produktion: nur mit der ausdrücklichen Produktivfreigabe (`SHOP_LIVE_RELEASE`, Entscheidung von Lars), dem
|
||||
* Zahlungstreiber „stripe“ mit Live-Schlüssel und veröffentlichten Rechtstexten. Fehlt eines davon, bleibt der Shop in
|
||||
* Produktion abgeschaltet. Die Freigabe ist standardmäßig aus.
|
||||
*/
|
||||
final class Shop
|
||||
{
|
||||
public static function driver(): string
|
||||
{
|
||||
return (string) config('services.payment.driver');
|
||||
}
|
||||
|
||||
/** Produktivbetrieb ist freigegeben und vollständig vorbereitet (Freigabe, Live-Schlüssel, Rechtstexte). */
|
||||
public static function live(): bool
|
||||
{
|
||||
return app()->isProduction()
|
||||
&& config('shop.live_release') === true
|
||||
&& self::driver() === 'stripe'
|
||||
&& self::liveKey()
|
||||
&& SalesTerms::missingPages() === [];
|
||||
}
|
||||
|
||||
public static function enabled(): bool
|
||||
{
|
||||
if (app()->isProduction()) {
|
||||
return self::live();
|
||||
}
|
||||
|
||||
return in_array(self::driver(), ['test', 'stripe'], true);
|
||||
}
|
||||
|
||||
/** Stripe-Kasse: im Test nur mit Testschlüsseln, in Produktion nur nach der Produktivfreigabe. */
|
||||
public static function stripe(): bool
|
||||
{
|
||||
if (app()->isProduction()) {
|
||||
return self::live();
|
||||
}
|
||||
|
||||
return self::driver() === 'stripe';
|
||||
}
|
||||
|
||||
/** Kauf auf Rechnung für Organisationen (manuelle Rechnung, Zahlungseingang durch den Betreiber). */
|
||||
public static function invoice(): bool
|
||||
{
|
||||
return self::enabled() && (bool) config('shop.invoice', true);
|
||||
}
|
||||
|
||||
private static function liveKey(): bool
|
||||
{
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
|
||||
return str_starts_with($secret, 'sk_live_') || str_starts_with($secret, 'rk_live_');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
|
||||
/**
|
||||
* Preis oder bindende Bedingungen haben sich nach Anzeige der Bestellübersicht geändert. Es entsteht keine
|
||||
* Bestellung; der Käufer sieht zuerst die aktualisierte Übersicht (FACH-59).
|
||||
*/
|
||||
class StaleOverview extends DomainRuleException {}
|
||||
@@ -0,0 +1,257 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Stripe;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Stripe-Kasse (Checkout Session). Außerhalb der Produktion nur mit Testschlüsseln; ein Live-Schlüssel wird dort
|
||||
* abgewiesen. In Produktion nur nach der Produktivfreigabe (Shop::live) und nur mit Live-Schlüssel; in jedem anderen
|
||||
* Fall wird abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten berühren diese Anwendung
|
||||
* nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook). Der Betrag je Position ist der
|
||||
* Preis nach Rabatt, damit die Summe bei Stripe genau dem gespeicherten Zahlbetrag der Bestellung entspricht.
|
||||
*/
|
||||
class StripeGateway
|
||||
{
|
||||
/**
|
||||
* Legt für die Bestellung eine Checkout Session an oder liefert die noch offene wieder.
|
||||
*
|
||||
* @return array{id: string, url: string}
|
||||
*/
|
||||
public function checkoutFor(Order $order): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$order->loadMissing('lines', 'user');
|
||||
$taxRate = $this->taxRate();
|
||||
|
||||
if ($order->status !== 'offen') {
|
||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
||||
}
|
||||
|
||||
if ($order->payment_method === 'rechnung') {
|
||||
throw new DomainRuleException('Diese Bestellung wird auf Rechnung bezahlt, nicht bei Stripe.');
|
||||
}
|
||||
|
||||
$open = $this->reusableSession($order);
|
||||
|
||||
if ($open !== null) {
|
||||
return $open;
|
||||
}
|
||||
|
||||
$attempt = $order->payments()->where('provider', 'stripe')->count() + 1;
|
||||
$params = [
|
||||
'mode' => 'payment',
|
||||
'client_reference_id' => (string) $order->id,
|
||||
'customer_email' => $order->user->email,
|
||||
'locale' => 'de',
|
||||
'success_url' => route('member.order', $order).'?zahlung=zurueck',
|
||||
'cancel_url' => route('member.order', $order).'?zahlung=abbruch',
|
||||
'metadata' => ['order_id' => (string) $order->id],
|
||||
'payment_intent_data' => ['metadata' => ['order_id' => (string) $order->id]],
|
||||
];
|
||||
|
||||
foreach ($order->lines->values() as $index => $line) {
|
||||
$productData = ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'];
|
||||
|
||||
if ((int) $line->discount_cents > 0) {
|
||||
$productData['description'] = 'Listenpreis '.Money::format((int) $line->price_cents).', Rabatt '.Money::format((int) $line->discount_cents);
|
||||
}
|
||||
|
||||
$params['line_items'][$index] = [
|
||||
'quantity' => 1,
|
||||
'price_data' => [
|
||||
'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')),
|
||||
'unit_amount' => $line->payable(),
|
||||
'product_data' => $productData,
|
||||
],
|
||||
];
|
||||
|
||||
if ($taxRate !== null) {
|
||||
$params['line_items'][$index]['tax_rates'] = [$taxRate];
|
||||
}
|
||||
}
|
||||
|
||||
$response = $this->request()
|
||||
->withHeaders(['Idempotency-Key' => $this->idempotencyKey($order, $attempt, $params)])
|
||||
->post('/v1/checkout/sessions', $params);
|
||||
|
||||
$this->assertOk($response, 'angelegt');
|
||||
$id = (string) $response->json('id');
|
||||
$url = (string) $response->json('url');
|
||||
|
||||
if ($id === '' || $url === '') {
|
||||
throw new DomainRuleException('Stripe hat keine Kasse geliefert. Bitte versuche es später noch einmal.');
|
||||
}
|
||||
|
||||
$order->payments()->create(['provider' => 'stripe', 'status' => 'offen', 'provider_reference' => $id]);
|
||||
|
||||
return ['id' => $id, 'url' => $url];
|
||||
}
|
||||
|
||||
public function assertAllowed(): void
|
||||
{
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
|
||||
if ($secret === '') {
|
||||
throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.');
|
||||
}
|
||||
|
||||
if (app()->isProduction()) {
|
||||
if (! Shop::live()) {
|
||||
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) {
|
||||
throw new DomainRuleException('Außerhalb der Produktion erlaubt Stripe nur den Testmodus (Schlüssel sk_test_).');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vollerstattung der bezahlten Bestellung bei Stripe. Der Betrag ist der gespeicherte Zahlbetrag. Der
|
||||
* Idempotenzschlüssel verhindert eine doppelte Rückzahlung bei Wiederholung. Schlägt sie fehl, wird nichts
|
||||
* entzogen (Aufrufer: Checkout::refund). Geliefert werden Rückzahlungs-ID, Status (Stripe meldet unter Umständen
|
||||
* „pending“; er wird so festgehalten) und Zeitpunkt für das Zahlungsjournal.
|
||||
*
|
||||
* @return array{id: string, status: string, created: ?CarbonImmutable}
|
||||
*/
|
||||
public function refund(Order $order, Payment $payment, string $reason): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$intent = (string) $payment->provider_payment_ref;
|
||||
|
||||
if ($intent === '') {
|
||||
$session = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
|
||||
$this->assertOk($session, 'abgefragt');
|
||||
$intent = (string) $session->json('payment_intent');
|
||||
}
|
||||
|
||||
if ($intent === '') {
|
||||
throw new DomainRuleException('Zu dieser Zahlung gibt es bei Stripe keinen Zahlungsvorgang. Erstatte sie im Stripe-Dashboard und prüfe den Fall.');
|
||||
}
|
||||
|
||||
$response = $this->request()
|
||||
->withHeaders(['Idempotency-Key' => 'luf-refund-'.$order->id.'-'.$payment->id])
|
||||
->post('/v1/refunds', [
|
||||
'payment_intent' => $intent,
|
||||
'amount' => $order->payable(),
|
||||
'reason' => 'requested_by_customer',
|
||||
'metadata' => ['order_id' => (string) $order->id, 'grund' => mb_substr($reason, 0, 200)],
|
||||
]);
|
||||
|
||||
$this->assertOk($response, 'erstattet');
|
||||
$id = (string) $response->json('id');
|
||||
$status = (string) $response->json('status');
|
||||
|
||||
if ($id === '') {
|
||||
throw new DomainRuleException('Stripe hat keine Rückzahlung bestätigt. Prüfe den Fall im Stripe-Dashboard, bevor du es erneut versuchst.');
|
||||
}
|
||||
|
||||
if (in_array($status, ['failed', 'canceled'], true)) {
|
||||
throw new DomainRuleException('Stripe hat die Rückzahlung nicht ausgeführt (Status '.$status.'). Es wurde nichts verändert.');
|
||||
}
|
||||
|
||||
$payment->provider_payment_ref = $intent;
|
||||
$payment->save();
|
||||
|
||||
return [
|
||||
'id' => $id,
|
||||
'status' => $status !== '' ? $status : 'unbekannt',
|
||||
'created' => is_numeric($response->json('created')) ? CarbonImmutable::createFromTimestampUTC((int) $response->json('created')) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Stripe bindet einen Schlüssel an die Parameter der ersten Anfrage und lehnt dieselbe Kennung mit anderen
|
||||
* Parametern ab. Der Schlüssel enthält deshalb einen Fingerabdruck der Parameter und die Minute: Ein
|
||||
* doppelter Klick bleibt wirkungslos, eine geänderte Anfrage oder ein Neuversuch nach einer Korrektur nicht.
|
||||
*
|
||||
* @param array<string, mixed> $params
|
||||
*/
|
||||
private function idempotencyKey(Order $order, int $attempt, array $params): string
|
||||
{
|
||||
$fingerprint = substr(sha1(json_encode([$params, now()->format('YmdHi')], JSON_THROW_ON_ERROR)), 0, 12);
|
||||
|
||||
return 'luf-order-'.$order->id.'-'.$attempt.'-'.$fingerprint;
|
||||
}
|
||||
|
||||
/** Konfigurierter Steuersatz oder null; eine ungültige ID wird abgewiesen, statt geraten zu werden. */
|
||||
private function taxRate(): ?string
|
||||
{
|
||||
$id = trim((string) config('services.stripe.tax_rate'));
|
||||
|
||||
if ($id === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! preg_match('/^txr_[A-Za-z0-9]+$/', $id)) {
|
||||
throw new DomainRuleException('Die Steuersatz-ID für Stripe ist ungültig (erwartet txr_...).');
|
||||
}
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{id: string, url: string}|null
|
||||
*/
|
||||
private function reusableSession(Order $order): ?array
|
||||
{
|
||||
$payment = $order->payments()->where('provider', 'stripe')->where('status', 'offen')->latest('id')->first();
|
||||
|
||||
if ($payment === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
|
||||
} catch (ConnectionException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($response->successful() && $response->json('status') === 'open' && filled($response->json('url'))) {
|
||||
return ['id' => (string) $payment->provider_reference, 'url' => (string) $response->json('url')];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function request(): PendingRequest
|
||||
{
|
||||
return Http::baseUrl(rtrim((string) config('services.stripe.api_base'), '/'))
|
||||
->withToken((string) config('services.stripe.secret'))
|
||||
->asForm()
|
||||
->acceptJson()
|
||||
->timeout(15);
|
||||
}
|
||||
|
||||
private function assertOk(Response $response, string $what): void
|
||||
{
|
||||
if ($response->successful()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Statuscode, Fehlertyp, Code, betroffener Parameter und Begründung von Stripe, damit die Ursache lesbar ist.
|
||||
// Nie Schlüssel oder Kundendaten; die Begründung wird gekürzt.
|
||||
Log::warning('Stripe-Anfrage fehlgeschlagen', [
|
||||
'status' => $response->status(),
|
||||
'type' => $response->json('error.type'),
|
||||
'code' => $response->json('error.code'),
|
||||
'param' => $response->json('error.param'),
|
||||
'message' => mb_substr((string) $response->json('error.message'), 0, 300),
|
||||
]);
|
||||
|
||||
throw new DomainRuleException('Die Zahlung konnte bei Stripe nicht '.$what.' werden. Bitte versuche es später noch einmal.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Stripe;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
|
||||
/**
|
||||
* Prüft die Signatur einer Stripe-Meldung (Header „Stripe-Signature“: t=Zeit, v1=HMAC-SHA256 über „t.Nutzlast“).
|
||||
* Eine Meldung ohne gültige Signatur oder außerhalb der Zeittoleranz wird abgewiesen.
|
||||
*/
|
||||
class StripeSignature
|
||||
{
|
||||
public const TOLERANCE_SECONDS = 300;
|
||||
|
||||
public function verify(string $payload, ?string $header, ?int $now = null): void
|
||||
{
|
||||
$secret = (string) config('services.stripe.webhook_secret');
|
||||
|
||||
if ($secret === '') {
|
||||
throw new DomainRuleException('Das Webhook-Geheimnis ist nicht eingerichtet.');
|
||||
}
|
||||
|
||||
if ($header === null || trim($header) === '') {
|
||||
throw new DomainRuleException('Die Signatur fehlt.');
|
||||
}
|
||||
|
||||
$timestamp = null;
|
||||
$signatures = [];
|
||||
|
||||
foreach (explode(',', $header) as $part) {
|
||||
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
|
||||
|
||||
if ($key === 't') {
|
||||
$timestamp = ctype_digit($value) ? (int) $value : null;
|
||||
} elseif ($key === 'v1' && $value !== '') {
|
||||
$signatures[] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if ($timestamp === null || $signatures === []) {
|
||||
throw new DomainRuleException('Die Signatur ist unvollständig.');
|
||||
}
|
||||
|
||||
$expected = hash_hmac('sha256', $timestamp.'.'.$payload, $secret);
|
||||
$valid = false;
|
||||
|
||||
foreach ($signatures as $signature) {
|
||||
$valid = hash_equals($expected, $signature) || $valid;
|
||||
}
|
||||
|
||||
if (! $valid) {
|
||||
throw new DomainRuleException('Die Signatur stimmt nicht.');
|
||||
}
|
||||
|
||||
if (abs(($now ?? now()->getTimestamp()) - $timestamp) > self::TOLERANCE_SECONDS) {
|
||||
throw new DomainRuleException('Die Meldung ist zu alt.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Design;
|
||||
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
/**
|
||||
* Basiswerte der Größenskala des gemeinsamen Designsystems (ADR-44). Es sind bewusst nur zehn Werte; alles Weitere
|
||||
* (Überschrift 3, Einleitung, kleine Schrift, Abschnitts- und Widget-Abstände, Kopfzeile kompakt, Mindesthöhen der
|
||||
* Varianten …) leitet resources/css/tokens.css daraus ab. Die Ableitungsregeln stehen nur dort.
|
||||
*
|
||||
* Die Werte sind Pixel als ganze Zahl. Im Stylesheet werden sie in rem umgerechnet, damit die Textgröße des Browsers
|
||||
* wirkt. Die Standardwerte stehen ebenfalls in tokens.css (Block „Basiswerte“); ein Test hält beide gleich.
|
||||
* Trefferflächen (44 px) und die Untergrenze der Schrift auf Smartphones (16 px) sind nicht einstellbar.
|
||||
*/
|
||||
final class DesignScale
|
||||
{
|
||||
/**
|
||||
* @var array<string, array{label: string, default: int, min: int, max: int, unit: string, group: string, hint: string, effect: string}>
|
||||
*/
|
||||
public const PARAMETERS = [
|
||||
'body' => ['label' => 'Fließtext', 'default' => 17, 'min' => 16, 'max' => 20, 'unit' => 'px', 'group' => 'Schrift',
|
||||
'hint' => 'Schriftgröße auf Desktop; auf kleinen Bildschirmen etwa 1 px weniger, nie unter 16 px.',
|
||||
'effect' => 'Auch Einleitung, Überschrift 3, kleine Schrift und Schaltflächen folgen daraus.'],
|
||||
'h1' => ['label' => 'Überschrift 1', 'default' => 40, 'min' => 30, 'max' => 56, 'unit' => 'px', 'group' => 'Schrift',
|
||||
'hint' => 'Seitentitel auf Desktop; schrumpft auf Smartphones auf etwa 70 %.',
|
||||
'effect' => 'Muss mindestens 4 px größer sein als Überschrift 2.'],
|
||||
'h2' => ['label' => 'Überschrift 2', 'default' => 28, 'min' => 22, 'max' => 40, 'unit' => 'px', 'group' => 'Schrift',
|
||||
'hint' => 'Abschnittstitel auf Desktop; auch Titel in Bild und Text, Handlungsaufruf und breiten Karten.',
|
||||
'effect' => 'Muss mindestens 6 px größer sein als der Fließtext. Überschrift 3 bleibt darunter.'],
|
||||
'display' => ['label' => 'Display-Überschrift (Höchstwert)', 'default' => 52, 'min' => 36, 'max' => 80, 'unit' => 'px', 'group' => 'Schrift',
|
||||
'hint' => 'Größter Titel (Einstieg). Wächst mit der Breite des Platzes bis zu diesem Wert.',
|
||||
'effect' => 'Mindestens so groß wie Überschrift 1.'],
|
||||
'space' => ['label' => 'Basisabstand', 'default' => 8, 'min' => 6, 'max' => 12, 'unit' => 'px', 'group' => 'Abstände',
|
||||
'hint' => 'Grundmaß des Abstandsrasters (halber, einfacher, anderthalbfacher bis zwölffacher Wert).',
|
||||
'effect' => 'Alle Abstandsstufen der Komponenten und die Abstände zwischen Plätzen im Raster.'],
|
||||
'section' => ['label' => 'Abschnittsabstand (Desktop)', 'default' => 48, 'min' => 24, 'max' => 96, 'unit' => 'px', 'group' => 'Abstände',
|
||||
'hint' => 'Stufe „Normal“ auf Desktop. „Kompakt“ ist zwei Drittel davon, „Großzügig“ das Anderthalbfache.',
|
||||
'effect' => 'Auf Smartphones werden alle Stufen kleiner.'],
|
||||
'card_pad' => ['label' => 'Karten-Innenabstand', 'default' => 20, 'min' => 12, 'max' => 32, 'unit' => 'px', 'group' => 'Abstände',
|
||||
'hint' => 'Innenabstand von Karten auf Desktop.',
|
||||
'effect' => 'Große Flächen (Einstieg, Bild und Text, Handlungsaufruf) verwenden das Ein- bis Zweifache.'],
|
||||
'header' => ['label' => 'Höhe der Kopfzeile', 'default' => 80, 'min' => 56, 'max' => 112, 'unit' => 'px', 'group' => 'Rahmen',
|
||||
'hint' => 'Kopfzeile im Ausgangszustand auf Desktop. Beim Scrollen und auf Smartphones gilt 80 % davon.',
|
||||
'effect' => 'Die Anzeigegröße der Wortmarke folgt daraus; die Wortmarke selbst bleibt unverändert.'],
|
||||
'width' => ['label' => 'Maximale Inhaltsbreite', 'default' => 1312, 'min' => 960, 'max' => 1600, 'unit' => 'px', 'group' => 'Rahmen',
|
||||
'hint' => 'Breite des Standardrasters; Kopfzeile, Inhalt und Fußbereich fluchten hier. „Breit“ ist etwa 17 % mehr.',
|
||||
'effect' => 'Der Lesebereich (44 rem) ist davon unabhängig.'],
|
||||
'media' => ['label' => 'Bildhöhe in Bild und Text (Desktop)', 'default' => 320, 'min' => 200, 'max' => 480, 'unit' => 'px', 'group' => 'Medien',
|
||||
'hint' => 'Höhe des Bildes neben dem Text in der Variante „Standard“. Kompakt: 75 %, Großzügig: 130 %.',
|
||||
'effect' => 'Bestimmt zugleich die Mindesthöhe des Einstiegs (das 1,2-Fache; kompakt und großzügig wie bei Bild und Text).'],
|
||||
];
|
||||
|
||||
/** Gruppen in fester Reihenfolge. */
|
||||
public const GROUPS = ['Schrift', 'Abstände', 'Rahmen', 'Medien'];
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public static function defaults(): array
|
||||
{
|
||||
return array_map(static fn (array $p): int => $p['default'], self::PARAMETERS);
|
||||
}
|
||||
|
||||
/** Name der CSS-Variable, zum Beispiel card_pad → --ds-card-pad. */
|
||||
public static function variable(string $key): string
|
||||
{
|
||||
return '--ds-'.str_replace('_', '-', $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft vollständige Eingaben (Zeichenketten aus dem Formular oder Zahlen). Gibt Fehlermeldungen je Schlüssel zurück;
|
||||
* leer, wenn alles zulässig ist.
|
||||
*
|
||||
* @param array<string, mixed> $input
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function errors(array $input): array
|
||||
{
|
||||
$rules = [];
|
||||
$messages = [];
|
||||
$names = [];
|
||||
|
||||
foreach (self::PARAMETERS as $key => $p) {
|
||||
$rules[$key] = ['required', 'integer', 'min:'.$p['min'], 'max:'.$p['max']];
|
||||
$names[$key] = $p['label'];
|
||||
$messages["$key.required"] = $p['label'].': Bitte einen Wert eintragen.';
|
||||
$messages["$key.integer"] = $p['label'].': Bitte eine ganze Zahl in Pixeln eintragen.';
|
||||
$messages["$key.min"] = $p['label'].': Der Wert muss mindestens '.$p['min'].' px betragen.';
|
||||
$messages["$key.max"] = $p['label'].': Der Wert darf höchstens '.$p['max'].' px betragen.';
|
||||
}
|
||||
|
||||
$validator = Validator::make(array_intersect_key($input, self::PARAMETERS), $rules, $messages, $names);
|
||||
$errors = [];
|
||||
|
||||
foreach ($validator->errors()->messages() as $key => $list) {
|
||||
$errors[$key] = $list[0];
|
||||
}
|
||||
|
||||
if ($errors !== []) {
|
||||
return $errors;
|
||||
}
|
||||
|
||||
$v = array_map('intval', array_intersect_key($input, self::PARAMETERS));
|
||||
|
||||
if ($v['h2'] < $v['body'] + 6) {
|
||||
$errors['h2'] = 'Überschrift 2 muss mindestens 6 px größer sein als der Fließtext ('.($v['body'] + 6).' px).';
|
||||
}
|
||||
|
||||
if ($v['h1'] < $v['h2'] + 4) {
|
||||
$errors['h1'] = 'Überschrift 1 muss mindestens 4 px größer sein als Überschrift 2 ('.($v['h2'] + 4).' px).';
|
||||
}
|
||||
|
||||
if ($v['display'] < $v['h1']) {
|
||||
$errors['display'] = 'Die Display-Überschrift darf nicht kleiner sein als Überschrift 1 ('.$v['h1'].' px).';
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gespeicherte Werte lesen: nur bekannte Schlüssel, ganze Zahlen im zulässigen Bereich und stimmige Reihenfolge.
|
||||
* Alles andere (fehlende Schlüssel, Fremdes, beschädigte Daten) ergibt die Standardwerte, nie einen Fehler.
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public static function read(mixed $stored): array
|
||||
{
|
||||
if (! is_array($stored)) {
|
||||
return self::defaults();
|
||||
}
|
||||
|
||||
$merged = self::defaults();
|
||||
|
||||
foreach (array_keys(self::PARAMETERS) as $key) {
|
||||
if (array_key_exists($key, $stored) && (is_int($stored[$key]) || (is_string($stored[$key]) && ctype_digit($stored[$key])))) {
|
||||
$merged[$key] = (int) $stored[$key];
|
||||
}
|
||||
}
|
||||
|
||||
return self::errors($merged) === [] ? $merged : self::defaults();
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline-Stylesheet mit den abweichenden Basiswerten. Ausgegeben werden ausschließlich geprüfte ganze Zahlen zu
|
||||
* bekannten Schlüsseln. Ohne Abweichung leer: dann gelten die Standardwerte aus tokens.css.
|
||||
*
|
||||
* @param array<string, int> $values
|
||||
*/
|
||||
public static function css(array $values): string
|
||||
{
|
||||
$declarations = '';
|
||||
|
||||
foreach (self::PARAMETERS as $key => $p) {
|
||||
$value = $values[$key] ?? $p['default'];
|
||||
|
||||
if ($value !== $p['default'] && $value >= $p['min'] && $value <= $p['max']) {
|
||||
$declarations .= sprintf('%s:%d;', self::variable($key), $value);
|
||||
}
|
||||
}
|
||||
|
||||
return $declarations === '' ? '' : ':root{'.$declarations.'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Design;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\HtmlString;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Lesen und Schreiben der Größenskala (Schlüssel „design.scale“ in site_settings).
|
||||
*
|
||||
* Die öffentliche Ausgabe hängt nie am Erfolg dieser Klasse: Fehlt die Tabelle (Code vor Migration), ist die Datenbank
|
||||
* nicht erreichbar oder sind die Daten beschädigt, gelten die Standardwerte aus tokens.css, ohne Fehlerseite.
|
||||
* Änderungen wirken sofort (Zwischenspeicher wird beim Speichern geleert), ohne Deployment.
|
||||
*/
|
||||
final class DesignSettings
|
||||
{
|
||||
public const KEY = 'design.scale';
|
||||
|
||||
private const CACHE_KEY = 'design.scale.v1';
|
||||
|
||||
/** @var array<string, int>|null */
|
||||
private static ?array $memo = null;
|
||||
|
||||
/**
|
||||
* Wirksame Werte (gespeichert oder Standard).
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
if (self::$memo !== null) {
|
||||
return self::$memo;
|
||||
}
|
||||
|
||||
try {
|
||||
$stored = Cache::rememberForever(self::CACHE_KEY, static function (): array {
|
||||
$row = SiteSetting::query()->find(self::KEY);
|
||||
|
||||
return $row === null ? [] : (array) $row->value;
|
||||
});
|
||||
|
||||
return self::$memo = $stored === [] ? DesignScale::defaults() : DesignScale::read($stored);
|
||||
} catch (Throwable) {
|
||||
return self::$memo = DesignScale::defaults();
|
||||
}
|
||||
}
|
||||
|
||||
/** Ob abweichende Werte wirksam sind. */
|
||||
public static function isCustomised(): bool
|
||||
{
|
||||
return self::values() !== DesignScale::defaults();
|
||||
}
|
||||
|
||||
/**
|
||||
* Speichert vollständige, geprüfte Werte.
|
||||
*
|
||||
* @param array<string, mixed> $input
|
||||
* @return array<string, string> Fehlermeldungen je Schlüssel; leer bei Erfolg
|
||||
*/
|
||||
public static function save(array $input, ?User $by = null): array
|
||||
{
|
||||
$errors = DesignScale::errors($input);
|
||||
|
||||
if ($errors !== []) {
|
||||
return $errors;
|
||||
}
|
||||
|
||||
$ordered = [];
|
||||
|
||||
foreach (array_keys(DesignScale::PARAMETERS) as $key) {
|
||||
$ordered[$key] = (int) $input[$key];
|
||||
}
|
||||
|
||||
SiteSetting::query()->updateOrCreate(['key' => self::KEY], ['value' => $ordered, 'updated_by' => $by?->getKey()]);
|
||||
self::flush();
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Standardwerte wiederherstellen: die Zeile entfällt, es gelten wieder die Werte aus tokens.css. */
|
||||
public static function reset(): void
|
||||
{
|
||||
SiteSetting::query()->whereKey(self::KEY)->delete();
|
||||
self::flush();
|
||||
}
|
||||
|
||||
/** Zeitpunkt der letzten Speicherung, falls vorhanden. */
|
||||
public static function updatedAt(): ?Carbon
|
||||
{
|
||||
try {
|
||||
return SiteSetting::query()->find(self::KEY)?->updated_at;
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static function flush(): void
|
||||
{
|
||||
self::$memo = null;
|
||||
|
||||
try {
|
||||
Cache::forget(self::CACHE_KEY);
|
||||
} catch (Throwable) {
|
||||
// Der Zwischenspeicher ist nur Beschleunigung.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stylesheet-Block für Layouts und Vorschauen; nach dem Stylesheet der Website einzufügen, damit er gewinnt.
|
||||
* Leer, solange keine abweichenden Werte gespeichert sind.
|
||||
*/
|
||||
public static function styleTag(): HtmlString
|
||||
{
|
||||
$css = DesignScale::css(self::values());
|
||||
|
||||
return new HtmlString($css === '' ? '' : '<style id="lf-design-scale">'.$css.'</style>');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Design;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Eine Einstellung der Website (Schlüssel-Wert, Wert als JSON). Lesen und Schreiben der Größenskala
|
||||
* läuft über DesignSettings.
|
||||
*
|
||||
* @property string $key
|
||||
* @property array<string, mixed> $value
|
||||
* @property int|null $updated_by
|
||||
*/
|
||||
class SiteSetting extends Model
|
||||
{
|
||||
protected $table = 'site_settings';
|
||||
|
||||
protected $primaryKey = 'key';
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['value' => 'array'];
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ class Acquisition extends Model
|
||||
'reference_type',
|
||||
'reference_id',
|
||||
'conditions',
|
||||
'acting_user_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
|
||||
@@ -47,7 +47,7 @@ public function __invoke(
|
||||
$candidates = Grant::query()
|
||||
->where('license_article_id', $article->id)
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->whereHas('acquisition', fn ($query) => $query->where('party_id', $user->party_id))
|
||||
->usableBy($user)
|
||||
->get()
|
||||
->filter(function (Grant $grant) use ($now): bool {
|
||||
if ($grant->valid_from !== null && $grant->valid_from->greaterThan($now)) {
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
use App\Domain\Catalog\ArticleRelease;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\RightsProfileVersion;
|
||||
use App\Domain\Identity\Membership;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
@@ -32,6 +35,32 @@ protected function casts(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Berechtigungen, die ein Konto nutzen darf (zentrale Regel für Entscheidung, Bibliothek und Vorschaubilder):
|
||||
* - persönliche Erwerbe: Inhaber ist die Person des Kontos;
|
||||
* - Erwerbe einer Organisation: nur das auslösende Konto und nur, solange seine Mitgliedschaft mit
|
||||
* Bestellberechtigung besteht (Etappe 1, Domänenmodell 04; Sitzpools folgen mit A4).
|
||||
*
|
||||
* @param Builder<Grant> $query
|
||||
* @return Builder<Grant>
|
||||
*/
|
||||
public function scopeUsableBy(Builder $query, User $user): Builder
|
||||
{
|
||||
return $query->whereHas('acquisition', function (Builder $acquisition) use ($user): void {
|
||||
$acquisition->where(function (Builder $either) use ($user): void {
|
||||
$either->where('party_id', $user->party_id)
|
||||
->orWhere(function (Builder $organisation) use ($user): void {
|
||||
$organisation->where('acting_user_id', $user->id)
|
||||
->whereIn('party_id', Membership::query()
|
||||
->active()
|
||||
->where('user_id', $user->id)
|
||||
->where('may_order', true)
|
||||
->select('party_id'));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public function acquisition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Acquisition::class);
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferStatus;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\OrderLine;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
@@ -69,6 +71,60 @@ public function grantManually(User $user, Offer $offer, User $actor, string $rea
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Freischaltung einer bezahlten Bestellposition aus deren festgehaltenem Umfang (Umfangskopie und Bedingungen der
|
||||
* Position, nicht aus der Angebotsfassung). Inhaber ist der Lizenzinhaber der Position, das auslösende Konto wird
|
||||
* am Erwerb festgehalten. Wiederholsicher: je Bestellposition genau ein Erwerb.
|
||||
*/
|
||||
public function issueFromOrderLine(OrderLine $line, Party $holder, User $actor): Acquisition
|
||||
{
|
||||
return DB::transaction(function () use ($line, $holder, $actor): Acquisition {
|
||||
$existing = Acquisition::query()->where([
|
||||
'party_id' => $holder->id,
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
])->first();
|
||||
|
||||
if ($existing !== null) {
|
||||
return $existing->load('grants');
|
||||
}
|
||||
|
||||
$acquisition = Acquisition::query()->create([
|
||||
'party_id' => $holder->id,
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
'acting_user_id' => $actor->id,
|
||||
'conditions' => [
|
||||
'term_rule' => $line->term_rule,
|
||||
'update_promise' => $line->update_promise,
|
||||
'holder_kind' => $line->holder_kind,
|
||||
'offer_version_id' => $line->offer_version_id,
|
||||
'licence_scope' => $line->licence_scope,
|
||||
'trainer_count' => $line->trainer_count,
|
||||
'price_cents' => (int) $line->price_cents,
|
||||
'discount_cents' => (int) $line->discount_cents,
|
||||
],
|
||||
]);
|
||||
|
||||
$line->loadMissing('scopeItems.article');
|
||||
|
||||
foreach ($line->scopeItems as $item) {
|
||||
$acquisition->grants()->create([
|
||||
'license_article_id' => $item->license_article_id,
|
||||
'rights_profile_version_id' => $item->rights_profile_version_id,
|
||||
'rights_snapshot' => $item->rights_snapshot,
|
||||
'release_at_grant_id' => $item->article?->current_release_id,
|
||||
'status' => GrantStatus::Aktiv,
|
||||
'valid_from' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
return $acquisition->load('grants');
|
||||
});
|
||||
}
|
||||
|
||||
public function issue(
|
||||
User $user,
|
||||
OfferVersion $version,
|
||||
@@ -98,6 +154,8 @@ public function issue(
|
||||
'update_promise' => $version->update_promise,
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'offer_version_id' => $version->id,
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
],
|
||||
]);
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ class MediaDelivery extends Model
|
||||
'copy_id',
|
||||
'checksum',
|
||||
'marking',
|
||||
'composition_version_id',
|
||||
'delivered_at',
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Identity;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Rechnungsadresse eines Lizenzinhabers (Person oder Organisation). Eine je Inhaber. Sie wird nur gepflegt;
|
||||
* eine Bestellung kopiert sie erst, wenn die Rechnungsstellung sie braucht.
|
||||
*/
|
||||
class BillingAddress extends Model
|
||||
{
|
||||
/** Auswählbare Länder (ISO 3166-1 Alpha-2). */
|
||||
public const COUNTRIES = [
|
||||
'DE' => 'Deutschland',
|
||||
'AT' => 'Österreich',
|
||||
'CH' => 'Schweiz',
|
||||
'LI' => 'Liechtenstein',
|
||||
'LU' => 'Luxemburg',
|
||||
'BE' => 'Belgien',
|
||||
'NL' => 'Niederlande',
|
||||
'FR' => 'Frankreich',
|
||||
'IT' => 'Italien',
|
||||
'DK' => 'Dänemark',
|
||||
'PL' => 'Polen',
|
||||
'CZ' => 'Tschechien',
|
||||
];
|
||||
|
||||
protected $fillable = [
|
||||
'party_id',
|
||||
'recipient',
|
||||
'line2',
|
||||
'street',
|
||||
'postal_code',
|
||||
'city',
|
||||
'country',
|
||||
];
|
||||
|
||||
public function party(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Party::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Identity;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Mitgliedschaft eines Kontos in einer Organisation (Domänenmodell 04, MEMBERSHIP). Etappe 1 nutzt sie für die
|
||||
* Bestellberechtigung: Ein Konto bestellt nur für eine Organisation, bei der eine aktive Mitgliedschaft mit
|
||||
* `may_order` besteht. Sitzpools und Selbstverwaltung folgen mit A4.
|
||||
*/
|
||||
class Membership extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'party_id',
|
||||
'role',
|
||||
'may_order',
|
||||
'valid_from',
|
||||
'valid_until',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'may_order' => 'boolean',
|
||||
'valid_from' => 'date',
|
||||
'valid_until' => 'date',
|
||||
];
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function organisation(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Party::class, 'party_id');
|
||||
}
|
||||
|
||||
/** Mitgliedschaften, die heute gelten. */
|
||||
public function scopeActive(Builder $query): Builder
|
||||
{
|
||||
return $query
|
||||
->where(fn (Builder $inner) => $inner->whereNull('valid_from')->orWhereDate('valid_from', '<=', now()))
|
||||
->where(fn (Builder $inner) => $inner->whereNull('valid_until')->orWhereDate('valid_until', '>=', now()));
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,11 @@ public function user(): HasOne
|
||||
return $this->hasOne(User::class);
|
||||
}
|
||||
|
||||
public function billingAddress(): HasOne
|
||||
{
|
||||
return $this->hasOne(BillingAddress::class);
|
||||
}
|
||||
|
||||
public function profile(): HasOne
|
||||
{
|
||||
return $this->hasOne(Profile::class);
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Übernimmt das Vorschaubild eines Programms oder Moduls als gewöhnliches Bild-Medium im Medienmanager
|
||||
* (Programm- und Modulkarte), nach demselben Prinzip wie FilmStill.
|
||||
*
|
||||
* - Ausdrückliche Handlung der Redaktion. Das Vorschaubild ist ein geschütztes Bibliotheksbild; erst die Übernahme
|
||||
* legt ein Medium an, das für die Website freigegeben werden kann (WebsiteIntake, Warteschlange).
|
||||
* - Die Datei wird einmal kopiert. Dieselbe Vorschaudatei ergibt dasselbe Medium (composition_still_sources).
|
||||
* - Es entsteht keine Fassung, keine Berechtigung, kein Lizenzartikel.
|
||||
*/
|
||||
class CompositionStill
|
||||
{
|
||||
/** Wahr, wenn der letzte Aufruf ein schon vorhandenes Bild geliefert hat. */
|
||||
public bool $reused = false;
|
||||
|
||||
public function __construct(private readonly WebsiteIntake $intake) {}
|
||||
|
||||
public function refusal(Composition $composition): ?string
|
||||
{
|
||||
if ($composition->archived_at !== null) {
|
||||
return 'Das Programm oder Modul ist archiviert.';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function hasThumbnail(Composition $composition): bool
|
||||
{
|
||||
$path = $composition->thumbnail_path;
|
||||
|
||||
return is_string($path) && str_starts_with($path, 'vorschau/') && ! str_contains($path, '..')
|
||||
&& Storage::disk('media_derived')->exists($path);
|
||||
}
|
||||
|
||||
public function fromThumbnail(Composition $composition, ?User $actor = null): ContentElement
|
||||
{
|
||||
$this->reused = false;
|
||||
$refusal = $this->refusal($composition);
|
||||
|
||||
if ($refusal !== null) {
|
||||
throw new DomainRuleException($refusal);
|
||||
}
|
||||
|
||||
if (! $this->hasThumbnail($composition)) {
|
||||
throw new DomainRuleException('Dieses Programm oder Modul hat noch kein Vorschaubild. Setzen Sie es im Redaktionsmanager.');
|
||||
}
|
||||
|
||||
$bytes = Storage::disk('media_derived')->get((string) $composition->thumbnail_path);
|
||||
|
||||
if (! is_string($bytes) || $bytes === '') {
|
||||
throw new DomainRuleException('Das Vorschaubild ließ sich nicht lesen.');
|
||||
}
|
||||
|
||||
$key = 'file:'.hash('sha256', $bytes);
|
||||
$existing = $this->existing($composition, $key);
|
||||
|
||||
if ($existing instanceof ContentElement) {
|
||||
$this->reused = true;
|
||||
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$title = (string) ($composition->display_title ?: $composition->designation);
|
||||
$path = 'cms/titelbild-'.$composition->id.'-'.Str::lower(Str::random(8)).'.jpg';
|
||||
Storage::disk('cms_incoming')->put($path, $bytes);
|
||||
|
||||
$still = $this->intake->acceptImage($path, 'Titelbild: '.$title, null, 'Titelbild zu „'.$title.'“', $actor);
|
||||
|
||||
try {
|
||||
CompositionStillSource::query()->updateOrCreate(
|
||||
['composition_id' => $composition->id, 'source_key' => $key],
|
||||
['still_element_id' => $still->id, 'actor_id' => $actor?->id],
|
||||
);
|
||||
} catch (QueryException) {
|
||||
return $this->existing($composition, $key) ?? $still;
|
||||
}
|
||||
|
||||
return $still;
|
||||
}
|
||||
|
||||
private function existing(Composition $composition, string $key): ?ContentElement
|
||||
{
|
||||
$source = CompositionStillSource::query()->with('still')->where('composition_id', $composition->id)->where('source_key', $key)->first();
|
||||
$still = $source?->still;
|
||||
|
||||
// Ein archiviertes oder bei der Verarbeitung gescheitertes Bild wird nicht wiederverwendet.
|
||||
return $still instanceof ContentElement && $still->archived_at === null && ! filled($still->thumbnail_error) ? $still : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Herkunft eines Bild-Mediums aus dem Vorschaubild eines Programms oder Moduls (source_key file:{SHA-256}).
|
||||
*/
|
||||
class CompositionStillSource extends Model
|
||||
{
|
||||
protected $fillable = ['composition_id', 'still_element_id', 'source_key', 'actor_id'];
|
||||
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
public function still(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContentElement::class, 'still_element_id');
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ public function write(
|
||||
string $format,
|
||||
?string $checksum,
|
||||
string $marking,
|
||||
?string $copyId = null,
|
||||
?int $compositionVersionId = null,
|
||||
): MediaDelivery {
|
||||
return MediaDelivery::query()->create([
|
||||
'grant_id' => $grant->id,
|
||||
@@ -27,10 +29,16 @@ public function write(
|
||||
'content_element_version_id' => $version->id,
|
||||
'action' => $action,
|
||||
'format' => $format,
|
||||
'copy_id' => 'LK-'.strtoupper(bin2hex(random_bytes(6))),
|
||||
'copy_id' => $copyId ?? self::newCopyId(),
|
||||
'composition_version_id' => $compositionVersionId,
|
||||
'checksum' => $checksum,
|
||||
'marking' => $marking,
|
||||
'delivered_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function newCopyId(): string
|
||||
{
|
||||
return 'LK-'.strtoupper(bin2hex(random_bytes(6)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Legt ein Bild aus einem Film als gewöhnliches Bild-Medium im Medienmanager ab (Medien- und Materialkarte).
|
||||
*
|
||||
* - Die Stelle kommt aus der bereitgestellten Fassung, bei einem Film ohne solche Fassung (zum Beispiel ein Teaser nur
|
||||
* mit Website-Datei) aus der Website-Datei (`teaser/`, Herkunft `frame:0@Sekunde`).
|
||||
* - Zwei Wege: das Vorschaubild des Films übernehmen oder eine Stelle (Sekunde) wählen. Beides ist eine
|
||||
* ausdrückliche Handlung der Redaktion; erst dadurch entsteht ein Bild, das für die Website freigegeben werden kann.
|
||||
* - Das Bild wird einmal gezogen und gespeichert (WebsiteIntake legt es an, die Warteschlange leitet es ab und gibt
|
||||
* es frei). Seitenaufrufe lesen nur die gespeicherte Datei und starten nie ffmpeg.
|
||||
* - Dieselbe Stelle (oder dieselbe Vorschaudatei) ergibt dasselbe Medium (film_still_sources).
|
||||
* - Es wird nie der Film selbst, nur ein Einzelbild bis 1600 px Breite abgelegt. Traineranleitungen und
|
||||
* archivierte oder gesperrte Filme sind ausgeschlossen. Eine Rechte- oder Lizenzentscheidung entsteht nicht.
|
||||
*/
|
||||
class FilmStill
|
||||
{
|
||||
/** Breite eines übernommenen Standbilds; die kleine Filmstufe (640 px) wäre auf der Website sichtbar unscharf. */
|
||||
public const WIDTH = 1600;
|
||||
|
||||
/** Wahr, wenn der letzte Aufruf ein schon vorhandenes Bild geliefert hat (keine neue Extraktion). */
|
||||
public bool $reused = false;
|
||||
|
||||
public function __construct(
|
||||
private readonly ThumbnailDeriver $deriver,
|
||||
private readonly WebsiteIntake $intake,
|
||||
) {}
|
||||
|
||||
/** Grund, warum aus diesem Medium kein Standbild übernommen wird, sonst null. */
|
||||
public function refusal(ContentElement $film): ?string
|
||||
{
|
||||
if ($film->output_class !== 'film') {
|
||||
return 'Nur aus einem Film lässt sich ein Bild übernehmen.';
|
||||
}
|
||||
|
||||
if ($film->archived_at !== null) {
|
||||
return 'Der Film ist archiviert.';
|
||||
}
|
||||
|
||||
$slug = $film->editorialContentKind?->slug;
|
||||
|
||||
if (in_array($slug, PublicMaterialReader::CONFIDENTIAL_KINDS, true)) {
|
||||
return 'Aus Traineranleitungen werden keine Bilder für die Website übernommen.';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Die bereitgestellte Fassung, aus der Stellen gezogen werden (die höchste). */
|
||||
public function version(ContentElement $film): ?ContentElementVersion
|
||||
{
|
||||
return $film->versions()
|
||||
->where('status', ContentVersionStatus::Bereit->value)
|
||||
->orderByDesc('number')
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Website-Datei, aus der Stellen gezogen werden, wenn es keine bereitgestellte Fassung gibt (Film nur mit
|
||||
* Website-Datei). Sonst null.
|
||||
*/
|
||||
public function websiteFile(ContentElement $film): ?string
|
||||
{
|
||||
$path = $film->preview_path;
|
||||
|
||||
if ($this->version($film) instanceof ContentElementVersion
|
||||
|| ! is_string($path) || $path === '' || str_contains($path, '..') || ! str_starts_with($path, 'teaser/')
|
||||
|| ! Storage::disk('media_derived')->exists($path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/** Sekunde der Stelle, aus der das aktuelle Vorschaubild des Films stammt, sonst null. */
|
||||
public function thumbnailSecond(ContentElement $film): ?string
|
||||
{
|
||||
$source = $film->thumbnail_source;
|
||||
|
||||
return is_string($source) && preg_match('/^frame:\d+@([\d.]+)$/', $source, $match) === 1 ? $match[1] : null;
|
||||
}
|
||||
|
||||
public function fromSecond(ContentElement $film, float $seconds, ?User $actor = null): ContentElement
|
||||
{
|
||||
$this->reused = false;
|
||||
$this->guard($film);
|
||||
|
||||
if ($seconds < 0 || $seconds > 7200) {
|
||||
throw new DomainRuleException('Die Zeitposition liegt außerhalb des Films.');
|
||||
}
|
||||
|
||||
$version = $this->version($film);
|
||||
|
||||
if (! $version instanceof ContentElementVersion) {
|
||||
if ($this->websiteFile($film) !== null) {
|
||||
return $this->fromWebsiteFrame($film, $seconds, $actor);
|
||||
}
|
||||
|
||||
throw new DomainRuleException('Der Film hat weder eine bereitgestellte Fassung noch eine Website-Datei.');
|
||||
}
|
||||
|
||||
return $this->fromFrame($film, $version, $seconds, $actor);
|
||||
}
|
||||
|
||||
public function fromThumbnail(ContentElement $film, ?User $actor = null): ContentElement
|
||||
{
|
||||
$this->reused = false;
|
||||
$this->guard($film);
|
||||
|
||||
// Stammt das Vorschaubild aus einer Filmstelle, wird dieselbe Stelle in voller Auflösung gezogen.
|
||||
$second = $this->thumbnailSecond($film);
|
||||
|
||||
if ($second !== null && preg_match('/^frame:(\d+)@/', (string) $film->thumbnail_source, $match) === 1) {
|
||||
$version = ContentElementVersion::query()->find((int) $match[1]);
|
||||
|
||||
if ($version instanceof ContentElementVersion
|
||||
&& (int) $version->content_element_id === (int) $film->id
|
||||
&& $version->status !== ContentVersionStatus::Gesperrt) {
|
||||
try {
|
||||
return $this->fromFrame($film, $version, (float) $second, $actor);
|
||||
} catch (DomainRuleException) {
|
||||
// Die Stelle lässt sich nicht mehr ziehen: das gespeicherte Vorschaubild selbst übernehmen.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$path = $film->thumbnail_path;
|
||||
|
||||
if (! is_string($path) || ! str_starts_with($path, 'vorschau/') || str_contains($path, '..') || ! Storage::disk('media_derived')->exists($path)) {
|
||||
throw new DomainRuleException('Dieser Film hat noch kein Vorschaubild. Setzen Sie es im Medienmanager oder wählen Sie eine Stelle.');
|
||||
}
|
||||
|
||||
$bytes = Storage::disk('media_derived')->get($path);
|
||||
|
||||
if (! is_string($bytes) || $bytes === '') {
|
||||
throw new DomainRuleException('Das Vorschaubild ließ sich nicht lesen.');
|
||||
}
|
||||
|
||||
$key = 'file:'.hash('sha256', $bytes);
|
||||
$existing = $this->existing($film, $key);
|
||||
|
||||
if ($existing instanceof ContentElement) {
|
||||
$this->reused = true;
|
||||
|
||||
return $existing;
|
||||
}
|
||||
|
||||
return $this->store($film, $key, $bytes, 'Vorschaubild', $actor);
|
||||
}
|
||||
|
||||
private function fromFrame(ContentElement $film, ContentElementVersion $version, float $seconds, ?User $actor): ContentElement
|
||||
{
|
||||
$second = $this->secondText($seconds);
|
||||
$key = 'frame:'.$version->id.'@'.$second;
|
||||
$existing = $this->existing($film, $key);
|
||||
|
||||
if ($existing instanceof ContentElement) {
|
||||
$this->reused = true;
|
||||
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$bytes = $this->deriver->frameJpeg($version, (float) $second, self::WIDTH, original: true);
|
||||
|
||||
if (! is_string($bytes)) {
|
||||
throw new DomainRuleException('Aus dieser Filmstelle ließ sich kein Bild erzeugen.');
|
||||
}
|
||||
|
||||
return $this->store($film, $key, $bytes, 'Fassung '.$version->number.', '.str_replace('.', ',', $second).' s', $actor);
|
||||
}
|
||||
|
||||
private function fromWebsiteFrame(ContentElement $film, float $seconds, ?User $actor): ContentElement
|
||||
{
|
||||
$second = $this->secondText($seconds);
|
||||
$key = 'frame:0@'.$second;
|
||||
$existing = $this->existing($film, $key);
|
||||
|
||||
if ($existing instanceof ContentElement) {
|
||||
$this->reused = true;
|
||||
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$bytes = $this->deriver->websiteFileJpeg($film, (float) $second, self::WIDTH);
|
||||
|
||||
if (! is_string($bytes)) {
|
||||
throw new DomainRuleException('Aus dieser Stelle der Website-Datei ließ sich kein Bild erzeugen.');
|
||||
}
|
||||
|
||||
return $this->store($film, $key, $bytes, 'Website-Datei, '.str_replace('.', ',', $second).' s', $actor);
|
||||
}
|
||||
|
||||
private function guard(ContentElement $film): void
|
||||
{
|
||||
$refusal = $this->refusal($film);
|
||||
|
||||
if ($refusal !== null) {
|
||||
throw new DomainRuleException($refusal);
|
||||
}
|
||||
}
|
||||
|
||||
private function existing(ContentElement $film, string $key): ?ContentElement
|
||||
{
|
||||
$source = FilmStillSource::query()->with('still')->where('film_element_id', $film->id)->where('source_key', $key)->first();
|
||||
$still = $source?->still;
|
||||
|
||||
// Ein archiviertes oder an der Verarbeitung gescheitertes Bild wird nicht wiederverwendet; die Stelle kann neu
|
||||
// übernommen werden (store() ordnet dann das neue Bild zu).
|
||||
return $still instanceof ContentElement && $still->archived_at === null && ! filled($still->thumbnail_error) ? $still : null;
|
||||
}
|
||||
|
||||
private function store(ContentElement $film, string $key, string $bytes, string $label, ?User $actor): ContentElement
|
||||
{
|
||||
$title = (string) ($film->display_title ?: $film->working_title);
|
||||
$path = 'cms/standbild-'.$film->id.'-'.Str::lower(Str::random(8)).'.jpg';
|
||||
Storage::disk('cms_incoming')->put($path, $bytes);
|
||||
|
||||
$still = $this->intake->acceptImage(
|
||||
$path,
|
||||
'Standbild: '.$title.' ('.$label.')',
|
||||
filled($film->website_credit) ? (string) $film->website_credit : null,
|
||||
'Szene aus dem Film „'.$title.'“',
|
||||
$actor,
|
||||
);
|
||||
|
||||
try {
|
||||
FilmStillSource::query()->updateOrCreate(
|
||||
['film_element_id' => $film->id, 'source_key' => $key],
|
||||
['still_element_id' => $still->id, 'actor_id' => $actor?->id],
|
||||
);
|
||||
} catch (QueryException) {
|
||||
// Gleichzeitige Übernahme derselben Stelle: das zuerst angelegte Bild gilt.
|
||||
return $this->existing($film, $key) ?? $still;
|
||||
}
|
||||
|
||||
return $still;
|
||||
}
|
||||
|
||||
private function secondText(float $seconds): string
|
||||
{
|
||||
$text = number_format(max(0, min(7200, $seconds)), 3, '.', '');
|
||||
|
||||
return rtrim(rtrim($text, '0'), '.') ?: '0';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Herkunft eines Standbilds: aus welchem Film und welcher Stelle (frame:{Fassung}@{Sekunde}) oder aus welcher Datei
|
||||
* (file:{SHA-256}) das Bild-Medium stammt.
|
||||
*/
|
||||
class FilmStillSource extends Model
|
||||
{
|
||||
protected $fillable = ['film_element_id', 'still_element_id', 'source_key', 'actor_id'];
|
||||
|
||||
public function film(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContentElement::class, 'film_element_id');
|
||||
}
|
||||
|
||||
public function still(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContentElement::class, 'still_element_id');
|
||||
}
|
||||
}
|
||||
@@ -4,39 +4,72 @@
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Jobs\StorePresentationFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Legt die technische Ableitung eines Präsentationsmediums an der Medienidentität ab.
|
||||
* Es entsteht keine Inhaltsfassung, keine Freigabe und keine Berechtigung.
|
||||
* Legt die technische Ableitung eines Präsentationsmediums (Website-Datei) an der Medienidentität ab.
|
||||
* Es entsteht keine Inhaltsfassung, keine Freigabe und keine Berechtigung. Eine vorhandene Inhaltsfassung bleibt
|
||||
* unverändert und geschützt; die Website-Datei ist eine eigene, bewusst gewählte Datei daneben.
|
||||
*
|
||||
* Der Web-Prozess hat `derived/` nur lesend. Er prüft deshalb nur und gibt das Kopieren an die Warteschlange
|
||||
* (`StorePresentationFile`, ruft `place()` auf).
|
||||
*/
|
||||
class PresentationFile
|
||||
{
|
||||
public function store(ContentElement $element, string $incoming): void
|
||||
/**
|
||||
* Dateiendungen, die ein Browser auf der Website abspielen kann.
|
||||
*
|
||||
* @var array<string, list<string>>
|
||||
*/
|
||||
public const EXTENSIONS = [
|
||||
'bild' => ['jpg', 'jpeg', 'png', 'webp', 'gif'],
|
||||
'audio' => ['mp3', 'm4a', 'ogg'],
|
||||
'film' => ['mp4', 'webm'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Prüft die Datei im Eingang, ohne etwas zu verändern. Wirft eine verständliche Regelverletzung.
|
||||
*/
|
||||
public function validate(string $outputClass, string $incoming): void
|
||||
{
|
||||
if (! in_array($element->output_class, ['bild', 'film', 'audio'], true)) {
|
||||
if (! isset(self::EXTENSIONS[$outputClass])) {
|
||||
throw new DomainRuleException('Eine Präsentationsdatei ist ein Bild, ein Film oder ein Hörstück.');
|
||||
}
|
||||
|
||||
if ($element->versions()->exists()) {
|
||||
throw new DomainRuleException('Dieses Medium hat bereits eine Inhaltsfassung. Die Präsentationsdatei ersetzt sie nicht.');
|
||||
$extension = strtolower(pathinfo($incoming, PATHINFO_EXTENSION));
|
||||
|
||||
if (! in_array($extension, self::EXTENSIONS[$outputClass], true)) {
|
||||
throw new DomainRuleException(sprintf(
|
||||
'Für die Website geht nur %s. Eine %s-Datei kann der Browser nicht direkt abspielen; wandle sie vorher um oder lade sie ohne „Eigenständiges Präsentationsmedium“ hoch.',
|
||||
$this->formats($outputClass),
|
||||
$extension === '' ? 'Datei ohne Endung' : '.'.$extension,
|
||||
));
|
||||
}
|
||||
|
||||
if (! $this->readable($incoming)) {
|
||||
throw new DomainRuleException('Die Datei liegt nicht im Eingang.');
|
||||
}
|
||||
}
|
||||
|
||||
public function store(ContentElement $element, string $incoming): void
|
||||
{
|
||||
$this->validate((string) $element->output_class, $incoming);
|
||||
|
||||
$element->thumbnail_error = null;
|
||||
$element->save();
|
||||
|
||||
StorePresentationFile::dispatch($element->id, $incoming);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kopiert die Datei nach `derived/`. Läuft nur in der Warteschlange, die dort schreiben darf.
|
||||
*/
|
||||
public function place(ContentElement $element, string $incoming): void
|
||||
{
|
||||
$this->validate((string) $element->output_class, $incoming);
|
||||
|
||||
$extension = strtolower(pathinfo($incoming, PATHINFO_EXTENSION));
|
||||
$allowed = match ($element->output_class) {
|
||||
'bild' => ['jpg', 'jpeg', 'png', 'webp', 'gif'],
|
||||
'audio' => ['mp3', 'm4a', 'ogg'],
|
||||
default => ['mp4', 'webm'],
|
||||
};
|
||||
|
||||
if (! in_array($extension, $allowed, true)) {
|
||||
throw new DomainRuleException('Diese Datei ist keine freigebbare Ableitung. Es wird keine Inhaltsfassung angelegt.');
|
||||
}
|
||||
|
||||
$prefix = $element->output_class === 'bild' ? 'vorschau' : 'teaser';
|
||||
$target = $prefix.'/'.$element->id.'/datei.'.$extension;
|
||||
$stream = Storage::disk('cms_incoming')->readStream($incoming);
|
||||
@@ -46,11 +79,15 @@ public function store(ContentElement $element, string $incoming): void
|
||||
}
|
||||
|
||||
try {
|
||||
Storage::disk('media_derived')->writeStream($target, $stream);
|
||||
$written = Storage::disk('media_derived')->writeStream($target, $stream);
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
|
||||
if ($written === false) {
|
||||
throw new DomainRuleException('Die Datei ließ sich nicht ablegen.');
|
||||
}
|
||||
|
||||
if ($element->output_class === 'bild') {
|
||||
$element->thumbnail_path = $target;
|
||||
$element->thumbnail_source = 'eigen';
|
||||
@@ -58,7 +95,18 @@ public function store(ContentElement $element, string $incoming): void
|
||||
$element->preview_path = $target;
|
||||
}
|
||||
|
||||
$element->thumbnail_error = null;
|
||||
$element->save();
|
||||
Storage::disk('cms_incoming')->delete($incoming);
|
||||
}
|
||||
|
||||
public function formats(string $outputClass): string
|
||||
{
|
||||
return match ($outputClass) {
|
||||
'bild' => 'JPG, PNG, WebP oder GIF',
|
||||
'audio' => 'MP3, M4A oder OGG',
|
||||
default => 'MP4 (H.264) oder WebM',
|
||||
};
|
||||
}
|
||||
|
||||
private function readable(string $path): bool
|
||||
|
||||
@@ -87,6 +87,27 @@ public function forElementFrame(ContentElement $element, ContentElementVersion $
|
||||
$this->rememberElement($element, 'frame:'.$version->id.'@'.$this->secondText($seconds));
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschaubild aus einer Stelle der Website-Datei. Die Herkunft steht als `frame:0@{Sekunde}`; die 0 steht für die
|
||||
* Website-Datei (es gibt keine Fassung), alle Leser der Herkunft kommen damit zurecht.
|
||||
*/
|
||||
public function forElementWebsiteFrame(ContentElement $element, float $seconds): void
|
||||
{
|
||||
$bytes = $this->jpegAtWebsiteFile($element, $seconds);
|
||||
|
||||
if (! is_string($bytes)) {
|
||||
$this->fail($element, 'Aus dieser Filmstelle ließ sich kein Vorschaubild erzeugen.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$name = 'element-'.$element->id;
|
||||
$path = 'vorschau/'.$name.'.jpg';
|
||||
Storage::disk('media_derived')->put($path, $bytes);
|
||||
$this->still($element, Storage::disk('media_derived'), $path, $name);
|
||||
$this->rememberElement($element, 'frame:0@'.$this->secondText($seconds));
|
||||
}
|
||||
|
||||
public function forCompositionUpload(Composition $composition, string $incoming): void
|
||||
{
|
||||
if (! str_starts_with($incoming, 'vorschau/') || str_contains($incoming, '..')) {
|
||||
@@ -138,8 +159,20 @@ public function forCompositionFrame(Composition $composition, ContentElementVers
|
||||
$this->rememberChoice($composition, 'frame:'.$version->id.'@'.$this->secondText($seconds));
|
||||
}
|
||||
|
||||
public function frameInput(ContentElementVersion $version): ?string
|
||||
/**
|
||||
* Datei, aus der ein Bild gezogen wird. Vorgabe: die kleine Filmstufe (schnell, für die Vorschau). Mit $original
|
||||
* zuerst die Mediendatei selbst, damit ein übernommenes Standbild nicht aus der kleinen Stufe hochgerechnet wird.
|
||||
*/
|
||||
public function frameInput(ContentElementVersion $version, bool $original = false): ?string
|
||||
{
|
||||
if ($original) {
|
||||
$master = is_array($version->metadata) ? ($version->metadata['file'] ?? null) : null;
|
||||
|
||||
if ($this->readableDerived($master, 'inhalte/')) {
|
||||
return $master;
|
||||
}
|
||||
}
|
||||
|
||||
$proxy = MediaRendition::query()
|
||||
->where('content_element_version_id', $version->id)
|
||||
->where('role', 'variant')
|
||||
@@ -155,15 +188,55 @@ public function frameInput(ContentElementVersion $version): ?string
|
||||
return $this->readableDerived($file, 'inhalte/') ? $file : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Einzelbild einer Filmstelle als JPEG, 640 px breit aus der kleinen Stufe (Vorschau im Editor und Vorschaubild).
|
||||
*/
|
||||
public function jpegAtVersion(ContentElementVersion $version, float $seconds): ?string
|
||||
{
|
||||
return $this->frameJpeg($version, $seconds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Einzelbild einer Filmstelle als JPEG. Ein übernommenes Standbild (FilmStill) wird mit $width und $original aus der
|
||||
* Mediendatei gezogen statt aus der kleinen Stufe und dabei nie über die Breite der Quelle hinaus vergrößert.
|
||||
*/
|
||||
public function frameJpeg(ContentElementVersion $version, float $seconds, int $width = 640, bool $original = false): ?string
|
||||
{
|
||||
if ($seconds < 0 || $seconds > 7200) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$file = $this->frameInput($version);
|
||||
$file = $this->frameInput($version, $original);
|
||||
|
||||
if ($file === null) {
|
||||
return $file === null ? null : $this->jpegFromFile($file, $seconds, $width);
|
||||
}
|
||||
|
||||
/**
|
||||
* Einzelbild aus der Website-Datei eines Films (`teaser/`), für Medien ohne Inhaltsfassung.
|
||||
*/
|
||||
public function jpegAtWebsiteFile(ContentElement $element, float $seconds): ?string
|
||||
{
|
||||
return $this->websiteFileJpeg($element, $seconds, 640);
|
||||
}
|
||||
|
||||
/**
|
||||
* Einzelbild aus der Website-Datei in der gewünschten Breite, nie über die Breite der Datei hinaus (Standbild für
|
||||
* die Medienkarte, FilmStill).
|
||||
*/
|
||||
public function websiteFileJpeg(ContentElement $element, float $seconds, int $width): ?string
|
||||
{
|
||||
$file = $element->preview_path;
|
||||
|
||||
if ($element->output_class !== 'film' || ! $this->readableDerived($file, 'teaser/')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->jpegFromFile($file, $seconds, $width);
|
||||
}
|
||||
|
||||
private function jpegFromFile(string $file, float $seconds, int $width): ?string
|
||||
{
|
||||
if ($seconds < 0 || $seconds > 7200) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -186,7 +259,7 @@ public function jpegAtVersion(ContentElementVersion $version, float $seconds): ?
|
||||
'-frames:v',
|
||||
'1',
|
||||
'-vf',
|
||||
'scale=640:-2',
|
||||
$width === 640 ? 'scale=640:-2' : 'scale=min('.max(160, min(2400, $width)).'\,iw):-2',
|
||||
'-f',
|
||||
'image2pipe',
|
||||
'-vcodec',
|
||||
|
||||
@@ -37,6 +37,16 @@ public static function effectiveFor(mixed $path): ?self
|
||||
return $alias instanceof self && $alias->everReleased() ? $alias : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Früherer Pfad, dessen übernommenes Medium inzwischen gelöscht wurde. Die Datei unter cms/ bleibt liegen, wird aber
|
||||
* weder ausgeliefert noch als Bild gezeigt: Das Löschen des Mediums gilt auch für die frühere Adresse.
|
||||
*/
|
||||
public static function isRetired(mixed $path): bool
|
||||
{
|
||||
return is_string($path) && $path !== ''
|
||||
&& self::query()->where('legacy_path', $path)->whereNull('content_element_id')->exists();
|
||||
}
|
||||
|
||||
public function everReleased(): bool
|
||||
{
|
||||
$element = $this->element;
|
||||
|
||||
@@ -44,7 +44,7 @@ public function refusal(ContentElement $element): ?string
|
||||
}
|
||||
|
||||
if ($this->derivedPath($element) === null) {
|
||||
return 'Für die Website fehlt eine freigebbare Ableitung. Beim Bild ist das das Vorschaubild. Film und Hörstück ohne Inhaltsfassung nutzen die Datei am Medium unter teaser/. Ein Film mit Inhaltsfassung nutzt die Teaserfassung seiner bereitgestellten Fassung. Die Originaldatei bleibt geschützt.';
|
||||
return 'Für die Website fehlt eine freigebbare Datei. Beim Bild ist das das Vorschaubild. Bei Film und Hörstück lädst du unter „Website-Freigabe“ eine Website-Datei hoch (Film als MP4 oder WebM); die geschützte Originaldatei bleibt unberührt.';
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Domain\Design\DesignScale;
|
||||
use App\Domain\Design\DesignSettings;
|
||||
use App\Domain\Identity\StaffRole;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
/**
|
||||
* Website → Design → Größen (ADR-44): die zehn Basiswerte der Größenskala einsehen, ändern, speichern und auf die
|
||||
* Standardwerte zurücksetzen. Gespeichert wird erst mit „Größen speichern“; offene Eingaben bleiben beim Wechseln
|
||||
* der Ansicht erhalten. Die Werte wirken sofort auf die öffentliche Website und alle CMS-Vorschauen, ohne Deployment.
|
||||
* Zugriff nur für den Systemverwalter.
|
||||
*/
|
||||
class DesignGroessen extends Page
|
||||
{
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Design';
|
||||
|
||||
protected static ?string $navigationLabel = 'Größen';
|
||||
|
||||
protected static ?int $navigationSort = 30;
|
||||
|
||||
protected static ?string $slug = 'design/groessen';
|
||||
|
||||
protected static ?string $title = 'Größen';
|
||||
|
||||
protected string $view = 'filament.design.groessen';
|
||||
|
||||
/** Eingaben je Basiswert (Zeichenketten aus dem Formular). @var array<string, int|string> */
|
||||
public array $werte = [];
|
||||
|
||||
/** Fehlermeldungen je Basiswert nach dem letzten Speichern. @var array<string, string> */
|
||||
public array $fehler = [];
|
||||
|
||||
/** @var array{aktion: string, argument: int|string|null, titel: string, text: string, label: string, gefahr: bool}|null */
|
||||
public ?array $bestaetigung = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return auth()->user()?->hasStaffRole(StaffRole::Systemverwalter) === true;
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->ladeGespeicherte();
|
||||
}
|
||||
|
||||
/** Die Überschrift steht im gemeinsamen Objektkopf (filament.verwaltung.kopf), nicht doppelt im Seitenkopf. */
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::SevenExtraLarge;
|
||||
}
|
||||
|
||||
/** Wirksame Werte der Website (gespeichert oder Standard). @return array<string, int> */
|
||||
public function gespeichert(): array
|
||||
{
|
||||
return DesignSettings::values();
|
||||
}
|
||||
|
||||
/** Ob die Eingaben vom wirksamen Stand abweichen. */
|
||||
public function geaendert(): bool
|
||||
{
|
||||
$aktuell = [];
|
||||
|
||||
foreach (array_keys(DesignScale::PARAMETERS) as $key) {
|
||||
$wert = $this->werte[$key] ?? '';
|
||||
$aktuell[$key] = is_string($wert) && ctype_digit($wert) ? (int) $wert : $wert;
|
||||
}
|
||||
|
||||
return $aktuell !== $this->gespeichert();
|
||||
}
|
||||
|
||||
/** Eine Eingabe wurde geändert: ihre Fehlermeldung vom letzten Speichern entfällt. */
|
||||
public function updatedWerte(mixed $value, string $key): void
|
||||
{
|
||||
unset($this->fehler[$key]);
|
||||
}
|
||||
|
||||
public function speichern(): void
|
||||
{
|
||||
$this->fehler = DesignSettings::save($this->werte, auth()->user());
|
||||
|
||||
if ($this->fehler !== []) {
|
||||
Notification::make()->danger()->title('Nicht gespeichert')->body('Bitte die markierten Werte korrigieren.')->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->ladeGespeicherte();
|
||||
Notification::make()->success()->title('Größen gespeichert')->body('Die Werte gelten jetzt auf der Website und in den CMS-Vorschauen.')->send();
|
||||
}
|
||||
|
||||
public function askConfirmation(string $aktion, int|string|null $argument = null): void
|
||||
{
|
||||
$this->bestaetigung = match ($aktion) {
|
||||
'standard' => ['aktion' => 'standard', 'argument' => null, 'titel' => 'Standardwerte wiederherstellen?', 'text' => 'Die gespeicherten Größen werden entfernt. Website und Vorschauen verwenden sofort wieder die Standardwerte aus dem Designsystem. Offene Eingaben gehen dabei verloren.', 'label' => 'Standardwerte wiederherstellen', 'gefahr' => true],
|
||||
'verwerfen' => ['aktion' => 'verwerfen', 'argument' => null, 'titel' => 'Änderungen verwerfen?', 'text' => 'Die Eingaben kehren zum wirksamen Stand zurück. Gespeichert wird dabei nichts.', 'label' => 'Verwerfen', 'gefahr' => true],
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
public function confirmConfirmation(): void
|
||||
{
|
||||
$frage = $this->bestaetigung;
|
||||
$this->bestaetigung = null;
|
||||
|
||||
match ($frage['aktion'] ?? null) {
|
||||
'standard' => $this->standardWiederherstellen(),
|
||||
'verwerfen' => $this->ladeGespeicherte(),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
public function cancelConfirmation(): void
|
||||
{
|
||||
$this->bestaetigung = null;
|
||||
}
|
||||
|
||||
private function standardWiederherstellen(): void
|
||||
{
|
||||
DesignSettings::reset();
|
||||
$this->ladeGespeicherte();
|
||||
Notification::make()->success()->title('Standardwerte wiederhergestellt')->body('Website und Vorschauen verwenden wieder die Standardwerte.')->send();
|
||||
}
|
||||
|
||||
private function ladeGespeicherte(): void
|
||||
{
|
||||
$this->werte = $this->gespeichert();
|
||||
$this->fehler = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\ExerciseImportRun;
|
||||
use App\Domain\Catalog\ExerciseSource;
|
||||
use App\Domain\Catalog\ExerciseSourceSnapshot;
|
||||
use App\Domain\Catalog\ShinkanImport;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Resources\Practices\PracticeResource;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
/**
|
||||
* Übernahme aus Shinkan: Welche Übungen stellt die Quelle bereit, was ist neu oder geändert, was ist übernommen und was
|
||||
* stellt die Quelle nicht mehr bereit? Abrufen verändert nur den Quellenstand; erst „Übernehmen“ legt eine lokale
|
||||
* Fassung an, und erst eine Produktveröffentlichung setzt sie ein.
|
||||
*/
|
||||
class Uebernahme extends Page
|
||||
{
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
|
||||
protected static ?string $navigationLabel = 'Übernahme (Shinkan)';
|
||||
|
||||
protected static ?int $navigationSort = 6;
|
||||
|
||||
protected static ?string $slug = 'uebernahme';
|
||||
|
||||
protected static ?string $title = 'Übernahme aus Shinkan';
|
||||
|
||||
protected string $view = 'filament.pages.uebernahme';
|
||||
|
||||
public string $feedback = '';
|
||||
|
||||
public bool $feedbackError = false;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return ContentElementResource::editor();
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
public function fetch(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$run = app(ShinkanImport::class)->fetch();
|
||||
$this->feedbackError = $run->status !== 'ok';
|
||||
$this->feedback = $run->status === 'ok'
|
||||
? 'Abruf abgeschlossen: '.$run->added.' neu, '.$run->updated.' geändert, '.$run->removed.' nicht mehr bereitgestellt. Es wurde noch keine lokale Fassung angelegt.'
|
||||
: (string) $run->error;
|
||||
}
|
||||
|
||||
public function adopt(int $snapshotId): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
try {
|
||||
$user = Filament::auth()->user();
|
||||
$version = app(ShinkanImport::class)->adopt(ExerciseSourceSnapshot::query()->findOrFail($snapshotId), $user instanceof User ? $user : null);
|
||||
$this->feedbackError = false;
|
||||
$this->feedback = 'Fassung '.$version->number.' ist lokal angelegt und unveränderlich. Produkte verwenden sie erst, wenn du sie dort bewusst einsetzt und das Produkt veröffentlichst.';
|
||||
} catch (DomainRuleException $exception) {
|
||||
$this->feedbackError = true;
|
||||
$this->feedback = $exception->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function daten(): array
|
||||
{
|
||||
$import = app(ShinkanImport::class);
|
||||
$labels = [
|
||||
'neu' => ['Neu bei der Quelle', 'offen'],
|
||||
'geaendert' => ['Neue Quellfassung zur Übernahme', 'offen'],
|
||||
'uebernommen' => ['Übernommen', 'gut'],
|
||||
'nicht_mehr_bereitgestellt' => ['An der Quelle nicht mehr bereitgestellt', 'leise'],
|
||||
];
|
||||
$rows = [];
|
||||
|
||||
foreach (ExerciseSource::query()->with('composition')->orderBy('title')->get() as $source) {
|
||||
$state = $import->state($source);
|
||||
$latest = $source->latestSnapshot();
|
||||
$payload = $latest?->payload ?? [];
|
||||
$rows[] = [
|
||||
'titel' => $source->title ?: $source->source_id,
|
||||
'zustand' => $labels[$state][0],
|
||||
'ton' => $labels[$state][1],
|
||||
'snapshot' => $latest !== null && $latest->adopted_version_id === null ? $latest->id : null,
|
||||
'lokal' => $source->composition === null ? null : PracticeResource::getUrl('edit', ['record' => $source->composition]),
|
||||
'varianten' => count($payload['variants'] ?? []),
|
||||
'quellmedien' => array_map(fn (array $media): string => ($media['title'] ?? '').' ('.($media['media_type'] ?? '').')', (array) ($payload['media'] ?? [])),
|
||||
'hinweis' => $state === 'nicht_mehr_bereitgestellt'
|
||||
? 'Lokale Fassungen und Verwendungen bleiben unverändert. Eine rechtliche Sperre ist ein eigener Vorgang am Medium.'
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'zeilen' => $rows,
|
||||
'eingerichtet' => app(ShinkanImport::class)->configured(),
|
||||
'letzterLauf' => ExerciseImportRun::query()->orderByDesc('id')->first(),
|
||||
];
|
||||
}
|
||||
}
|
||||
Loaded 100 of 667 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user