Compare commits
52
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 | ||
|
|
1bc5356e84 |
No files matched your search
@@ -70,3 +70,7 @@ PAYMENT_DRIVER=test
|
|||||||
MEDIA_PUBLIC_PATH=
|
MEDIA_PUBLIC_PATH=
|
||||||
MEDIA_DERIVED_PATH=
|
MEDIA_DERIVED_PATH=
|
||||||
MEDIA_ORIGINALS_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=
|
||||||
@@ -57,6 +57,8 @@ public function publishRelease(
|
|||||||
'content_element_version_id' => $row['version_id'],
|
'content_element_version_id' => $row['version_id'],
|
||||||
'role' => $row['role'] !== '' ? $row['role'] : $row['path'],
|
'role' => $row['role'] !== '' ? $row['role'] : $row['path'],
|
||||||
'path' => $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();
|
$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) {
|
if ($root->status !== ContentVersionStatus::Bereit) {
|
||||||
throw new DomainRuleException('Ein Artikel-Stand kann nur eine bereitgestellte Fassung festschreiben.');
|
throw new DomainRuleException('Ein Artikel-Stand kann nur eine bereitgestellte Fassung festschreiben.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ class CompatibilityAttestation extends Model
|
|||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'composition_version_id',
|
'composition_version_id',
|
||||||
'resolved_hash',
|
'resolved_hash',
|
||||||
|
'structure_hash',
|
||||||
'confirmed_by',
|
'confirmed_by',
|
||||||
'confirmed_at',
|
'confirmed_at',
|
||||||
'note',
|
'note',
|
||||||
|
|||||||
@@ -36,6 +36,11 @@ protected function casts(): array
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected static function booted(): void
|
||||||
|
{
|
||||||
|
static::addGlobalScope(new SupportedKindScope);
|
||||||
|
}
|
||||||
|
|
||||||
public function editorialContentKind(): BelongsTo
|
public function editorialContentKind(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(EditorialContentKind::class);
|
return $this->belongsTo(EditorialContentKind::class);
|
||||||
|
|||||||
@@ -7,13 +7,24 @@ enum CompositionKind: string
|
|||||||
case Kombination = 'kombination';
|
case Kombination = 'kombination';
|
||||||
case Uebung = 'uebung';
|
case Uebung = 'uebung';
|
||||||
case Kurs = 'kurs';
|
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
|
public function label(): string
|
||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::Kombination => 'Fachliche Kombination',
|
self::Kombination => 'Fachliche Kombination',
|
||||||
self::Uebung => 'Übung',
|
self::Uebung => 'Modul',
|
||||||
self::Kurs => 'Kurs',
|
self::Kurs => 'Kurs',
|
||||||
|
self::Exercise => 'Übung',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,8 +32,9 @@ public function plural(): string
|
|||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::Kombination => 'Fachliche Kombinationen',
|
self::Kombination => 'Fachliche Kombinationen',
|
||||||
self::Uebung => 'Übungen',
|
self::Uebung => 'Module',
|
||||||
self::Kurs => 'Kurse',
|
self::Kurs => 'Kurse',
|
||||||
|
self::Exercise => 'Übungen',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,8 +42,9 @@ public function createLabel(): string
|
|||||||
{
|
{
|
||||||
return match ($this) {
|
return match ($this) {
|
||||||
self::Kombination => 'Kombination anlegen',
|
self::Kombination => 'Kombination anlegen',
|
||||||
self::Uebung => 'Übung anlegen',
|
self::Uebung => 'Modul anlegen',
|
||||||
self::Kurs => 'Kurs 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::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::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::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::Kombination => 'Fachliche Kombination',
|
||||||
self::Uebung => 'Modul',
|
self::Uebung => 'Modul',
|
||||||
self::Kurs => 'Programm',
|
self::Kurs => 'Programm',
|
||||||
|
self::Exercise => 'Übung',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +74,7 @@ public function deskExplanation(): string
|
|||||||
self::Kombination => $this->explanation(),
|
self::Kombination => $this->explanation(),
|
||||||
self::Uebung => 'Ein Modul mit Lernziel, Zeit, Material und geordneten Bestandteilen. Dieselben Medien können in mehreren Modulen stecken.',
|
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::Kurs => 'Ein Programm aus Modulen und weiteren Inhalten.',
|
||||||
|
self::Exercise => $this->explanation(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,8 +14,21 @@ class CompositionMember extends Model
|
|||||||
'placement_note',
|
'placement_note',
|
||||||
'content_element_version_id',
|
'content_element_version_id',
|
||||||
'nested_composition_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
|
protected static function booted(): void
|
||||||
{
|
{
|
||||||
static::creating(function (CompositionMember $member): void {
|
static::creating(function (CompositionMember $member): void {
|
||||||
@@ -41,6 +54,11 @@ public function contentElementVersion(): BelongsTo
|
|||||||
return $this->belongsTo(ContentElementVersion::class);
|
return $this->belongsTo(ContentElementVersion::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function variant(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(CompositionVersionVariant::class, 'variant_id');
|
||||||
|
}
|
||||||
|
|
||||||
public function nestedCompositionVersion(): BelongsTo
|
public function nestedCompositionVersion(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id');
|
return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id');
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ public function publish(
|
|||||||
?string $note,
|
?string $note,
|
||||||
array $didactic,
|
array $didactic,
|
||||||
bool $consent,
|
bool $consent,
|
||||||
|
array $variants = [],
|
||||||
): CompositionVersion {
|
): CompositionVersion {
|
||||||
$review = $this->review($host, $members);
|
$review = $this->review($host, $members);
|
||||||
|
|
||||||
@@ -67,8 +68,8 @@ public function publish(
|
|||||||
|
|
||||||
$this->publishedDrafts = [];
|
$this->publishedDrafts = [];
|
||||||
|
|
||||||
return DB::transaction(function () use ($host, $members, $actor, $note, $didactic): CompositionVersion {
|
return DB::transaction(function () use ($host, $members, $actor, $note, $didactic, $variants): CompositionVersion {
|
||||||
return $this->materialize($host, $members, $didactic, $actor, $note, []);
|
return $this->materialize($host, $members, $didactic, $actor, $note, [], $variants);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,6 +221,12 @@ private function inspectReleasedComposition(
|
|||||||
): void {
|
): void {
|
||||||
$version = CompositionVersion::query()->with('composition', 'members')->find($id);
|
$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) {
|
if (! $version instanceof CompositionVersion || $version->composition === null) {
|
||||||
$blocked[] = $this->block('Modul', 'Ein Bestandteil ist nicht mehr vorhanden.', $depth, null);
|
$blocked[] = $this->block('Modul', 'Ein Bestandteil ist nicht mehr vorhanden.', $depth, null);
|
||||||
|
|
||||||
@@ -324,6 +331,7 @@ private function materialize(
|
|||||||
?User $actor,
|
?User $actor,
|
||||||
?string $note,
|
?string $note,
|
||||||
array $stack,
|
array $stack,
|
||||||
|
array $variants = [],
|
||||||
): CompositionVersion {
|
): CompositionVersion {
|
||||||
if (isset($this->publishedDrafts[$composition->id])) {
|
if (isset($this->publishedDrafts[$composition->id])) {
|
||||||
return $this->publishedDrafts[$composition->id];
|
return $this->publishedDrafts[$composition->id];
|
||||||
@@ -341,6 +349,10 @@ private function materialize(
|
|||||||
'role' => trim((string) ($member['role'] ?? '')),
|
'role' => trim((string) ($member['role'] ?? '')),
|
||||||
'note' => trim((string) ($member['note'] ?? '')),
|
'note' => trim((string) ($member['note'] ?? '')),
|
||||||
'target' => $this->resolveTarget((string) ($member['target'] ?? ''), $actor, $stack),
|
'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,
|
'learning_goal' => $didactic['learning_goal'] ?? null,
|
||||||
'duration_minutes' => $didactic['duration_minutes'] ?? null,
|
'duration_minutes' => $didactic['duration_minutes'] ?? null,
|
||||||
|
'duration_max' => $didactic['duration_max'] ?? null,
|
||||||
'material_note' => $didactic['material_note'] ?? null,
|
'material_note' => $didactic['material_note'] ?? null,
|
||||||
|
'prerequisites' => $didactic['prerequisites'] ?? null,
|
||||||
],
|
],
|
||||||
|
$variants,
|
||||||
);
|
);
|
||||||
$this->publishedDrafts[$composition->id] = $version;
|
$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,
|
'learning_goal' => $draft['learning_goal'] ?? null,
|
||||||
'duration_minutes' => $draft['duration_minutes'] ?? null,
|
'duration_minutes' => $draft['duration_minutes'] ?? null,
|
||||||
|
'duration_max' => $draft['duration_max'] ?? null,
|
||||||
'material_note' => $draft['material_note'] ?? null,
|
'material_note' => $draft['material_note'] ?? null,
|
||||||
|
'prerequisites' => $draft['prerequisites'] ?? null,
|
||||||
],
|
],
|
||||||
$actor,
|
$actor,
|
||||||
is_string($draft['revision_note'] ?? null) ? $draft['revision_note'] : null,
|
is_string($draft['revision_note'] ?? null) ? $draft['revision_note'] : null,
|
||||||
$stack,
|
$stack,
|
||||||
|
is_array($draft['variants'] ?? null) ? $draft['variants'] : [],
|
||||||
);
|
);
|
||||||
app(EditorialWorkingDraft::class)->clear($composition);
|
app(EditorialWorkingDraft::class)->clear($composition);
|
||||||
|
|
||||||
|
|||||||
@@ -60,6 +60,11 @@ private function members(CompositionVersion $version, array $stack = []): array
|
|||||||
$nested->loadMissing('composition.editorialContentKind', 'composition');
|
$nested->loadMissing('composition.editorialContentKind', 'composition');
|
||||||
$composition = $nested->composition;
|
$composition = $nested->composition;
|
||||||
|
|
||||||
|
// Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht anzeigen (Rückfallschutz).
|
||||||
|
if ($composition === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
$nodes[] = new StructureNode(
|
$nodes[] = new StructureNode(
|
||||||
role: $member->role,
|
role: $member->role,
|
||||||
position: $member->position,
|
position: $member->position,
|
||||||
|
|||||||
@@ -17,6 +17,10 @@ class CompositionVersion extends Model
|
|||||||
'learning_goal',
|
'learning_goal',
|
||||||
'duration_minutes',
|
'duration_minutes',
|
||||||
'material_note',
|
'material_note',
|
||||||
|
'duration_max',
|
||||||
|
'prerequisites',
|
||||||
|
'structure_hash',
|
||||||
|
'source_snapshot_id',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
@@ -60,6 +64,11 @@ public function members(): HasMany
|
|||||||
return $this->hasMany(CompositionMember::class)->orderBy('position');
|
return $this->hasMany(CompositionMember::class)->orderBy('position');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function variants(): HasMany
|
||||||
|
{
|
||||||
|
return $this->hasMany(CompositionVersionVariant::class)->orderBy('position');
|
||||||
|
}
|
||||||
|
|
||||||
public function attestations(): HasMany
|
public function attestations(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(CompatibilityAttestation::class);
|
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',
|
'preview_path',
|
||||||
'editorial_content_kind_id',
|
'editorial_content_kind_id',
|
||||||
'archived_at',
|
'archived_at',
|
||||||
|
'source_ref',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
|
|||||||
@@ -5,9 +5,14 @@
|
|||||||
class ContentResolver
|
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) {
|
if ($node instanceof ContentElementVersion) {
|
||||||
$node->loadMissing('element');
|
$node->loadMissing('element');
|
||||||
@@ -16,6 +21,8 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
|||||||
'version_id' => $node->id,
|
'version_id' => $node->id,
|
||||||
'role' => $path,
|
'role' => $path,
|
||||||
'path' => $path !== '' ? $path : $node->element->working_title,
|
'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;
|
$stack[] = $node->composition_id;
|
||||||
$rows = [];
|
$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;
|
$segment = $path === '' ? $member->role : $path.' / '.$member->role;
|
||||||
|
|
||||||
if ($member->content_element_version_id !== null) {
|
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,
|
'version_id' => $member->content_element_version_id,
|
||||||
'role' => $member->role,
|
'role' => $member->role,
|
||||||
'path' => $segment,
|
'path' => $segment,
|
||||||
|
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
|
||||||
|
'variant' => $variantKey,
|
||||||
];
|
];
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
@@ -45,7 +60,20 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
|||||||
throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.');
|
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;
|
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(
|
public function publishComposition(
|
||||||
Composition $composition,
|
Composition $composition,
|
||||||
@@ -233,18 +235,21 @@ public function publishComposition(
|
|||||||
?User $confirmedBy = null,
|
?User $confirmedBy = null,
|
||||||
?string $note = null,
|
?string $note = null,
|
||||||
array $didactic = [],
|
array $didactic = [],
|
||||||
|
array $variants = [],
|
||||||
): CompositionVersion {
|
): CompositionVersion {
|
||||||
if ($members === []) {
|
if ($members === []) {
|
||||||
throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.');
|
throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$variants = $this->checkedVariants($variants);
|
||||||
$this->assertAcyclic($composition->id, $members);
|
$this->assertAcyclic($composition->id, $members);
|
||||||
|
|
||||||
foreach ($members as $member) {
|
foreach ($members as $member) {
|
||||||
$this->assertReadyMember($member['target']);
|
$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;
|
$number = ((int) $composition->versions()->max('number')) + 1;
|
||||||
$version = $composition->versions()->create([
|
$version = $composition->versions()->create([
|
||||||
'number' => $number,
|
'number' => $number,
|
||||||
@@ -253,28 +258,52 @@ public function publishComposition(
|
|||||||
'resolved_hash' => 'pending',
|
'resolved_hash' => 'pending',
|
||||||
'learning_goal' => $this->optionalText($didactic['learning_goal'] ?? null),
|
'learning_goal' => $this->optionalText($didactic['learning_goal'] ?? null),
|
||||||
'duration_minutes' => isset($didactic['duration_minutes']) ? (int) $didactic['duration_minutes'] : 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),
|
'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) {
|
foreach (array_values($members) as $index => $member) {
|
||||||
$target = $member['target'];
|
$target = $member['target'];
|
||||||
|
$selection = $target instanceof CompositionVersion ? ($member['selection'] ?? null) : null;
|
||||||
$version->members()->create([
|
$version->members()->create([
|
||||||
'position' => $index + 1,
|
'position' => $index + 1,
|
||||||
'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'),
|
'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'),
|
||||||
'placement_note' => $this->optionalText($member['note'] ?? null),
|
'placement_note' => $this->optionalText($member['note'] ?? null),
|
||||||
'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
||||||
'nested_composition_version_id' => $target instanceof CompositionVersion ? $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);
|
$resolvedHash = $this->resolver->resolvedHash($version);
|
||||||
|
$structureHash = $this->structureHash($version);
|
||||||
$version->attestations()->create([
|
$version->attestations()->create([
|
||||||
'resolved_hash' => $resolvedHash,
|
'resolved_hash' => $resolvedHash,
|
||||||
|
'structure_hash' => $structureHash,
|
||||||
'confirmed_by' => $confirmedBy?->id,
|
'confirmed_by' => $confirmedBy?->id,
|
||||||
'confirmed_at' => now(),
|
'confirmed_at' => now(),
|
||||||
'note' => $note,
|
'note' => $note,
|
||||||
]);
|
]);
|
||||||
$version->resolved_hash = $resolvedHash;
|
$version->resolved_hash = $resolvedHash;
|
||||||
|
$version->structure_hash = $structureHash;
|
||||||
$version->status = ContentVersionStatus::Bereit;
|
$version->status = ContentVersionStatus::Bereit;
|
||||||
$version->save();
|
$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
|
public function createComposition(string $designation, CompositionKind $kind = CompositionKind::Uebung): Composition
|
||||||
{
|
{
|
||||||
return Composition::query()->create([
|
return Composition::query()->create([
|
||||||
@@ -345,6 +471,10 @@ private function assertAcyclic(int $compositionId, array $members, array $stack
|
|||||||
|
|
||||||
private function assertReadyMember(ContentElementVersion|CompositionVersion $target): void
|
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) {
|
if ($target->status !== ContentVersionStatus::Bereit) {
|
||||||
throw new DomainRuleException('Eine Komposition darf nur bereitgestellte Fassungen enthalten.');
|
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),
|
'note' => $this->optionalText($member['note'] ?? null),
|
||||||
'element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
'element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
||||||
'composition_version_id' => $target instanceof CompositionVersion ? $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 = [
|
public const CONTEXTS = [
|
||||||
'medium' => 'Medium',
|
'medium' => 'Medium',
|
||||||
'modul' => 'Modul',
|
'modul' => 'Modul',
|
||||||
|
'uebung' => 'Übung',
|
||||||
'programm' => 'Programm',
|
'programm' => 'Programm',
|
||||||
'lizenzartikel' => 'Lizenzartikel',
|
'lizenzartikel' => 'Lizenzartikel',
|
||||||
];
|
];
|
||||||
@@ -26,7 +27,7 @@ class EditorialContentKind extends Model
|
|||||||
* Modulen (programm, modul), Vertraulichkeit von Traineranleitungen (traineranleitung). Ihre Bezeichnung bleibt
|
* Modulen (programm, modul), Vertraulichkeit von Traineranleitungen (traineranleitung). Ihre Bezeichnung bleibt
|
||||||
* pflegbar; deaktivieren, Kontexte ändern und löschen sind gesperrt.
|
* 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 = [
|
protected $fillable = [
|
||||||
'slug',
|
'slug',
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ public static function compositionContext(?CompositionKind $kind): ?string
|
|||||||
return match ($kind) {
|
return match ($kind) {
|
||||||
CompositionKind::Kurs => 'programm',
|
CompositionKind::Kurs => 'programm',
|
||||||
CompositionKind::Uebung => 'modul',
|
CompositionKind::Uebung => 'modul',
|
||||||
|
CompositionKind::Exercise => 'uebung',
|
||||||
default => null,
|
default => null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -137,6 +138,7 @@ private function usedKindIds(string $context): array
|
|||||||
'lizenzartikel' => DB::table('license_articles'),
|
'lizenzartikel' => DB::table('license_articles'),
|
||||||
'programm' => DB::table('compositions')->where('kind', CompositionKind::Kurs->value),
|
'programm' => DB::table('compositions')->where('kind', CompositionKind::Kurs->value),
|
||||||
'modul' => DB::table('compositions')->where('kind', CompositionKind::Uebung->value),
|
'modul' => DB::table('compositions')->where('kind', CompositionKind::Uebung->value),
|
||||||
|
'uebung' => DB::table('compositions')->where('kind', CompositionKind::Exercise->value),
|
||||||
default => null,
|
default => null,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -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,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)',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,8 +12,16 @@ class Offer extends Model
|
|||||||
'name',
|
'name',
|
||||||
'composition_id',
|
'composition_id',
|
||||||
'option_label',
|
'option_label',
|
||||||
|
'standalone_bundle',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'standalone_bundle' => 'boolean',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */
|
/** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */
|
||||||
public function composition(): BelongsTo
|
public function composition(): BelongsTo
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,6 +6,27 @@ class OfferCoverage
|
|||||||
{
|
{
|
||||||
public function __construct(private readonly ContentResolver $resolver) {}
|
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
|
* @param list<LicenseArticle> $articles
|
||||||
* @return list<string>
|
* @return list<string>
|
||||||
|
|||||||
@@ -102,10 +102,18 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
|||||||
'dynamic' => false,
|
'dynamic' => false,
|
||||||
'grant_kind' => 'kauf',
|
'grant_kind' => 'kauf',
|
||||||
'holder_kind' => 'person',
|
'holder_kind' => 'person',
|
||||||
|
'licence_scope' => null,
|
||||||
|
'trainer_count' => null,
|
||||||
], $attributes);
|
], $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);
|
$this->assertAttributes($attributes);
|
||||||
|
[$attributes['licence_scope'], $attributes['trainer_count']] = LicenceScope::normalise($attributes['licence_scope'], $attributes['trainer_count']);
|
||||||
$scope = $this->scopeFor($lines);
|
$scope = $this->scopeFor($lines);
|
||||||
|
$this->assertSellableContent($scope);
|
||||||
$this->assertCoverage($lines, $attributes);
|
$this->assertCoverage($lines, $attributes);
|
||||||
|
|
||||||
return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion {
|
return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion {
|
||||||
@@ -126,6 +134,8 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
|||||||
'dynamic' => $attributes['dynamic'],
|
'dynamic' => $attributes['dynamic'],
|
||||||
'grant_kind' => $attributes['grant_kind'],
|
'grant_kind' => $attributes['grant_kind'],
|
||||||
'holder_kind' => $attributes['holder_kind'],
|
'holder_kind' => $attributes['holder_kind'],
|
||||||
|
'licence_scope' => $attributes['licence_scope'],
|
||||||
|
'trainer_count' => $attributes['trainer_count'],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
foreach (array_values($lines) as $index => $line) {
|
foreach (array_values($lines) as $index => $line) {
|
||||||
@@ -176,13 +186,18 @@ public function end(Offer $offer): OfferVersion
|
|||||||
* Produktzuordnung der Option: Die Komposition bestimmt die öffentliche Produktseite und die Alternativgruppe,
|
* 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.
|
* die Bezeichnung benennt die Option auf dieser Seite. Beides sind keine bindenden Konditionen.
|
||||||
*/
|
*/
|
||||||
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel): Offer
|
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel, bool $ownBundlePage = false): Offer
|
||||||
{
|
{
|
||||||
if ($compositionId !== null) {
|
if ($compositionId !== null) {
|
||||||
Composition::query()->findOrFail($compositionId);
|
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->composition_id = $compositionId;
|
||||||
|
$offer->standalone_bundle = $ownBundlePage;
|
||||||
$offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null;
|
$offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null;
|
||||||
$offer->save();
|
$offer->save();
|
||||||
|
|
||||||
@@ -219,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
|
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
||||||
* @return list<array{license_article_id: int, rights_profile_version_id: int}>
|
* @return list<array{license_article_id: int, rights_profile_version_id: int}>
|
||||||
@@ -236,6 +277,10 @@ private function assertCoverage(array $lines, array $attributes): void
|
|||||||
}
|
}
|
||||||
|
|
||||||
$version = CompositionVersion::query()->findOrFail($versionId);
|
$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 = [];
|
$articles = [];
|
||||||
|
|
||||||
foreach ($lines as $line) {
|
foreach ($lines as $line) {
|
||||||
@@ -244,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);
|
$missing = app(OfferCoverage::class)->missingLeaves($version, $articles);
|
||||||
|
|
||||||
if ($missing !== []) {
|
if ($missing !== []) {
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ class OfferVersion extends Model
|
|||||||
'dynamic',
|
'dynamic',
|
||||||
'grant_kind',
|
'grant_kind',
|
||||||
'holder_kind',
|
'holder_kind',
|
||||||
|
'licence_scope',
|
||||||
|
'trainer_count',
|
||||||
'activated_at',
|
'activated_at',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ class ReleaseContent extends Model
|
|||||||
'content_element_version_id',
|
'content_element_version_id',
|
||||||
'role',
|
'role',
|
||||||
'path',
|
'path',
|
||||||
|
'requirement',
|
||||||
|
'variant_key',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected static function booted(): void
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -70,9 +70,9 @@ public function narrowBehavior(): string
|
|||||||
public function heights(): array
|
public function heights(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'compact' => 'Kompakt (mind. 400 px)',
|
'compact' => 'Kompakt (niedriger, 75 % der Standardhöhe)',
|
||||||
'normal' => 'Normal (mind. 512 px)',
|
'normal' => 'Standard',
|
||||||
'large' => 'Groß (mind. 640 px)',
|
'large' => 'Großzügig (höher, 130 % der Standardhöhe)',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,10 +115,18 @@ public function settings(): array
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function settingGroups(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'Aussehen' => ['accent'],
|
||||||
|
'Seitenstruktur' => ['heading_level'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
public function settingLabels(): array
|
public function settingLabels(): array
|
||||||
{
|
{
|
||||||
return [
|
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.'],
|
'accent' => ['Markenakzent', 'Freigegebene Akzente aus dem Brand-UI-Kit. Vorgabe: gelbe Unterstreichung.'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ public function heights(): array
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'compact' => 'Kompakt (flacheres Bild, engere Abstände)',
|
'compact' => 'Kompakt (flacheres Bild, engere Abstände)',
|
||||||
'normal' => 'Normal',
|
'normal' => 'Standard',
|
||||||
'spacious' => 'Großzügig (höheres Bild, mehr Abstand)',
|
'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
|
public function settingLabels(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'],
|
'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.'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -107,20 +107,31 @@ protected function imageSourceFields(): array
|
|||||||
->view('filament.cms.filmbild-feld')
|
->view('filament.cms.filmbild-feld')
|
||||||
->dehydrated(false)
|
->dehydrated(false)
|
||||||
->visible(fn (Get $get): bool => $this->filmFor($get('element')) !== null)
|
->visible(fn (Get $get): bool => $this->filmFor($get('element')) !== null)
|
||||||
->viewData(function (Get $get): array {
|
->viewData(fn (Get $get): array => $this->filmFieldData($this->filmFor($get('element')))),
|
||||||
$film = $this->filmFor($get('element'));
|
];
|
||||||
$stills = app(FilmStill::class);
|
}
|
||||||
$version = $film instanceof ContentElement ? $stills->version($film) : null;
|
|
||||||
|
|
||||||
return [
|
/**
|
||||||
'film' => $film,
|
* Anzeigedaten des Felds „Bild aus dem Film“. Die Stelle kommt aus der bereitgestellten Fassung, bei einem Film
|
||||||
'filmTitle' => $film instanceof ContentElement ? (string) ($film->display_title ?: $film->working_title) : '',
|
* nur mit Website-Datei aus dieser (Route content.website-frame).
|
||||||
'filmVersionId' => $version?->id,
|
*
|
||||||
'filmHasThumbnail' => $film instanceof ContentElement && is_string($film->thumbnail_path) && $film->thumbnail_path !== '',
|
* @return array<string, mixed>
|
||||||
'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',
|
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',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -165,7 +165,7 @@ public function settings(): array
|
|||||||
{
|
{
|
||||||
$choices = $this->textChoices();
|
$choices = $this->textChoices();
|
||||||
|
|
||||||
return ($choices === [] ? [] : ['text_source' => $choices]) + ($this->supportsClip() ? ['clip' => ['yes' => 'Abspielen', 'no' => 'Nicht abspielen']] : []) + [
|
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'],
|
'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)'],
|
'fit' => ['cover' => 'Ausschnitt füllt die Fläche', 'contain' => 'Ganzes Bild zeigen (Dokument, Poster)'],
|
||||||
'heading_level' => ['h3' => 'H3', 'h2' => 'H2', 'h4' => 'H4'],
|
'heading_level' => ['h3' => 'H3', 'h2' => 'H2', 'h4' => 'H4'],
|
||||||
@@ -176,18 +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
|
public function settingLabels(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'text_source' => ['Text der Karte', 'Welche Angabe aus der Redaktion die Karte zeigt. Vorgabe: Automatisch. Der gewählte Text erscheint öffentlich, wenn die Karte öffentlich ist; ist er nicht gepflegt, bleibt die Karte ohne Text.'],
|
'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.'],
|
||||||
'clip' => ['Trailer auf der Karte', 'Spielt den freigegebenen Trailer stumm ab, solange die Maus auf der Karte steht; am Handy mit Tippen auf das Bild, per Tastatur über die Schaltfläche am Bild. 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.'],
|
'fit' => ['Bildausschnitt', 'Ausschnitt füllt die ganze Fläche; „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche. Vorgabe: Ausschnitt.'],
|
||||||
'format' => ['Bildformat', 'Vorgabe: Querformat 16:9. Gilt auch neben dem Text; das Motiv wird nicht nachträglich hochkant beschnitten.'],
|
'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.'],
|
||||||
'fit' => ['Bilddarstellung', 'Vorgabe: Ausschnitt. „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche.'],
|
'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.'],
|
||||||
'heading_level' => ['Überschriftenebene', 'Vorgabe: H3, passend unter einer Abschnittsüberschrift (H2).'],
|
'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' => ['Text anzeigen', 'Aus den Fachdaten. Vorgabe: anzeigen.'],
|
'show_summary' => ['Beschreibung', 'Der Beschreibungstext unter dem Titel, aus den Fachdaten. Vorgabe: Anzeigen.'],
|
||||||
'show_kind' => ['Art oder Label', 'Zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: anzeigen.'],
|
'show_kind' => ['Art-Label', 'Kleines Label über dem Titel, zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: Anzeigen.'],
|
||||||
'show_meta' => ['Zusatzangaben', 'Aus den Fachdaten, zum Beispiel Ausgabeart oder Programmzugehörigkeit. Vorgabe: anzeigen.'],
|
'show_meta' => ['Zusatzangaben', 'Angaben 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.'],
|
'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).'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -348,6 +364,7 @@ public function resolve(array $widget, RenderContext $context): array
|
|||||||
'actionLabel' => filled($data['action_label'] ?? null) ? (string) $data['action_label'] : $this->defaultActionLabel(),
|
'actionLabel' => filled($data['action_label'] ?? null) ? (string) $data['action_label'] : $this->defaultActionLabel(),
|
||||||
'note' => filled($data['note'] ?? null) ? (string) $data['note'] : null,
|
'note' => filled($data['note'] ?? null) ? (string) $data['note'] : null,
|
||||||
'stacked' => $widget['variant'] === 'stacked',
|
'stacked' => $widget['variant'] === 'stacked',
|
||||||
|
'bare' => $this->supportsClip() && $option('show_body', 'yes') === 'no',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ public function version(): int
|
|||||||
public const HEIGHTS = [
|
public const HEIGHTS = [
|
||||||
'auto' => 'Automatisch',
|
'auto' => 'Automatisch',
|
||||||
'compact' => 'Kompakt',
|
'compact' => 'Kompakt',
|
||||||
'normal' => 'Normal',
|
'normal' => 'Standard',
|
||||||
'large' => 'Groß',
|
'large' => 'Groß',
|
||||||
'spacious' => 'Großzügig',
|
'spacious' => 'Großzügig',
|
||||||
'fill' => 'Abschnittshöhe füllen',
|
'fill' => 'Abschnittshöhe füllen',
|
||||||
@@ -194,6 +194,29 @@ public function settingLabels(): array
|
|||||||
return [];
|
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
|
* Alle zulässigen Einstellungen einschließlich der gemeinsamen Höhe. Registry-Prüfung, Editor und Darstellung
|
||||||
* verwenden ausschließlich diese Zusammenführung.
|
* verwenden ausschließlich diese Zusammenführung.
|
||||||
|
|||||||
@@ -6,6 +6,9 @@
|
|||||||
use App\Domain\Catalog\Offer;
|
use App\Domain\Catalog\Offer;
|
||||||
use App\Domain\Catalog\OfferService;
|
use App\Domain\Catalog\OfferService;
|
||||||
use App\Domain\Catalog\OfferVersion;
|
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\Party;
|
||||||
use App\Domain\Identity\PartyType;
|
use App\Domain\Identity\PartyType;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
@@ -20,6 +23,9 @@ class Cart
|
|||||||
{
|
{
|
||||||
public const KEY = 'shop.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 ADDED = 'added';
|
||||||
|
|
||||||
public const PRESENT = 'present';
|
public const PRESENT = 'present';
|
||||||
@@ -32,6 +38,7 @@ public function __construct(
|
|||||||
private readonly OwnershipCheck $ownership,
|
private readonly OwnershipCheck $ownership,
|
||||||
private readonly OrderHolders $holders,
|
private readonly OrderHolders $holders,
|
||||||
private readonly OfferService $offers,
|
private readonly OfferService $offers,
|
||||||
|
private readonly DiscountService $discounts,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -57,7 +64,10 @@ public function has(Offer $offer): bool
|
|||||||
*/
|
*/
|
||||||
public function alternativeTo(Offer $offer): ?Offer
|
public function alternativeTo(Offer $offer): ?Offer
|
||||||
{
|
{
|
||||||
if ($offer->composition_id === null) {
|
$products = app(ProductOptions::class);
|
||||||
|
$group = $products->groupKey($offer);
|
||||||
|
|
||||||
|
if ($group === null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,8 +75,8 @@ public function alternativeTo(Offer $offer): ?Offer
|
|||||||
|
|
||||||
return $ids === [] ? null : Offer::query()
|
return $ids === [] ? null : Offer::query()
|
||||||
->whereIn('id', $ids)
|
->whereIn('id', $ids)
|
||||||
->where('composition_id', $offer->composition_id)
|
->get()
|
||||||
->first();
|
->first(fn (Offer $other): bool => $products->groupKey($other) === $group);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function add(Offer $offer): string
|
public function add(Offer $offer): string
|
||||||
@@ -133,13 +143,51 @@ public function acceptCurrent(Offer $offer): void
|
|||||||
|
|
||||||
public function clear(): void
|
public function clear(): void
|
||||||
{
|
{
|
||||||
session()->forget(self::KEY);
|
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.
|
* Serverseitige Prüfung: aktuelle Fassung, Preis, Kaufbarkeit, passende Inhaberart, vorhandene Rechte.
|
||||||
*/
|
*/
|
||||||
public function review(?User $user = null, ?int $holderPartyId = null): CartReview
|
public function review(?User $user = null, ?int $holderPartyId = null, bool $lockDiscount = false): CartReview
|
||||||
{
|
{
|
||||||
$offers = Offer::query()
|
$offers = Offer::query()
|
||||||
->whereIn('id', array_keys($this->items()))
|
->whereIn('id', array_keys($this->items()))
|
||||||
@@ -203,7 +251,15 @@ public function review(?User $user = null, ?int $holderPartyId = null): CartRevi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new CartReview($lines, $holder);
|
$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);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -45,6 +45,14 @@ public function blocks(): bool
|
|||||||
|
|
||||||
public function title(): string
|
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;
|
$composition = $this->offer->composition;
|
||||||
|
|
||||||
return $composition !== null
|
return $composition !== null
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domain\Commerce;
|
namespace App\Domain\Commerce;
|
||||||
|
|
||||||
|
use App\Domain\Commerce\Discount\DiscountResult;
|
||||||
use App\Domain\Identity\Party;
|
use App\Domain\Identity\Party;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,6 +17,7 @@ final class CartReview
|
|||||||
public function __construct(
|
public function __construct(
|
||||||
public readonly array $lines,
|
public readonly array $lines,
|
||||||
public readonly ?Party $holder,
|
public readonly ?Party $holder,
|
||||||
|
public readonly ?DiscountResult $discount = null,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** @return list<CartLine> */
|
/** @return list<CartLine> */
|
||||||
@@ -24,11 +26,35 @@ public function orderable(): array
|
|||||||
return array_values(array_filter($this->lines, fn (CartLine $line): bool => $line->orderable()));
|
return array_values(array_filter($this->lines, fn (CartLine $line): bool => $line->orderable()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function totalCents(): int
|
/** 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()));
|
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
|
public function blocked(): bool
|
||||||
{
|
{
|
||||||
foreach ($this->lines as $line) {
|
foreach ($this->lines as $line) {
|
||||||
@@ -47,7 +73,7 @@ public function empty(): bool
|
|||||||
|
|
||||||
public function canOrder(): bool
|
public function canOrder(): bool
|
||||||
{
|
{
|
||||||
return $this->holder !== null && ! $this->blocked() && ! $this->empty();
|
return $this->holder !== null && ! $this->blocked() && ! $this->empty() && ! $this->discountBlocks();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function digest(): string
|
public function digest(): string
|
||||||
@@ -60,6 +86,6 @@ public function digest(): string
|
|||||||
|
|
||||||
sort($parts);
|
sort($parts);
|
||||||
|
|
||||||
return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts));
|
return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts).'|'.($this->discount?->digestPart() ?? '-'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,14 +6,18 @@
|
|||||||
use App\Domain\Catalog\Offer;
|
use App\Domain\Catalog\Offer;
|
||||||
use App\Domain\Catalog\OfferService;
|
use App\Domain\Catalog\OfferService;
|
||||||
use App\Domain\Catalog\OfferVersion;
|
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\Acquisition;
|
||||||
use App\Domain\Entitlement\AcquisitionType;
|
use App\Domain\Entitlement\AcquisitionType;
|
||||||
use App\Domain\Entitlement\GrantIssuer;
|
use App\Domain\Entitlement\GrantIssuer;
|
||||||
use App\Domain\Entitlement\GrantStatus;
|
use App\Domain\Entitlement\GrantStatus;
|
||||||
use App\Domain\Identity\AccountStatus;
|
use App\Domain\Identity\AccountStatus;
|
||||||
use App\Domain\Identity\Party;
|
use App\Domain\Identity\Party;
|
||||||
|
use App\Domain\Identity\PartyType;
|
||||||
use App\Mail\OrderConfirmed;
|
use App\Mail\OrderConfirmed;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use Carbon\CarbonInterface;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Mail;
|
use Illuminate\Support\Facades\Mail;
|
||||||
|
|
||||||
@@ -23,6 +27,7 @@ public function __construct(
|
|||||||
private readonly GrantIssuer $grants,
|
private readonly GrantIssuer $grants,
|
||||||
private readonly OfferService $offers,
|
private readonly OfferService $offers,
|
||||||
private readonly OrderHolders $holders,
|
private readonly OrderHolders $holders,
|
||||||
|
private readonly PaymentJournal $journal,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -32,6 +37,12 @@ public function place(User $user, Offer $offer): Order
|
|||||||
{
|
{
|
||||||
$this->assertActive($user);
|
$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);
|
$version = $this->offers->currentActiveVersion($offer);
|
||||||
|
|
||||||
if ($version->grant_kind !== 'kauf' || $version->holder_kind !== 'person') {
|
if ($version->grant_kind !== 'kauf' || $version->holder_kind !== 'person') {
|
||||||
@@ -44,7 +55,7 @@ public function place(User $user, Offer $offer): Order
|
|||||||
|
|
||||||
$holder = $this->holders->resolve($user, null);
|
$holder = $this->holders->resolve($user, null);
|
||||||
|
|
||||||
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]]));
|
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]], null, null, Shop::driver() === 'stripe' ? 'stripe' : 'test'));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -53,14 +64,25 @@ public function place(User $user, Offer $offer): Order
|
|||||||
* Bestellung und der Käufer sieht zuerst die aktualisierte Übersicht. Positionen, deren Umfang der Inhaber bereits
|
* Bestellung und der Käufer sieht zuerst die aktualisierte Übersicht. Positionen, deren Umfang der Inhaber bereits
|
||||||
* mit denselben Rechten besitzt, erzeugen keine Bestellposition.
|
* mit denselben Rechten besitzt, erzeugen keine Bestellposition.
|
||||||
*/
|
*/
|
||||||
public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, string $digest): Order
|
public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, string $digest, ?array $consent = null, ?string $paymentMethod = null): Order
|
||||||
{
|
{
|
||||||
$this->assertActive($user);
|
$this->assertActive($user);
|
||||||
|
|
||||||
$order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest): Order {
|
if ($consent === null && Shop::live()) {
|
||||||
// Optionen sperren, damit eine gleichzeitige Aktivierung die Prüfung nicht unterläuft.
|
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();
|
Offer::query()->whereIn('id', array_keys($cart->items()))->orderBy('id')->lockForUpdate()->get();
|
||||||
$review = $cart->review($user, $holderPartyId);
|
$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) {
|
if ($review->holder === null) {
|
||||||
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
|
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
|
||||||
@@ -78,9 +100,19 @@ public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, strin
|
|||||||
throw new DomainRuleException('Es gibt nichts zu bestellen. Alle Positionen sind bereits erworben.');
|
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());
|
$pairs = array_map(fn (CartLine $line): array => [$line->offer, $line->version], $review->orderable());
|
||||||
|
|
||||||
return $this->createOrder($user, $review->holder, $pairs);
|
return $this->createOrder($user, $review->holder, $pairs, $review, $consent === null ? null : SalesTerms::proof($consent), $method);
|
||||||
});
|
});
|
||||||
|
|
||||||
$cart->clear();
|
$cart->clear();
|
||||||
@@ -90,16 +122,28 @@ public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, strin
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param list<array{0: Offer, 1: OfferVersion}> $pairs
|
* @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): Order
|
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([
|
$order = Order::query()->create([
|
||||||
'user_id' => $user->id,
|
'user_id' => $user->id,
|
||||||
'party_id' => $holder->id,
|
'party_id' => $holder->id,
|
||||||
'status' => 'offen',
|
'status' => 'offen',
|
||||||
'holder_kind' => $holder->type->value,
|
'holder_kind' => $holder->type->value,
|
||||||
'total_cents' => array_sum(array_map(fn (array $pair): int => (int) $pair[1]->price_cents, $pairs)),
|
'subtotal_cents' => $subtotal,
|
||||||
|
'discount_cents' => $discountCents,
|
||||||
|
'total_cents' => $subtotal - $discountCents,
|
||||||
'currency' => 'EUR',
|
'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]) {
|
foreach ($pairs as [$offer, $version]) {
|
||||||
@@ -114,6 +158,9 @@ private function createOrder(User $user, Party $holder, array $pairs): Order
|
|||||||
'tax_class' => $version->tax_class,
|
'tax_class' => $version->tax_class,
|
||||||
'grant_kind' => $version->grant_kind,
|
'grant_kind' => $version->grant_kind,
|
||||||
'holder_party_id' => $holder->id,
|
'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');
|
$version->load('resolvedScopes.rights');
|
||||||
|
|
||||||
@@ -140,26 +187,49 @@ private function createOrder(User $user, Party $holder, array $pairs): Order
|
|||||||
public function confirmTestPayment(Order $order, string $reference): Order
|
public function confirmTestPayment(Order $order, string $reference): Order
|
||||||
{
|
{
|
||||||
$this->assertTestDriver();
|
$this->assertTestDriver();
|
||||||
|
$this->assertTestOrder($order);
|
||||||
|
|
||||||
return $this->settle($order, 'test', $reference);
|
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
|
* Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die
|
||||||
* Bestellung. Wiederholte Meldungen sind wirkungslos.
|
* 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): Order
|
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'));
|
$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'))) {
|
if ($amountCents !== $expected || strtoupper($currency) !== strtoupper((string) ($order->currency ?? 'EUR'))) {
|
||||||
throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.');
|
throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->settle($order, $provider, $reference);
|
return $this->settle($order, $provider, $reference, null, $occurredAt ?? now(), $live ?? Shop::live(), $paymentIntent);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function settle(Order $order, string $provider, string $reference): Order
|
/**
|
||||||
|
* 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);
|
$reference = trim($reference);
|
||||||
|
|
||||||
@@ -168,7 +238,7 @@ private function settle(Order $order, string $provider, string $reference): Orde
|
|||||||
}
|
}
|
||||||
|
|
||||||
$paidNow = false;
|
$paidNow = false;
|
||||||
$order = DB::transaction(function () use ($order, $provider, $reference, &$paidNow): Order {
|
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, $occurredAt, $live, $paymentIntent, &$paidNow): Order {
|
||||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||||
|
|
||||||
if ($order->status === 'bezahlt') {
|
if ($order->status === 'bezahlt') {
|
||||||
@@ -180,10 +250,14 @@ private function settle(Order $order, string $provider, string $reference): Orde
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
|
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
|
||||||
$order->payments()->updateOrCreate(
|
$payment = $order->payments()->updateOrCreate(
|
||||||
['provider_reference' => $reference],
|
['provider_reference' => $reference],
|
||||||
['provider' => $provider, 'status' => 'bestaetigt'],
|
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->status = 'bezahlt';
|
||||||
$order->save();
|
$order->save();
|
||||||
$paidNow = true;
|
$paidNow = true;
|
||||||
@@ -207,6 +281,7 @@ private function settle(Order $order, string $provider, string $reference): Orde
|
|||||||
public function failTestPayment(Order $order, string $reference): Order
|
public function failTestPayment(Order $order, string $reference): Order
|
||||||
{
|
{
|
||||||
$this->assertTestDriver();
|
$this->assertTestDriver();
|
||||||
|
$this->assertTestOrder($order);
|
||||||
|
|
||||||
return DB::transaction(function () use ($order, $reference): Order {
|
return DB::transaction(function () use ($order, $reference): Order {
|
||||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||||
@@ -229,9 +304,14 @@ public function failTestPayment(Order $order, string $reference): Order
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen
|
* Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen
|
||||||
* (kostenlose Vergabe, frühere Käufe) bleiben unberührt.
|
* (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): Order
|
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);
|
$reason = trim($reason);
|
||||||
|
|
||||||
@@ -239,7 +319,17 @@ public function refund(Order $order, string $reason): Order
|
|||||||
throw new DomainRuleException('Eine Erstattung braucht eine Begründung.');
|
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);
|
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||||
|
|
||||||
if ($order->status !== 'bezahlt') {
|
if ($order->status !== 'bezahlt') {
|
||||||
@@ -262,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->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']);
|
||||||
$order->status = 'erstattet';
|
$order->status = 'erstattet';
|
||||||
$order->save();
|
$order->save();
|
||||||
@@ -270,6 +370,28 @@ 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
|
private function assertActive(User $user): void
|
||||||
{
|
{
|
||||||
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
|
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
|
||||||
@@ -277,6 +399,14 @@ private function assertActive(User $user): void
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 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
|
private function assertTestDriver(): void
|
||||||
{
|
{
|
||||||
if (app()->isProduction() || config('services.payment.driver') !== 'test') {
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,8 +17,39 @@ class Order extends Model
|
|||||||
'holder_kind',
|
'holder_kind',
|
||||||
'total_cents',
|
'total_cents',
|
||||||
'currency',
|
'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
|
public function user(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(User::class);
|
return $this->belongsTo(User::class);
|
||||||
|
|||||||
@@ -22,8 +22,17 @@ class OrderLine extends Model
|
|||||||
'tax_class',
|
'tax_class',
|
||||||
'grant_kind',
|
'grant_kind',
|
||||||
'holder_party_id',
|
'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
|
public function order(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(Order::class);
|
return $this->belongsTo(Order::class);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Domain\Commerce;
|
namespace App\Domain\Commerce;
|
||||||
|
|
||||||
|
use App\Domain\Catalog\LicenceScope;
|
||||||
use App\Domain\Catalog\OfferVersion;
|
use App\Domain\Catalog\OfferVersion;
|
||||||
use App\Domain\Entitlement\Grant;
|
use App\Domain\Entitlement\Grant;
|
||||||
use App\Domain\Entitlement\GrantStatus;
|
use App\Domain\Entitlement\GrantStatus;
|
||||||
@@ -27,12 +28,23 @@ public function covers(Party $holder, OfferVersion $version): bool
|
|||||||
$byAcquisition = Grant::query()
|
$byAcquisition = Grant::query()
|
||||||
->where('status', GrantStatus::Aktiv)
|
->where('status', GrantStatus::Aktiv)
|
||||||
->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id))
|
->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id))
|
||||||
|
->with('acquisition')
|
||||||
->get()
|
->get()
|
||||||
->filter(fn (Grant $grant): bool => ($grant->valid_from === null || ! $grant->valid_from->greaterThan($now))
|
->filter(fn (Grant $grant): bool => ($grant->valid_from === null || ! $grant->valid_from->greaterThan($now))
|
||||||
&& ($grant->valid_until === null || $grant->valid_until->greaterThan($now)))
|
&& ($grant->valid_until === null || $grant->valid_until->greaterThan($now)))
|
||||||
->groupBy('acquisition_id');
|
->groupBy('acquisition_id');
|
||||||
|
|
||||||
|
$wanted = LicenceScope::key($version->licence_scope, $version->trainer_count);
|
||||||
|
|
||||||
foreach ($byAcquisition as $grants) {
|
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 = [];
|
$have = [];
|
||||||
|
|
||||||
foreach ($grants as $grant) {
|
foreach ($grants as $grant) {
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ class Payment extends Model
|
|||||||
'provider',
|
'provider',
|
||||||
'status',
|
'status',
|
||||||
'provider_reference',
|
'provider_reference',
|
||||||
|
'provider_payment_ref',
|
||||||
|
'amount_cents',
|
||||||
|
'confirmed_by',
|
||||||
];
|
];
|
||||||
|
|
||||||
public function order(): BelongsTo
|
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(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,8 +2,10 @@
|
|||||||
|
|
||||||
namespace App\Domain\Commerce;
|
namespace App\Domain\Commerce;
|
||||||
|
|
||||||
|
use App\Domain\Catalog\Bundle;
|
||||||
use App\Domain\Catalog\Composition;
|
use App\Domain\Catalog\Composition;
|
||||||
use App\Domain\Catalog\EditorialProfileReader;
|
use App\Domain\Catalog\EditorialProfileReader;
|
||||||
|
use App\Domain\Catalog\LicenceScope;
|
||||||
use App\Domain\Catalog\LicenseArticle;
|
use App\Domain\Catalog\LicenseArticle;
|
||||||
use App\Domain\Catalog\Offer;
|
use App\Domain\Catalog\Offer;
|
||||||
use App\Domain\Catalog\OfferService;
|
use App\Domain\Catalog\OfferService;
|
||||||
@@ -37,6 +39,125 @@ public function forComposition(Composition $composition): array
|
|||||||
return $options;
|
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.
|
* Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option.
|
||||||
*
|
*
|
||||||
@@ -89,18 +210,28 @@ public function describe(Offer $offer, OfferVersion $version): array
|
|||||||
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
|
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
|
||||||
'holder_kind' => $version->holder_kind,
|
'holder_kind' => $version->holder_kind,
|
||||||
'term' => self::termLabel($version),
|
'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,
|
'scope' => $scope,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function termLabel(OfferVersion $version): string
|
public static function termLabel(OfferVersion $version): string
|
||||||
{
|
{
|
||||||
return match ($version->term_rule) {
|
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',
|
'dauerhaft' => 'Dauerhaft nutzbar',
|
||||||
'befristet' => 'Befristet',
|
'befristet' => 'Befristet',
|
||||||
'solange_angebot_aktiv' => 'Solange das Angebot aktiv ist',
|
'solange_angebot_aktiv' => 'Solange das Angebot aktiv ist',
|
||||||
'periodisch' => 'Laufend, periodisch',
|
'periodisch' => 'Laufend, periodisch',
|
||||||
default => (string) $version->term_rule,
|
default => (string) $rule,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,9 +3,12 @@
|
|||||||
namespace App\Domain\Commerce;
|
namespace App\Domain\Commerce;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Etappe 1 verwendet ausschließlich Testzahlung und erteilt keine Produktivfreigabe. Der Shop (Warenkorb, Kasse,
|
* Wann der Shop (Warenkorb, Kasse, Kopflink) aktiv ist.
|
||||||
* Kopflink) ist deshalb nur aktiv, wenn die Umgebung nicht Produktion ist und der Zahlungstreiber „test“ gilt.
|
*
|
||||||
* Dieselbe Bedingung gilt für die Testzahlung der Bestellseite.
|
* 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
|
final class Shop
|
||||||
{
|
{
|
||||||
@@ -14,14 +17,45 @@ public static function driver(): string
|
|||||||
return (string) config('services.payment.driver');
|
return (string) config('services.payment.driver');
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function enabled(): bool
|
/** Produktivbetrieb ist freigegeben und vollständig vorbereitet (Freigabe, Live-Schlüssel, Rechtstexte). */
|
||||||
|
public static function live(): bool
|
||||||
{
|
{
|
||||||
return ! app()->isProduction() && in_array(self::driver(), ['test', 'stripe'], true);
|
return app()->isProduction()
|
||||||
|
&& config('shop.live_release') === true
|
||||||
|
&& self::driver() === 'stripe'
|
||||||
|
&& self::liveKey()
|
||||||
|
&& SalesTerms::missingPages() === [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Stripe-Kasse (Etappe 1: nur Testmodus, nie in Produktion). */
|
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
|
public static function stripe(): bool
|
||||||
{
|
{
|
||||||
return ! app()->isProduction() && self::driver() === 'stripe';
|
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_');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,11 @@
|
|||||||
namespace App\Domain\Commerce\Stripe;
|
namespace App\Domain\Commerce\Stripe;
|
||||||
|
|
||||||
use App\Domain\Catalog\DomainRuleException;
|
use App\Domain\Catalog\DomainRuleException;
|
||||||
|
use App\Domain\Commerce\Money;
|
||||||
use App\Domain\Commerce\Order;
|
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\ConnectionException;
|
||||||
use Illuminate\Http\Client\PendingRequest;
|
use Illuminate\Http\Client\PendingRequest;
|
||||||
use Illuminate\Http\Client\Response;
|
use Illuminate\Http\Client\Response;
|
||||||
@@ -11,9 +15,11 @@
|
|||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stripe-Kasse (Checkout Session) für die Testzahlung in Etappe 1. Ausschließlich Testschlüssel: Ein Live-Schlüssel
|
* Stripe-Kasse (Checkout Session). Außerhalb der Produktion nur mit Testschlüsseln; ein Live-Schlüssel wird dort
|
||||||
* oder die Produktionsumgebung werden abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten
|
* abgewiesen. In Produktion nur nach der Produktivfreigabe (Shop::live) und nur mit Live-Schlüssel; in jedem anderen
|
||||||
* berühren diese Anwendung nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook).
|
* 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
|
class StripeGateway
|
||||||
{
|
{
|
||||||
@@ -24,7 +30,7 @@ class StripeGateway
|
|||||||
*/
|
*/
|
||||||
public function checkoutFor(Order $order): array
|
public function checkoutFor(Order $order): array
|
||||||
{
|
{
|
||||||
$this->assertSandbox();
|
$this->assertAllowed();
|
||||||
$order->loadMissing('lines', 'user');
|
$order->loadMissing('lines', 'user');
|
||||||
$taxRate = $this->taxRate();
|
$taxRate = $this->taxRate();
|
||||||
|
|
||||||
@@ -32,6 +38,10 @@ public function checkoutFor(Order $order): array
|
|||||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
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);
|
$open = $this->reusableSession($order);
|
||||||
|
|
||||||
if ($open !== null) {
|
if ($open !== null) {
|
||||||
@@ -51,12 +61,18 @@ public function checkoutFor(Order $order): array
|
|||||||
];
|
];
|
||||||
|
|
||||||
foreach ($order->lines->values() as $index => $line) {
|
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] = [
|
$params['line_items'][$index] = [
|
||||||
'quantity' => 1,
|
'quantity' => 1,
|
||||||
'price_data' => [
|
'price_data' => [
|
||||||
'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')),
|
'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')),
|
||||||
'unit_amount' => (int) $line->price_cents,
|
'unit_amount' => $line->payable(),
|
||||||
'product_data' => ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'],
|
'product_data' => $productData,
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -66,7 +82,7 @@ public function checkoutFor(Order $order): array
|
|||||||
}
|
}
|
||||||
|
|
||||||
$response = $this->request()
|
$response = $this->request()
|
||||||
->withHeaders(['Idempotency-Key' => 'luf-order-'.$order->id.'-'.$attempt])
|
->withHeaders(['Idempotency-Key' => $this->idempotencyKey($order, $attempt, $params)])
|
||||||
->post('/v1/checkout/sessions', $params);
|
->post('/v1/checkout/sessions', $params);
|
||||||
|
|
||||||
$this->assertOk($response, 'angelegt');
|
$this->assertOk($response, 'angelegt');
|
||||||
@@ -82,21 +98,93 @@ public function checkoutFor(Order $order): array
|
|||||||
return ['id' => $id, 'url' => $url];
|
return ['id' => $id, 'url' => $url];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function assertSandbox(): void
|
public function assertAllowed(): void
|
||||||
{
|
{
|
||||||
$secret = (string) config('services.stripe.secret');
|
$secret = (string) config('services.stripe.secret');
|
||||||
|
|
||||||
if (app()->isProduction()) {
|
|
||||||
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($secret === '') {
|
if ($secret === '') {
|
||||||
throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.');
|
throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) {
|
if (app()->isProduction()) {
|
||||||
throw new DomainRuleException('Etappe 1 erlaubt nur den Stripe-Testmodus (Schlüssel sk_test_).');
|
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. */
|
/** Konfigurierter Steuersatz oder null; eine ungültige ID wird abgewiesen, statt geraten zu werden. */
|
||||||
|
|||||||
@@ -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'];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -101,6 +101,10 @@ public function issueFromOrderLine(OrderLine $line, Party $holder, User $actor):
|
|||||||
'update_promise' => $line->update_promise,
|
'update_promise' => $line->update_promise,
|
||||||
'holder_kind' => $line->holder_kind,
|
'holder_kind' => $line->holder_kind,
|
||||||
'offer_version_id' => $line->offer_version_id,
|
'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,
|
||||||
],
|
],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -150,6 +154,8 @@ public function issue(
|
|||||||
'update_promise' => $version->update_promise,
|
'update_promise' => $version->update_promise,
|
||||||
'holder_kind' => $version->holder_kind,
|
'holder_kind' => $version->holder_kind,
|
||||||
'offer_version_id' => $version->id,
|
'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',
|
'copy_id',
|
||||||
'checksum',
|
'checksum',
|
||||||
'marking',
|
'marking',
|
||||||
|
'composition_version_id',
|
||||||
'delivered_at',
|
'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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,11 @@ public function user(): HasOne
|
|||||||
return $this->hasOne(User::class);
|
return $this->hasOne(User::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function billingAddress(): HasOne
|
||||||
|
{
|
||||||
|
return $this->hasOne(BillingAddress::class);
|
||||||
|
}
|
||||||
|
|
||||||
public function profile(): HasOne
|
public function profile(): HasOne
|
||||||
{
|
{
|
||||||
return $this->hasOne(Profile::class);
|
return $this->hasOne(Profile::class);
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ public function write(
|
|||||||
string $format,
|
string $format,
|
||||||
?string $checksum,
|
?string $checksum,
|
||||||
string $marking,
|
string $marking,
|
||||||
|
?string $copyId = null,
|
||||||
|
?int $compositionVersionId = null,
|
||||||
): MediaDelivery {
|
): MediaDelivery {
|
||||||
return MediaDelivery::query()->create([
|
return MediaDelivery::query()->create([
|
||||||
'grant_id' => $grant->id,
|
'grant_id' => $grant->id,
|
||||||
@@ -27,10 +29,16 @@ public function write(
|
|||||||
'content_element_version_id' => $version->id,
|
'content_element_version_id' => $version->id,
|
||||||
'action' => $action,
|
'action' => $action,
|
||||||
'format' => $format,
|
'format' => $format,
|
||||||
'copy_id' => 'LK-'.strtoupper(bin2hex(random_bytes(6))),
|
'copy_id' => $copyId ?? self::newCopyId(),
|
||||||
|
'composition_version_id' => $compositionVersionId,
|
||||||
'checksum' => $checksum,
|
'checksum' => $checksum,
|
||||||
'marking' => $marking,
|
'marking' => $marking,
|
||||||
'delivered_at' => now(),
|
'delivered_at' => now(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static function newCopyId(): string
|
||||||
|
{
|
||||||
|
return 'LK-'.strtoupper(bin2hex(random_bytes(6)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,8 @@
|
|||||||
/**
|
/**
|
||||||
* Legt ein Bild aus einem Film als gewöhnliches Bild-Medium im Medienmanager ab (Medien- und Materialkarte).
|
* 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
|
* - 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.
|
* 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
|
* - Das Bild wird einmal gezogen und gespeichert (WebsiteIntake legt es an, die Warteschlange leitet es ab und gibt
|
||||||
@@ -65,6 +67,23 @@ public function version(ContentElement $film): ?ContentElementVersion
|
|||||||
->first();
|
->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. */
|
/** Sekunde der Stelle, aus der das aktuelle Vorschaubild des Films stammt, sonst null. */
|
||||||
public function thumbnailSecond(ContentElement $film): ?string
|
public function thumbnailSecond(ContentElement $film): ?string
|
||||||
{
|
{
|
||||||
@@ -85,7 +104,11 @@ public function fromSecond(ContentElement $film, float $seconds, ?User $actor =
|
|||||||
$version = $this->version($film);
|
$version = $this->version($film);
|
||||||
|
|
||||||
if (! $version instanceof ContentElementVersion) {
|
if (! $version instanceof ContentElementVersion) {
|
||||||
throw new DomainRuleException('Der Film hat noch keine bereitgestellte Fassung.');
|
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);
|
return $this->fromFrame($film, $version, $seconds, $actor);
|
||||||
@@ -158,6 +181,27 @@ private function fromFrame(ContentElement $film, ContentElementVersion $version,
|
|||||||
return $this->store($film, $key, $bytes, 'Fassung '.$version->number.', '.str_replace('.', ',', $second).' s', $actor);
|
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
|
private function guard(ContentElement $film): void
|
||||||
{
|
{
|
||||||
$refusal = $this->refusal($film);
|
$refusal = $this->refusal($film);
|
||||||
|
|||||||
@@ -215,6 +215,15 @@ public function frameJpeg(ContentElementVersion $version, float $seconds, int $w
|
|||||||
* Einzelbild aus der Website-Datei eines Films (`teaser/`), für Medien ohne Inhaltsfassung.
|
* Einzelbild aus der Website-Datei eines Films (`teaser/`), für Medien ohne Inhaltsfassung.
|
||||||
*/
|
*/
|
||||||
public function jpegAtWebsiteFile(ContentElement $element, float $seconds): ?string
|
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;
|
$file = $element->preview_path;
|
||||||
|
|
||||||
@@ -222,7 +231,7 @@ public function jpegAtWebsiteFile(ContentElement $element, float $seconds): ?str
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->jpegFromFile($file, $seconds, 640);
|
return $this->jpegFromFile($file, $seconds, $width);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function jpegFromFile(string $file, float $seconds, int $width): ?string
|
private function jpegFromFile(string $file, float $seconds, int $width): ?string
|
||||||
|
|||||||
@@ -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(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Pages;
|
||||||
|
|
||||||
|
use App\Domain\Commerce\SalesTerms;
|
||||||
|
use App\Domain\Commerce\Shop;
|
||||||
|
use App\Filament\Support\ShopAccess;
|
||||||
|
use Filament\Pages\Page;
|
||||||
|
use Filament\Support\Enums\Width;
|
||||||
|
use Illuminate\Contracts\Support\Htmlable;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verkaufsstart: Was ist bereit, was fehlt noch? Die Seite liest nur. Sie nennt die fehlenden Rechtstexte, den
|
||||||
|
* Zustand der Zahlungseinrichtung und der Produktivfreigabe, ohne Schlüssel oder Werte zu zeigen. Die Produktivfreigabe
|
||||||
|
* ist eine Entscheidung von Lars und wird nicht hier, sondern in der Umgebungsdatei des Servers gesetzt.
|
||||||
|
*/
|
||||||
|
class Verkaufsstart extends Page
|
||||||
|
{
|
||||||
|
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||||
|
|
||||||
|
protected static ?string $navigationLabel = 'Verkaufsstart';
|
||||||
|
|
||||||
|
protected static ?int $navigationSort = 3;
|
||||||
|
|
||||||
|
protected static ?string $slug = 'verkaufsstart';
|
||||||
|
|
||||||
|
protected static ?string $title = 'Verkaufsstart';
|
||||||
|
|
||||||
|
protected string $view = 'filament.pages.verkaufsstart';
|
||||||
|
|
||||||
|
public static function canAccess(): bool
|
||||||
|
{
|
||||||
|
return ShopAccess::allowed();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getHeading(): string|Htmlable|null
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getMaxContentWidth(): Width|string|null
|
||||||
|
{
|
||||||
|
return Width::Full;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function daten(): array
|
||||||
|
{
|
||||||
|
$legal = [];
|
||||||
|
|
||||||
|
foreach (SalesTerms::pages() as $key => $definition) {
|
||||||
|
$page = SalesTerms::page($key);
|
||||||
|
$legal[] = [
|
||||||
|
'text' => $definition['label'],
|
||||||
|
'neben' => $page === null
|
||||||
|
? 'Fehlt: Es gibt keine veröffentlichte Seite unter '.implode(' oder ', $definition['paths']).'. Die Seite pflegst du in der Webpräsenz; den Text liefert die Rechtsberatung.'
|
||||||
|
: 'Veröffentlicht unter '.$page->path.'. Inhalt und Vollständigkeit prüft die Rechtsberatung.',
|
||||||
|
'zustand' => $page === null ? ['label' => 'Fehlt', 'ton' => 'offen'] : ['label' => 'Veröffentlicht', 'ton' => 'gut'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$secret = (string) config('services.stripe.secret');
|
||||||
|
$mode = match (true) {
|
||||||
|
$secret === '' => 'nicht eingerichtet',
|
||||||
|
str_starts_with($secret, 'sk_test_'), str_starts_with($secret, 'rk_test_') => 'Testmodus',
|
||||||
|
str_starts_with($secret, 'sk_live_'), str_starts_with($secret, 'rk_live_') => 'Live-Schlüssel',
|
||||||
|
default => 'unbekanntes Format',
|
||||||
|
};
|
||||||
|
$withoutScope = DB::table('offer_versions')->where('status', 'aktiv')->where('grant_kind', 'kauf')->whereNull('licence_scope')->count();
|
||||||
|
|
||||||
|
$zahlung = [
|
||||||
|
['text' => 'Zahlungsweg: '.Shop::driver(), 'neben' => 'Test: Testzahlung ohne Anbieter. Stripe: Kasse bei Stripe.', 'zustand' => Shop::driver() === 'stripe' ? ['label' => 'Stripe', 'ton' => 'gut'] : ['label' => 'Test', 'ton' => 'neutral']],
|
||||||
|
['text' => 'Stripe-Schlüssel: '.$mode, 'neben' => 'Der Schlüssel steht nur in der Umgebungsdatei des Servers und wird hier nie angezeigt.', 'zustand' => $mode === 'nicht eingerichtet' ? ['label' => 'Fehlt', 'ton' => 'offen'] : ['label' => $mode, 'ton' => 'neutral']],
|
||||||
|
['text' => 'Signaturschlüssel für Stripe-Meldungen: '.(filled(config('services.stripe.webhook_secret')) ? 'gesetzt' : 'fehlt'), 'neben' => 'Ohne ihn weist die Anwendung jede Meldung von Stripe ab; Zahlungen schalten dann nichts frei.', 'zustand' => filled(config('services.stripe.webhook_secret')) ? ['label' => 'Gesetzt', 'ton' => 'gut'] : ['label' => 'Fehlt', 'ton' => 'offen']],
|
||||||
|
['text' => 'Steuersatz bei Stripe: '.(filled(config('services.stripe.tax_rate')) ? 'hinterlegt' : 'nicht hinterlegt'), 'neben' => 'Steuerstatus und Belegangaben sind noch nicht entschieden (OPEN-06). Ohne sie gibt es keinen Steuerausweis auf der Stripe-Kasse und keine Rechnungsvorlage.', 'zustand' => filled(config('services.stripe.tax_rate')) ? ['label' => 'Hinterlegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
|
||||||
|
['text' => 'Aussteller auf dem Zahlungsbeleg: '.(filled(config('shop.receipt.issuer')) ? 'gepflegt' : 'nicht gepflegt'), 'neben' => 'Mitglieder laden zu jeder Zahlung einen Beleg (PDF) herunter. Er nennt den Aussteller nur, wenn er mit SHOP_RECEIPT_ISSUER gepflegt ist (Zeilen durch „|“ getrennt). Name und Anschrift des Verkäufers, Steuerangaben und eine Rechnungsnummer hängen an der rechtlichen Klärung (OPEN-06); bis dahin trägt der Beleg keine steuerlichen Angaben.', 'zustand' => filled(config('shop.receipt.issuer')) ? ['label' => 'Gepflegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
|
||||||
|
['text' => 'Kauf auf Rechnung für Vereine: '.(Shop::invoice() ? 'angeboten' : 'aus'), 'neben' => Shop::invoice()
|
||||||
|
? 'Die Rechnung erstellt der Betreiber manuell; den Zahlungseingang bestätigst du in der Bestellverwaltung. Vereine sehen die Möglichkeit im Checkout.'
|
||||||
|
: 'Mitglieder sehen die Möglichkeit nicht. Sie wird erst angeboten, wenn der Prozess vollständig ist: Rechnungserstellung mit Nummernkreis, Benachrichtigung des Betreibers bei neuer Rechnungsbestellung und die rechtliche Klärung (OPEN-06). Die Umsetzung ist vorbereitet; schaltest du sie mit SHOP_INVOICE=true in der Umgebungsdatei ein, erscheint sie im Checkout. Bereits angelegte Rechnungsbestellungen bleiben in der Bestellverwaltung bearbeitbar.',
|
||||||
|
'zustand' => Shop::invoice() ? ['label' => 'Angeboten', 'ton' => 'neutral'] : ['label' => 'Aus', 'ton' => 'neutral']],
|
||||||
|
];
|
||||||
|
|
||||||
|
$freigabe = [
|
||||||
|
['text' => 'Produktivfreigabe (SHOP_LIVE_RELEASE): '.(config('shop.live_release') === true ? 'gesetzt' : 'nicht gesetzt'), 'neben' => 'Standardmäßig aus. Setzt Lars in der Umgebungsdatei des Servers, wenn er den Verkauf freigibt. Ohne sie bleibt der Shop in Produktion abgeschaltet und Stripe nimmt dort keine Zahlung an.', 'zustand' => config('shop.live_release') === true ? ['label' => 'Gesetzt', 'ton' => 'gut'] : ['label' => 'Aus', 'ton' => 'neutral']],
|
||||||
|
['text' => 'Umgebung: '.(app()->isProduction() ? 'Produktion' : 'Test oder lokal'), 'neben' => app()->isProduction() ? 'Der Shop ist hier '.(Shop::enabled() ? 'aktiv.' : 'abgeschaltet.') : 'Hier läuft der Shop mit Test- oder Sandbox-Zahlung.', 'zustand' => app()->isProduction() ? (Shop::enabled() ? ['label' => 'Live', 'ton' => 'gut'] : ['label' => 'Abgeschaltet', 'ton' => 'neutral']) : ['label' => 'Test', 'ton' => 'neutral']],
|
||||||
|
];
|
||||||
|
|
||||||
|
$angebote = [
|
||||||
|
['text' => $withoutScope === 0 ? 'Alle aktiven Käufe haben einen Nutzerkreis.' : $withoutScope.' aktive Kaufangebote ohne festgelegten Nutzerkreis', 'neben' => $withoutScope === 0 ? null : 'Käufer sähen „Nutzerkreis nicht festgelegt“. Lege Einzel- oder Mehrfachlizenz mit „Geänderte Fassung aktivieren“ am Angebot fest.', 'zustand' => $withoutScope === 0 ? ['label' => 'Vollständig', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
|
||||||
|
];
|
||||||
|
|
||||||
|
return [
|
||||||
|
'kopf' => [
|
||||||
|
'titel' => 'Verkaufsstart',
|
||||||
|
'typ' => 'Bereitschaft für den Verkauf in Deutschland',
|
||||||
|
'status' => ['text' => SalesTerms::missingPages() === [] ? 'Alle Rechtstexte sind veröffentlicht. Die rechtliche Freigabe der Inhalte steht aus, bis die Rechtsberatung sie bestätigt.' : 'Es fehlen veröffentlichte Rechtstexte. Ohne sie bleibt der Shop in Produktion abgeschaltet.', 'ton' => SalesTerms::missingPages() === [] ? 'gut' : 'offen'],
|
||||||
|
],
|
||||||
|
'haupt' => [
|
||||||
|
['titel' => 'Rechtstexte im Bestellablauf', 'hilfe' => 'Der Checkout verlinkt diese Seiten und hält mit jeder Bestellung fest, welche Fassung galt. Den Wortlaut der Zustimmungen im Checkout hat der Betreiber noch rechtlich zu prüfen (Entwurf '.SalesTerms::VERSION.').', 'zeilen' => $legal],
|
||||||
|
['titel' => 'Zahlung und Belege', 'zeilen' => $zahlung],
|
||||||
|
],
|
||||||
|
'seite' => [
|
||||||
|
['titel' => 'Freigabe', 'zeilen' => $freigabe, 'hilfe' => 'Die Produktivfreigabe liegt bei Lars. Sie wird nicht über diese Oberfläche gesetzt.'],
|
||||||
|
['titel' => 'Angebote', 'zeilen' => $angebote],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Pages;
|
||||||
|
|
||||||
|
use App\Domain\Catalog\Offer;
|
||||||
|
use App\Domain\Commerce\LedgerEntry;
|
||||||
|
use App\Domain\Commerce\PaymentJournal;
|
||||||
|
use App\Filament\Support\ShopAccess;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Filament\Pages\Page;
|
||||||
|
use Filament\Support\Enums\Width;
|
||||||
|
use Illuminate\Contracts\Support\Htmlable;
|
||||||
|
use Livewire\Attributes\Url;
|
||||||
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Einnahmen und Erstattungen (Zahlungsjournal): Jede Geldbewegung steht unveränderlich mit Datum, Betrag, Beleg beim
|
||||||
|
* Anbieter, handelnder Person, Begründung und Zahler da. Die Seite liest nur; es gibt nichts zu bearbeiten oder zu
|
||||||
|
* löschen. Standardmäßig zählen nur echte Zahlungen; Testzahlungen sind ein eigener Filter und fließen nie in die
|
||||||
|
* Summen echter Einnahmen. Der Export (CSV) enthält alle Zeilen des gewählten Zeitraums und Filters.
|
||||||
|
*/
|
||||||
|
class Zahlungsjournal extends Page
|
||||||
|
{
|
||||||
|
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||||
|
|
||||||
|
protected static ?string $navigationLabel = 'Einnahmen und Erstattungen';
|
||||||
|
|
||||||
|
protected static ?int $navigationSort = 2;
|
||||||
|
|
||||||
|
protected static ?string $slug = 'zahlungsjournal';
|
||||||
|
|
||||||
|
protected static ?string $title = 'Einnahmen und Erstattungen';
|
||||||
|
|
||||||
|
protected string $view = 'filament.pages.zahlungsjournal';
|
||||||
|
|
||||||
|
#[Url(as: 'zeitraum')]
|
||||||
|
public string $modus = 'monat';
|
||||||
|
|
||||||
|
#[Url(as: 'jahr')]
|
||||||
|
public ?int $jahr = null;
|
||||||
|
|
||||||
|
#[Url(as: 'nr')]
|
||||||
|
public ?int $nr = null;
|
||||||
|
|
||||||
|
#[Url(as: 'art')]
|
||||||
|
public string $art = 'alle';
|
||||||
|
|
||||||
|
#[Url(as: 'weg')]
|
||||||
|
public string $weg = 'alle';
|
||||||
|
|
||||||
|
/** Ohne Angabe: auf Prod die echten Zahlungen, auf jeder anderen Instanz (Test, lokal) die Testzahlungen. */
|
||||||
|
#[Url(as: 'betrieb')]
|
||||||
|
public ?string $betrieb = null;
|
||||||
|
|
||||||
|
/** Kennung eines Angebots oder leer für alle (Zeichenkette, damit die Auswahl „Alle“ leer sein kann). */
|
||||||
|
#[Url(as: 'angebot')]
|
||||||
|
public string $angebot = '';
|
||||||
|
|
||||||
|
public static function canAccess(): bool
|
||||||
|
{
|
||||||
|
return ShopAccess::allowed();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getHeading(): string|Htmlable|null
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getMaxContentWidth(): Width|string|null
|
||||||
|
{
|
||||||
|
return Width::Full;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function mount(): void
|
||||||
|
{
|
||||||
|
$now = CarbonImmutable::now(PaymentJournal::TIMEZONE);
|
||||||
|
$this->jahr ??= $now->year;
|
||||||
|
$this->nr ??= $this->modus === 'quartal' ? $now->quarter : $now->month;
|
||||||
|
$this->betrieb ??= self::defaultBetrieb();
|
||||||
|
$this->normalize();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nur Prod zeigt standardmäßig echte Zahlungen; auf anderen Instanzen entstehen Buchungen nur aus der Sandbox. */
|
||||||
|
public static function defaultBetrieb(): string
|
||||||
|
{
|
||||||
|
return app()->isProduction() ? 'echt' : 'test';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Beim Wechsel zwischen Monat und Quartal bleibt der gewählte Zeitraum erhalten. */
|
||||||
|
public function updatingModus(string $value): void
|
||||||
|
{
|
||||||
|
if ($this->modus === 'monat' && $value === 'quartal') {
|
||||||
|
$this->nr = (int) ceil(((int) $this->nr) / 3);
|
||||||
|
} elseif ($this->modus === 'quartal' && $value === 'monat') {
|
||||||
|
$this->nr = (((int) $this->nr) - 1) * 3 + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updated(): void
|
||||||
|
{
|
||||||
|
$this->normalize();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ungültige Eingaben aus der Adresszeile fallen auf zulässige Werte zurück. */
|
||||||
|
private function normalize(): void
|
||||||
|
{
|
||||||
|
$this->modus = in_array($this->modus, ['monat', 'quartal', 'jahr'], true) ? $this->modus : 'monat';
|
||||||
|
$this->art = in_array($this->art, ['alle', LedgerEntry::KIND_PAYMENT, LedgerEntry::KIND_REFUND], true) ? $this->art : 'alle';
|
||||||
|
$this->weg = in_array($this->weg, ['alle', 'stripe', 'ueberweisung', 'test'], true) ? $this->weg : 'alle';
|
||||||
|
$this->betrieb = in_array($this->betrieb, ['echt', 'test', 'alle'], true) ? $this->betrieb : self::defaultBetrieb();
|
||||||
|
$this->angebot = ctype_digit($this->angebot) && Offer::query()->whereKey((int) $this->angebot)->exists() ? $this->angebot : '';
|
||||||
|
$this->jahr = max(2020, min((int) CarbonImmutable::now(PaymentJournal::TIMEZONE)->year + 1, (int) ($this->jahr ?? 2026)));
|
||||||
|
$max = $this->modus === 'quartal' ? 4 : 12;
|
||||||
|
$this->nr = max(1, min($max, (int) ($this->nr ?? 1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{0: CarbonImmutable, 1: CarbonImmutable}
|
||||||
|
*/
|
||||||
|
private function range(): array
|
||||||
|
{
|
||||||
|
return PaymentJournal::range($this->modus, (int) $this->jahr, (int) $this->nr);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function zeitraumName(): string
|
||||||
|
{
|
||||||
|
$months = [1 => 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
|
||||||
|
|
||||||
|
return match ($this->modus) {
|
||||||
|
'monat' => $months[(int) $this->nr].' '.$this->jahr,
|
||||||
|
'quartal' => $this->nr.'. Quartal '.$this->jahr,
|
||||||
|
default => 'Jahr '.$this->jahr,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function daten(): array
|
||||||
|
{
|
||||||
|
[$from, $to] = $this->range();
|
||||||
|
$journal = app(PaymentJournal::class);
|
||||||
|
$offerId = $this->angebot === '' ? null : (int) $this->angebot;
|
||||||
|
$entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId);
|
||||||
|
$shares = $offerId === null ? null : $journal->shares($entries, $offerId);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'zeitraum' => $this->zeitraumName(),
|
||||||
|
'eintraege' => $entries->take(PaymentJournal::DISPLAY_LIMIT),
|
||||||
|
'anzahl' => $entries->count(),
|
||||||
|
'angebote' => Offer::query()->orderBy('name')->pluck('name', 'id')->all(),
|
||||||
|
'angebotName' => $offerId === null ? null : Offer::query()->find($offerId)?->name,
|
||||||
|
'anteile' => $shares,
|
||||||
|
'summen' => PaymentJournal::totals($entries, $shares),
|
||||||
|
'nachBetrieb' => $journal->countByOperation($from, $to),
|
||||||
|
'ohneAdresse' => $entries->filter(fn (LedgerEntry $entry): bool => $entry->kind === LedgerEntry::KIND_PAYMENT && empty(($entry->payer ?? [])['billing']))->count(),
|
||||||
|
'nachgetragen' => $entries->where('derived', true)->count(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function exportieren(): StreamedResponse
|
||||||
|
{
|
||||||
|
abort_unless(ShopAccess::allowed(), 403);
|
||||||
|
|
||||||
|
[$from, $to] = $this->range();
|
||||||
|
$journal = app(PaymentJournal::class);
|
||||||
|
$offerId = $this->angebot === '' ? null : (int) $this->angebot;
|
||||||
|
$entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId);
|
||||||
|
$shares = $offerId === null ? null : $journal->shares($entries, $offerId);
|
||||||
|
$name = 'zahlungsjournal-'.match ($this->modus) {
|
||||||
|
'monat' => $this->jahr.'-'.str_pad((string) $this->nr, 2, '0', STR_PAD_LEFT),
|
||||||
|
'quartal' => $this->jahr.'-Q'.$this->nr,
|
||||||
|
default => (string) $this->jahr,
|
||||||
|
}.'-'.match ($this->betrieb) {
|
||||||
|
'echt' => 'echt', 'test' => 'test', default => 'alle'
|
||||||
|
}.($offerId === null ? '' : '-angebot-'.$offerId).'.csv';
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($entries, $shares): void {
|
||||||
|
echo PaymentJournal::csv($entries, $shares);
|
||||||
|
}, $name, ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@
|
|||||||
use App\Domain\Catalog\DomainRuleException;
|
use App\Domain\Catalog\DomainRuleException;
|
||||||
use App\Domain\Catalog\EditorialVocabulary;
|
use App\Domain\Catalog\EditorialVocabulary;
|
||||||
use App\Domain\Catalog\EditorialWorkingDraft;
|
use App\Domain\Catalog\EditorialWorkingDraft;
|
||||||
|
use App\Domain\Catalog\ForeignCompositions;
|
||||||
use App\Domain\Catalog\IdentityDimension;
|
use App\Domain\Catalog\IdentityDimension;
|
||||||
use App\Domain\Catalog\IdentityDimensionValue;
|
use App\Domain\Catalog\IdentityDimensionValue;
|
||||||
use App\Domain\Catalog\IdentityProfile;
|
use App\Domain\Catalog\IdentityProfile;
|
||||||
@@ -39,6 +40,7 @@
|
|||||||
use Filament\Support\Exceptions\Halt;
|
use Filament\Support\Exceptions\Halt;
|
||||||
use Illuminate\Contracts\Support\Htmlable;
|
use Illuminate\Contracts\Support\Htmlable;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||||
use Livewire\WithFileUploads;
|
use Livewire\WithFileUploads;
|
||||||
|
|
||||||
@@ -68,6 +70,15 @@ abstract class EditComposition extends EditRecord
|
|||||||
|
|
||||||
public string $materialNote = '';
|
public string $materialNote = '';
|
||||||
|
|
||||||
|
/** @var list<array{key: string, name: string, description: string}> Durchführungsvarianten einer Übung */
|
||||||
|
public array $variants = [];
|
||||||
|
|
||||||
|
public string $durationMax = '';
|
||||||
|
|
||||||
|
public string $prerequisites = '';
|
||||||
|
|
||||||
|
public string $newVariantName = '';
|
||||||
|
|
||||||
public string $revisionNote = '';
|
public string $revisionNote = '';
|
||||||
|
|
||||||
public string $search = '';
|
public string $search = '';
|
||||||
@@ -489,8 +500,173 @@ public function cancelText(): void
|
|||||||
$this->newTextBody = '';
|
$this->newTextBody = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function isExercise(): bool
|
||||||
|
{
|
||||||
|
return $this->hostKind() === CompositionKind::Exercise;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function addVariant(): void
|
||||||
|
{
|
||||||
|
$name = trim($this->newVariantName);
|
||||||
|
|
||||||
|
if ($name === '') {
|
||||||
|
$this->feedback = 'Eine Variante braucht einen Namen.';
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$base = Str::slug($name) ?: 'variante';
|
||||||
|
$key = $base;
|
||||||
|
$n = 2;
|
||||||
|
|
||||||
|
while (in_array($key, array_column($this->variants, 'key'), true)) {
|
||||||
|
$key = $base.'-'.$n++;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->variants[] = ['key' => $key, 'name' => $name, 'description' => '', 'origin' => 'lokal'];
|
||||||
|
$this->newVariantName = '';
|
||||||
|
$this->feedback = 'Variante „'.$name.'“ ist angelegt. Ordne ihr Bestandteile zu. Gespeichert wird mit „Entwurf speichern“.';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function removeVariant(string $key): void
|
||||||
|
{
|
||||||
|
foreach ($this->members as $member) {
|
||||||
|
if (($member['variant'] ?? null) === $key) {
|
||||||
|
$this->feedback = 'Diese Variante hat noch Bestandteile. Ordne sie zuerst einer anderen Variante oder dem gemeinsamen Teil zu.';
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->variants = array_values(array_filter($this->variants, fn (array $variant): bool => $variant['key'] !== $key));
|
||||||
|
$this->feedback = 'Die Variante ist aus diesem Entwurf genommen. Eine freigegebene Fassung bleibt unverändert.';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setMemberVariant(int $index, string $key): void
|
||||||
|
{
|
||||||
|
if (! isset($this->members[$index])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->members[$index]['variant'] = $key === '' ? null : $key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setMemberRequirement(int $index, string $requirement): void
|
||||||
|
{
|
||||||
|
if (! isset($this->members[$index]) || ! in_array($requirement, ['erforderlich', 'ergaenzend'], true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->members[$index]['requirement'] = $requirement;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Angebotene Varianten der eingebundenen Übungsfassung. Ohne Auswahl werden alle angeboten.
|
||||||
|
*/
|
||||||
|
public function toggleVariantSelection(int $index, string $key): void
|
||||||
|
{
|
||||||
|
if (! isset($this->members[$index])) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$all = array_column($this->offeredVariants((string) ($this->members[$index]['target'] ?? '')), 'key');
|
||||||
|
$current = $this->members[$index]['selection'] ?? null;
|
||||||
|
$current = is_array($current) ? $current : $all;
|
||||||
|
$current = in_array($key, $current, true) ? array_values(array_diff($current, [$key])) : [...$current, $key];
|
||||||
|
|
||||||
|
if ($current === []) {
|
||||||
|
$this->feedback = 'Mindestens eine Variante muss angeboten werden.';
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->members[$index]['selection'] = count($current) === count($all) ? null : array_values($current);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<array{key: string, name: string}>
|
||||||
|
*/
|
||||||
|
public function offeredVariants(string $target): array
|
||||||
|
{
|
||||||
|
if (preg_match('/^composition:(\d+)$/', $target, $match) !== 1) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return CompositionVersion::query()->find((int) $match[1])?->variants
|
||||||
|
->map(fn ($variant): array => ['key' => $variant->key, 'name' => $variant->name])
|
||||||
|
->all() ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $member
|
||||||
|
* @return array{variant: string|null, requirement: string, selection: list<string>|null, origin: string}
|
||||||
|
*/
|
||||||
|
private function memberExtras(array $member): array
|
||||||
|
{
|
||||||
|
$selection = $member['selection'] ?? null;
|
||||||
|
|
||||||
|
return [
|
||||||
|
'variant' => isset($member['variant']) && $member['variant'] !== '' ? (string) $member['variant'] : null,
|
||||||
|
'requirement' => ($member['requirement'] ?? 'erforderlich') === 'ergaenzend' ? 'ergaenzend' : 'erforderlich',
|
||||||
|
'selection' => is_array($selection) && $selection !== [] ? array_values(array_map('strval', $selection)) : null,
|
||||||
|
'origin' => ($member['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return list<array{key: string, name: string, description: string}>
|
||||||
|
*/
|
||||||
|
private function normalizeVariants(mixed $variants): array
|
||||||
|
{
|
||||||
|
$result = [];
|
||||||
|
|
||||||
|
foreach (is_array($variants) ? $variants : [] as $variant) {
|
||||||
|
if (is_array($variant) && trim((string) ($variant['key'] ?? '')) !== '') {
|
||||||
|
$result[] = [
|
||||||
|
'key' => trim((string) $variant['key']),
|
||||||
|
'name' => trim((string) ($variant['name'] ?? '')),
|
||||||
|
'description' => trim((string) ($variant['description'] ?? '')),
|
||||||
|
'origin' => ($variant['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rückfallschutz: Enthält dieser Aufbau (in einer Fassung oder im Entwurf) einen Bestandteil, den dieser Programmstand
|
||||||
|
* nicht kennt, bleibt er schreibgeschützt. Der Editor könnte den Bestandteil sonst nicht laden und würde ihn beim
|
||||||
|
* Speichern oder Freigeben still weglassen.
|
||||||
|
*/
|
||||||
|
public function schreibschutz(): ?string
|
||||||
|
{
|
||||||
|
$foreign = app(ForeignCompositions::class);
|
||||||
|
$reason = 'Dieser Aufbau enthält einen Bestandteil aus einer neueren Programmversion. Er kann hier nur angesehen werden, damit nichts verloren geht.';
|
||||||
|
|
||||||
|
if ($foreign->compositionHasForeignMembers((int) $this->getRecord()->getKey())) {
|
||||||
|
return $reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
$draft = app(EditorialWorkingDraft::class)->read($this->getRecord());
|
||||||
|
|
||||||
|
foreach (is_array($draft['members'] ?? null) ? $draft['members'] : [] as $member) {
|
||||||
|
if (is_array($member) && $foreign->isForeignTarget((string) ($member['target'] ?? ''))) {
|
||||||
|
return $reason;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
public function saveDraft(): void
|
public function saveDraft(): void
|
||||||
{
|
{
|
||||||
|
if (($reason = $this->schreibschutz()) !== null) {
|
||||||
|
$this->feedback = $reason;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
$this->commitRoleDraft();
|
$this->commitRoleDraft();
|
||||||
$minutes = $this->minutes($this->durationMinutes);
|
$minutes = $this->minutes($this->durationMinutes);
|
||||||
|
|
||||||
@@ -508,6 +684,13 @@ public function saveDraft(): void
|
|||||||
|
|
||||||
public function armRelease(): void
|
public function armRelease(): void
|
||||||
{
|
{
|
||||||
|
if (($reason = $this->schreibschutz()) !== null) {
|
||||||
|
$this->releaseArmed = false;
|
||||||
|
$this->feedback = $reason;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
$this->commitRoleDraft();
|
$this->commitRoleDraft();
|
||||||
|
|
||||||
if ($this->members === []) {
|
if ($this->members === []) {
|
||||||
@@ -585,6 +768,12 @@ protected function selectFirstPart(): void
|
|||||||
|
|
||||||
public function discardDraft(): void
|
public function discardDraft(): void
|
||||||
{
|
{
|
||||||
|
if (($reason = $this->schreibschutz()) !== null) {
|
||||||
|
$this->feedback = $reason;
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
/** @var Composition $record */
|
/** @var Composition $record */
|
||||||
$record = $this->getRecord();
|
$record = $this->getRecord();
|
||||||
app(EditorialWorkingDraft::class)->clear($record);
|
app(EditorialWorkingDraft::class)->clear($record);
|
||||||
@@ -924,7 +1113,7 @@ private function includePart(string $target, bool $allowDraft): bool
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($this->members as $index => $member) {
|
foreach ($this->isExercise() ? [] : $this->members as $index => $member) {
|
||||||
if (($member['target'] ?? '') === $target) {
|
if (($member['target'] ?? '') === $target) {
|
||||||
$this->selected = $index;
|
$this->selected = $index;
|
||||||
$this->panel = 'bestandteil';
|
$this->panel = 'bestandteil';
|
||||||
@@ -944,6 +1133,7 @@ private function includePart(string $target, bool $allowDraft): bool
|
|||||||
|
|
||||||
$row['role'] = app(EditorialCatalog::class)->defaultRole((string) $row['kind']);
|
$row['role'] = app(EditorialCatalog::class)->defaultRole((string) $row['kind']);
|
||||||
$row['note'] = '';
|
$row['note'] = '';
|
||||||
|
$row = [...$row, ...$this->memberExtras([])];
|
||||||
$this->members[] = $row;
|
$this->members[] = $row;
|
||||||
$this->members = array_values($this->members);
|
$this->members = array_values($this->members);
|
||||||
$this->selected = array_key_last($this->members);
|
$this->selected = array_key_last($this->members);
|
||||||
@@ -1034,6 +1224,7 @@ public function useVersion(int $index, string $target): void
|
|||||||
$this->commitRoleDraft();
|
$this->commitRoleDraft();
|
||||||
$row['role'] = $this->members[$index]['role'] ?? $row['kind'];
|
$row['role'] = $this->members[$index]['role'] ?? $row['kind'];
|
||||||
$row['note'] = $this->members[$index]['note'] ?? '';
|
$row['note'] = $this->members[$index]['note'] ?? '';
|
||||||
|
$row = [...$row, ...$this->memberExtras($this->members[$index])];
|
||||||
$this->members[$index] = $row;
|
$this->members[$index] = $row;
|
||||||
$this->syncRoleDraft();
|
$this->syncRoleDraft();
|
||||||
$this->feedback = $row['version_label'].' ist für diese Stelle ausgewählt. Der Entwurf speichert das. Eine freigegebene Fassung bleibt unverändert.';
|
$this->feedback = $row['version_label'].' ist für diese Stelle ausgewählt. Der Entwurf speichert das. Eine freigegebene Fassung bleibt unverändert.';
|
||||||
@@ -1521,6 +1712,12 @@ public function presentationChips(): array
|
|||||||
|
|
||||||
public function publishRevision(): bool
|
public function publishRevision(): bool
|
||||||
{
|
{
|
||||||
|
if (($reason = $this->schreibschutz()) !== null) {
|
||||||
|
$this->feedback = $reason;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$this->commitRoleDraft();
|
$this->commitRoleDraft();
|
||||||
|
|
||||||
if ($this->members === []) {
|
if ($this->members === []) {
|
||||||
@@ -1560,9 +1757,12 @@ public function publishRevision(): bool
|
|||||||
[
|
[
|
||||||
'learning_goal' => $this->blank($this->learningGoal),
|
'learning_goal' => $this->blank($this->learningGoal),
|
||||||
'duration_minutes' => $minutes,
|
'duration_minutes' => $minutes,
|
||||||
|
'duration_max' => $this->blank($this->durationMax),
|
||||||
'material_note' => $this->blank($this->materialNote),
|
'material_note' => $this->blank($this->materialNote),
|
||||||
|
'prerequisites' => $this->blank($this->prerequisites),
|
||||||
],
|
],
|
||||||
$this->releaseConsent,
|
$this->releaseConsent,
|
||||||
|
$this->normalizeVariants($this->variants),
|
||||||
);
|
);
|
||||||
} catch (DomainRuleException $exception) {
|
} catch (DomainRuleException $exception) {
|
||||||
$this->feedback = $exception->getMessage();
|
$this->feedback = $exception->getMessage();
|
||||||
@@ -1679,7 +1879,8 @@ protected function loadAufbau(): void
|
|||||||
$this->imageCaptionText = $this->captionFor($composition->thumbnail_source);
|
$this->imageCaptionText = $this->captionFor($composition->thumbnail_source);
|
||||||
$this->catalogScope = match ($this->hostKind()) {
|
$this->catalogScope = match ($this->hostKind()) {
|
||||||
CompositionKind::Kurs => 'module',
|
CompositionKind::Kurs => 'module',
|
||||||
CompositionKind::Uebung => 'medien',
|
CompositionKind::Uebung => 'uebungen',
|
||||||
|
CompositionKind::Exercise => 'medien',
|
||||||
default => 'alles',
|
default => 'alles',
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1693,6 +1894,9 @@ protected function loadAufbau(): void
|
|||||||
|
|
||||||
if ($version === null) {
|
if ($version === null) {
|
||||||
$this->members = [];
|
$this->members = [];
|
||||||
|
$this->variants = [];
|
||||||
|
$this->durationMax = '';
|
||||||
|
$this->prerequisites = '';
|
||||||
$this->learningGoal = '';
|
$this->learningGoal = '';
|
||||||
$this->durationMinutes = '';
|
$this->durationMinutes = '';
|
||||||
$this->materialNote = '';
|
$this->materialNote = '';
|
||||||
@@ -1726,10 +1930,14 @@ protected function applyDraft(array $draft): void
|
|||||||
|
|
||||||
$row['role'] = (string) ($member['role'] ?? $row['kind']);
|
$row['role'] = (string) ($member['role'] ?? $row['kind']);
|
||||||
$row['note'] = trim((string) ($member['note'] ?? ''));
|
$row['note'] = trim((string) ($member['note'] ?? ''));
|
||||||
|
$row = [...$row, ...$this->memberExtras($member)];
|
||||||
$rows[] = $row;
|
$rows[] = $row;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->members = $rows;
|
$this->members = $rows;
|
||||||
|
$this->variants = $this->normalizeVariants($draft['variants'] ?? []);
|
||||||
|
$this->durationMax = ($draft['duration_max'] ?? null) === null ? '' : (string) $draft['duration_max'];
|
||||||
|
$this->prerequisites = (string) ($draft['prerequisites'] ?? '');
|
||||||
$this->learningGoal = (string) ($draft['learning_goal'] ?? '');
|
$this->learningGoal = (string) ($draft['learning_goal'] ?? '');
|
||||||
$this->durationMinutes = ($draft['duration_minutes'] ?? null) === null ? '' : (string) $draft['duration_minutes'];
|
$this->durationMinutes = ($draft['duration_minutes'] ?? null) === null ? '' : (string) $draft['duration_minutes'];
|
||||||
$this->materialNote = (string) ($draft['material_note'] ?? '');
|
$this->materialNote = (string) ($draft['material_note'] ?? '');
|
||||||
@@ -1747,6 +1955,11 @@ protected function applyDraft(array $draft): void
|
|||||||
protected function applyVersion(CompositionVersion $version): void
|
protected function applyVersion(CompositionVersion $version): void
|
||||||
{
|
{
|
||||||
$this->members = app(EditorialCatalog::class)->rows($version, (int) $this->getRecord()->getKey());
|
$this->members = app(EditorialCatalog::class)->rows($version, (int) $this->getRecord()->getKey());
|
||||||
|
$this->variants = $this->normalizeVariants($version->variants->map(fn ($variant): array => [
|
||||||
|
'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description,
|
||||||
|
])->all());
|
||||||
|
$this->durationMax = $version->duration_max === null ? '' : (string) $version->duration_max;
|
||||||
|
$this->prerequisites = (string) ($version->prerequisites ?? '');
|
||||||
$this->learningGoal = (string) ($version->learning_goal ?? '');
|
$this->learningGoal = (string) ($version->learning_goal ?? '');
|
||||||
$this->durationMinutes = $version->duration_minutes === null ? '' : (string) $version->duration_minutes;
|
$this->durationMinutes = $version->duration_minutes === null ? '' : (string) $version->duration_minutes;
|
||||||
$this->materialNote = (string) ($version->material_note ?? '');
|
$this->materialNote = (string) ($version->material_note ?? '');
|
||||||
@@ -1833,18 +2046,21 @@ protected function needsRevision(): bool
|
|||||||
|
|
||||||
protected function sameMembers(CompositionVersion $version): bool
|
protected function sameMembers(CompositionVersion $version): bool
|
||||||
{
|
{
|
||||||
$version->loadMissing('members');
|
$version->loadMissing('members.variant');
|
||||||
$current = $version->members->map(function ($member): string {
|
$current = $version->members->map(function ($member): string {
|
||||||
$target = $member->content_element_version_id
|
$target = $member->content_element_version_id
|
||||||
? 'element:'.$member->content_element_version_id
|
? 'element:'.$member->content_element_version_id
|
||||||
: 'composition:'.$member->nested_composition_version_id;
|
: 'composition:'.$member->nested_composition_version_id;
|
||||||
|
|
||||||
return $member->role.'|'.$target.'|'.trim((string) ($member->placement_note ?? ''));
|
return $member->role.'|'.$target.'|'.trim((string) ($member->placement_note ?? ''))
|
||||||
|
.'|'.($member->variant?->key ?? '').'|'.($member->requirement ?: 'erforderlich').'|'.json_encode($member->variant_selection);
|
||||||
})->all();
|
})->all();
|
||||||
$next = array_values(array_map(
|
$next = array_values(array_map(function (array $member): string {
|
||||||
fn (array $member): string => trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? '').'|'.trim((string) ($member['note'] ?? '')),
|
$extras = $this->memberExtras($member);
|
||||||
$this->members,
|
|
||||||
));
|
return trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? '').'|'.trim((string) ($member['note'] ?? ''))
|
||||||
|
.'|'.($extras['variant'] ?? '').'|'.$extras['requirement'].'|'.json_encode($extras['selection']);
|
||||||
|
}, $this->members));
|
||||||
|
|
||||||
return $current === $next;
|
return $current === $next;
|
||||||
}
|
}
|
||||||
@@ -1859,8 +2075,15 @@ protected function didacticChanged(CompositionVersion $version): bool
|
|||||||
|
|
||||||
$storedMinutes = $version->duration_minutes === null ? null : (int) $version->duration_minutes;
|
$storedMinutes = $version->duration_minutes === null ? null : (int) $version->duration_minutes;
|
||||||
|
|
||||||
|
$storedVariants = $this->normalizeVariants($version->variants->map(fn ($variant): array => [
|
||||||
|
'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description,
|
||||||
|
])->all());
|
||||||
|
|
||||||
return $version->learning_goal !== $this->blank($this->learningGoal)
|
return $version->learning_goal !== $this->blank($this->learningGoal)
|
||||||
|| $version->material_note !== $this->blank($this->materialNote)
|
|| $version->material_note !== $this->blank($this->materialNote)
|
||||||
|
|| $version->prerequisites !== $this->blank($this->prerequisites)
|
||||||
|
|| ($version->duration_max === null ? null : (string) $version->duration_max) !== $this->blank($this->durationMax)
|
||||||
|
|| $storedVariants !== $this->normalizeVariants($this->variants)
|
||||||
|| $storedMinutes !== $minutes;
|
|| $storedMinutes !== $minutes;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1929,6 +2152,12 @@ protected function persistRedaktion(): bool
|
|||||||
|
|
||||||
protected function persistDraft(): bool
|
protected function persistDraft(): bool
|
||||||
{
|
{
|
||||||
|
if (($reason = $this->schreibschutz()) !== null) {
|
||||||
|
$this->feedback = $reason;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if ($this->minutes($this->durationMinutes) === false) {
|
if ($this->minutes($this->durationMinutes) === false) {
|
||||||
$this->feedback = 'Der Zeitbedarf ist eine Zahl von Minuten oder bleibt leer.';
|
$this->feedback = 'Der Zeitbedarf ist eine Zahl von Minuten oder bleibt leer.';
|
||||||
|
|
||||||
@@ -2065,12 +2294,16 @@ protected function payload(): array
|
|||||||
'learning_goal' => $this->blank($this->learningGoal),
|
'learning_goal' => $this->blank($this->learningGoal),
|
||||||
'duration_minutes' => $minutes === false ? $this->durationMinutes : $minutes,
|
'duration_minutes' => $minutes === false ? $this->durationMinutes : $minutes,
|
||||||
'material_note' => $this->blank($this->materialNote),
|
'material_note' => $this->blank($this->materialNote),
|
||||||
|
'duration_max' => $this->blank($this->durationMax),
|
||||||
|
'prerequisites' => $this->blank($this->prerequisites),
|
||||||
|
'variants' => $this->normalizeVariants($this->variants),
|
||||||
'revision_note' => $this->blank($this->revisionNote),
|
'revision_note' => $this->blank($this->revisionNote),
|
||||||
'members' => array_values(array_map(
|
'members' => array_values(array_map(
|
||||||
fn (array $member): array => [
|
fn (array $member): array => [
|
||||||
'role' => trim((string) ($member['role'] ?? '')),
|
'role' => trim((string) ($member['role'] ?? '')),
|
||||||
'target' => (string) ($member['target'] ?? ''),
|
'target' => (string) ($member['target'] ?? ''),
|
||||||
'note' => trim((string) ($member['note'] ?? '')),
|
'note' => trim((string) ($member['note'] ?? '')),
|
||||||
|
...$this->memberExtras($member),
|
||||||
],
|
],
|
||||||
$members,
|
$members,
|
||||||
)),
|
)),
|
||||||
@@ -2105,6 +2338,9 @@ protected function readyPayload(): array
|
|||||||
'learning_goal' => null,
|
'learning_goal' => null,
|
||||||
'duration_minutes' => null,
|
'duration_minutes' => null,
|
||||||
'material_note' => null,
|
'material_note' => null,
|
||||||
|
'duration_max' => null,
|
||||||
|
'prerequisites' => null,
|
||||||
|
'variants' => [],
|
||||||
'revision_note' => null,
|
'revision_note' => null,
|
||||||
'members' => [],
|
'members' => [],
|
||||||
];
|
];
|
||||||
@@ -2116,12 +2352,18 @@ protected function readyPayload(): array
|
|||||||
'learning_goal' => $version->learning_goal,
|
'learning_goal' => $version->learning_goal,
|
||||||
'duration_minutes' => $version->duration_minutes === null ? null : (int) $version->duration_minutes,
|
'duration_minutes' => $version->duration_minutes === null ? null : (int) $version->duration_minutes,
|
||||||
'material_note' => $version->material_note,
|
'material_note' => $version->material_note,
|
||||||
|
'duration_max' => $version->duration_max === null ? null : (string) $version->duration_max,
|
||||||
|
'prerequisites' => $version->prerequisites,
|
||||||
|
'variants' => $this->normalizeVariants($version->variants->map(fn ($variant): array => [
|
||||||
|
'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description, 'origin' => $variant->origin,
|
||||||
|
])->all()),
|
||||||
'revision_note' => null,
|
'revision_note' => null,
|
||||||
'members' => array_values(array_map(
|
'members' => array_values(array_map(
|
||||||
fn (array $row): array => [
|
fn (array $row): array => [
|
||||||
'role' => trim((string) ($row['role'] ?? '')),
|
'role' => trim((string) ($row['role'] ?? '')),
|
||||||
'target' => (string) ($row['target'] ?? ''),
|
'target' => (string) ($row['target'] ?? ''),
|
||||||
'note' => trim((string) ($row['note'] ?? '')),
|
'note' => trim((string) ($row['note'] ?? '')),
|
||||||
|
...$this->memberExtras($row),
|
||||||
],
|
],
|
||||||
$rows,
|
$rows,
|
||||||
)),
|
)),
|
||||||
@@ -2145,6 +2387,7 @@ protected function normalizePayload(array $payload): array
|
|||||||
'role' => trim((string) ($member['role'] ?? '')),
|
'role' => trim((string) ($member['role'] ?? '')),
|
||||||
'target' => (string) ($member['target'] ?? ''),
|
'target' => (string) ($member['target'] ?? ''),
|
||||||
'note' => trim((string) ($member['note'] ?? '')),
|
'note' => trim((string) ($member['note'] ?? '')),
|
||||||
|
...$this->memberExtras($member),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2152,6 +2395,9 @@ protected function normalizePayload(array $payload): array
|
|||||||
'learning_goal' => $payload['learning_goal'] ?? null,
|
'learning_goal' => $payload['learning_goal'] ?? null,
|
||||||
'duration_minutes' => $payload['duration_minutes'] ?? null,
|
'duration_minutes' => $payload['duration_minutes'] ?? null,
|
||||||
'material_note' => $payload['material_note'] ?? null,
|
'material_note' => $payload['material_note'] ?? null,
|
||||||
|
'duration_max' => isset($payload['duration_max']) && $payload['duration_max'] !== '' ? (string) $payload['duration_max'] : null,
|
||||||
|
'prerequisites' => $payload['prerequisites'] ?? null,
|
||||||
|
'variants' => $this->normalizeVariants($payload['variants'] ?? []),
|
||||||
'revision_note' => $payload['revision_note'] ?? null,
|
'revision_note' => $payload['revision_note'] ?? null,
|
||||||
'members' => $members,
|
'members' => $members,
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -33,12 +33,12 @@ protected function fixedKind(): ?CompositionKind
|
|||||||
|
|
||||||
private function onDesk(): bool
|
private function onDesk(): bool
|
||||||
{
|
{
|
||||||
return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung], true);
|
return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung, CompositionKind::Exercise], true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getSubheading(): string|Htmlable|null
|
public function getSubheading(): string|Htmlable|null
|
||||||
{
|
{
|
||||||
$desk = $this->onDesk() ? ' Programme und Module stehen gemeinsam auch auf dem Arbeitsplatz.' : '';
|
$desk = $this->onDesk() && $this->kind() !== CompositionKind::Exercise ? ' Programme und Module stehen gemeinsam auch auf dem Arbeitsplatz.' : '';
|
||||||
|
|
||||||
return $this->kind()->deskExplanation().$desk;
|
return $this->kind()->deskExplanation().$desk;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,6 +38,7 @@
|
|||||||
use Filament\Support\Enums\Width;
|
use Filament\Support\Enums\Width;
|
||||||
use Illuminate\Contracts\Support\Htmlable;
|
use Illuminate\Contracts\Support\Htmlable;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\Facades\Blade;
|
||||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||||
use Livewire\WithFileUploads;
|
use Livewire\WithFileUploads;
|
||||||
|
|
||||||
@@ -1046,18 +1047,20 @@ public function previewHtml(): string
|
|||||||
if ($this->previewSurface === 'bibliothek') {
|
if ($this->previewSurface === 'bibliothek') {
|
||||||
$title = trim($this->displayTitle) !== '' ? trim($this->displayTitle) : trim($this->workingTitle);
|
$title = trim($this->displayTitle) !== '' ? trim($this->displayTitle) : trim($this->workingTitle);
|
||||||
|
|
||||||
return view('member.partials.card', [
|
// Dieselbe Karte wie im Mitgliederbereich (<x-member.card>), ohne Verfügbarkeit: Die entscheidet die Lizenz.
|
||||||
'href' => '#vorschau',
|
return Blade::render('<x-member.card :card="$card" />', [
|
||||||
'card' => [
|
'card' => [
|
||||||
|
'type' => $element->output_class === 'film' ? 'film' : 'material',
|
||||||
|
'url' => '#vorschau',
|
||||||
'title' => $title !== '' ? $title : $element->working_title,
|
'title' => $title !== '' ? $title : $element->working_title,
|
||||||
'summary' => trim($this->summary) !== '' ? trim($this->summary) : null,
|
'summary' => trim($this->summary) !== '' ? trim($this->summary) : null,
|
||||||
'kind' => PublicMaterialReader::outputLabel((string) $element->output_class),
|
'kind' => PublicMaterialReader::outputLabel((string) $element->output_class),
|
||||||
'coverage' => 'offen',
|
'hide_status' => true,
|
||||||
'image' => trim($this->thumbnailAlt) !== '' ? trim($this->thumbnailAlt) : $title,
|
'image' => trim($this->thumbnailAlt) !== '' ? trim($this->thumbnailAlt) : $title,
|
||||||
'image_url' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
|
'image_url' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
|
||||||
'error' => 'Vorschau der Kartenform. Ob jemand sie öffnen darf, entscheidet die Lizenz.',
|
'error' => 'Vorschau der Kartenform. Ob jemand sie öffnen darf, entscheidet die Lizenz.',
|
||||||
],
|
],
|
||||||
])->render();
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$subject = app(PublicMaterialReader::class)->subject($element->id, true, $draft);
|
$subject = app(PublicMaterialReader::class)->subject($element->id, true, $draft);
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\DiscountCodes;
|
||||||
|
|
||||||
|
use App\Domain\Commerce\Discount\DiscountCode;
|
||||||
|
use App\Filament\Resources\DiscountCodes\Pages\ListDiscountCodes;
|
||||||
|
use App\Filament\Resources\DiscountCodes\Pages\ViewDiscountCode;
|
||||||
|
use App\Filament\Support\ShopAccess;
|
||||||
|
use Filament\Resources\Resource;
|
||||||
|
use Filament\Schemas\Schema;
|
||||||
|
use Filament\Tables\Columns\TextColumn;
|
||||||
|
use Filament\Tables\Table;
|
||||||
|
use Illuminate\Auth\Access\Response;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rabattcodes (FACH-14): anlegen, bearbeiten, zeitlich begrenzen, deaktivieren und einzelne Konten freischalten.
|
||||||
|
* Die Seiten nutzen die gemeinsamen Bausteine (Bestandsliste, Objektseite, Dialoge) wie die übrigen Kataloglisten.
|
||||||
|
*/
|
||||||
|
class DiscountCodeResource extends Resource
|
||||||
|
{
|
||||||
|
protected static ?string $model = DiscountCode::class;
|
||||||
|
|
||||||
|
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||||
|
|
||||||
|
protected static ?string $navigationLabel = 'Rabattcodes';
|
||||||
|
|
||||||
|
protected static ?string $modelLabel = 'Rabattcode';
|
||||||
|
|
||||||
|
protected static ?string $pluralModelLabel = 'Rabattcodes';
|
||||||
|
|
||||||
|
protected static ?string $recordTitleAttribute = 'code';
|
||||||
|
|
||||||
|
protected static ?int $navigationSort = 2;
|
||||||
|
|
||||||
|
public static function canViewAny(): bool
|
||||||
|
{
|
||||||
|
return ShopAccess::allowed();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function getViewAuthorizationResponse(Model $record): Response
|
||||||
|
{
|
||||||
|
return ShopAccess::allowed() ? Response::allow() : Response::deny();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function form(Schema $schema): Schema
|
||||||
|
{
|
||||||
|
return $schema;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function table(Table $table): Table
|
||||||
|
{
|
||||||
|
return $table->columns([
|
||||||
|
TextColumn::make('code')->label('Code')->searchable(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function getPages(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'index' => ListDiscountCodes::route('/'),
|
||||||
|
'view' => ViewDiscountCode::route('/{record}'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\DiscountCodes\Pages;
|
||||||
|
|
||||||
|
use App\Domain\Commerce\Discount\DiscountCode;
|
||||||
|
use App\Domain\Commerce\Discount\DiscountService;
|
||||||
|
use App\Filament\Resources\DiscountCodes\DiscountCodeResource;
|
||||||
|
use App\Filament\Support\DiscountCodeForm;
|
||||||
|
use App\Filament\Support\ListsCatalog;
|
||||||
|
use App\Filament\Support\ReportsDomainRules;
|
||||||
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Resources\Pages\ListRecords;
|
||||||
|
use Illuminate\Contracts\Support\Htmlable;
|
||||||
|
|
||||||
|
class ListDiscountCodes extends ListRecords
|
||||||
|
{
|
||||||
|
use ListsCatalog;
|
||||||
|
use ReportsDomainRules;
|
||||||
|
|
||||||
|
protected static string $resource = DiscountCodeResource::class;
|
||||||
|
|
||||||
|
public function getSubheading(): string|Htmlable|null
|
||||||
|
{
|
||||||
|
return 'Ein Code gilt für den ganzen Warenkorb oder nur für ausgewählte Ziele, und er ist allgemein einlösbar oder nur für freigeschaltete Konten. Beides stellst du unabhängig voneinander ein. Pro Bestellung gilt höchstens ein Code.';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getHeaderActions(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
Action::make('create')->label('Code anlegen')
|
||||||
|
->modalHeading('Neuer Rabattcode')
|
||||||
|
->modalDescription('Dieselbe Maske öffnet sich später beim Bearbeiten. Freigaben für einzelne Konten verwaltest du danach auf der Seite des Codes.')
|
||||||
|
->modalSubmitActionLabel('Code anlegen')
|
||||||
|
->modalWidth('3xl')
|
||||||
|
->fillForm(['kind' => DiscountCode::PERCENT, 'scope' => DiscountCode::SCOPE_CART, 'eligibility' => DiscountCode::OPEN, 'active' => true])
|
||||||
|
->schema(DiscountCodeForm::schema())
|
||||||
|
->action(function (array $data): void {
|
||||||
|
$code = null;
|
||||||
|
$this->report(function () use ($data, &$code): void {
|
||||||
|
[$fields, $targets] = DiscountCodeForm::fromForm($data);
|
||||||
|
$code = app(DiscountService::class)->save($fields, $targets);
|
||||||
|
}, 'Der Rabattcode ist angelegt.');
|
||||||
|
|
||||||
|
if ($code instanceof DiscountCode) {
|
||||||
|
$this->redirect(DiscountCodeResource::getUrl('view', ['record' => $code]));
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function catalogRows(): array
|
||||||
|
{
|
||||||
|
$rows = [];
|
||||||
|
$now = now();
|
||||||
|
|
||||||
|
foreach (DiscountCode::query()->with('targets')->withCount(['releases as active_releases_count' => fn ($query) => $query->whereNull('revoked_at')])->orderByDesc('id')->get() as $code) {
|
||||||
|
$state = $code->stateAt($now);
|
||||||
|
$url = DiscountCodeResource::getUrl('view', ['record' => $code]);
|
||||||
|
$rows[] = [
|
||||||
|
'schluessel' => 'c'.$code->id,
|
||||||
|
'titel' => $code->code,
|
||||||
|
'meta' => 'Rabattcode · '.$code->label,
|
||||||
|
'text' => $code->valueLabel().' · '.($code->forSelection() ? 'ausgewählte Ziele ('.$code->targets->count().')' : 'gesamter Warenkorb').' · '.($code->restricted() ? 'nur freigeschaltete Konten' : 'allgemein einlösbar'),
|
||||||
|
'symbol' => 'etikett',
|
||||||
|
'url' => $url,
|
||||||
|
'chips' => [
|
||||||
|
match ($state) {
|
||||||
|
'aktiv' => ['label' => 'Gültig', 'ton' => 'gut'],
|
||||||
|
'abgelaufen' => ['label' => 'Abgelaufen', 'ton' => 'leise'],
|
||||||
|
'noch_nicht' => ['label' => 'Noch nicht gültig', 'ton' => 'offen'],
|
||||||
|
default => ['label' => 'Deaktiviert', 'ton' => 'leise'],
|
||||||
|
},
|
||||||
|
['label' => $code->valueLabel(), 'ton' => 'neutral'],
|
||||||
|
['label' => $code->restricted() ? $code->active_releases_count.' freigeschaltet' : 'Allgemein', 'ton' => 'neutral'],
|
||||||
|
],
|
||||||
|
'zustand' => [$state === 'aktiv' ? 'aktiv' : 'inaktiv'],
|
||||||
|
'aktionen' => [['label' => 'Öffnen', 'href' => $url]],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function zustandOptionen(): array
|
||||||
|
{
|
||||||
|
return ['alle' => 'Jeder Zustand', 'aktiv' => 'Gerade gültig', 'inaktiv' => 'Abgelaufen, deaktiviert oder noch nicht gültig'];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function suchPlatzhalter(): string
|
||||||
|
{
|
||||||
|
return 'Code oder Name';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function einheit(): array
|
||||||
|
{
|
||||||
|
return ['Rabattcode', 'Rabattcodes'];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function leer(): array
|
||||||
|
{
|
||||||
|
return ['titel' => 'Noch keine Rabattcodes', 'text' => 'Mit „Code anlegen“ oben entsteht der erste Rabattcode, zum Beispiel der gemeinsame Zertifizierungscode.'];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\DiscountCodes\Pages;
|
||||||
|
|
||||||
|
use App\Domain\Catalog\Bundle;
|
||||||
|
use App\Domain\Catalog\LicenseArticle;
|
||||||
|
use App\Domain\Catalog\Offer;
|
||||||
|
use App\Domain\Commerce\Discount\DiscountCode;
|
||||||
|
use App\Domain\Commerce\Discount\DiscountRelease;
|
||||||
|
use App\Domain\Commerce\Discount\DiscountService;
|
||||||
|
use App\Domain\Commerce\Money;
|
||||||
|
use App\Domain\Commerce\Order;
|
||||||
|
use App\Filament\Resources\DiscountCodes\DiscountCodeResource;
|
||||||
|
use App\Filament\Support\DiscountCodeForm;
|
||||||
|
use App\Filament\Support\ReportsDomainRules;
|
||||||
|
use App\Models\User;
|
||||||
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Forms\Components\DatePicker;
|
||||||
|
use Filament\Forms\Components\Select;
|
||||||
|
use Filament\Forms\Components\Textarea;
|
||||||
|
use Filament\Resources\Pages\ViewRecord;
|
||||||
|
use Filament\Schemas\Components\View;
|
||||||
|
use Filament\Schemas\Schema;
|
||||||
|
use Filament\Support\Enums\Width;
|
||||||
|
use Illuminate\Contracts\Support\Htmlable;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rabattcode im gemeinsamen Rahmen. Bearbeiten nutzt dieselbe Maske wie Anlegen. Konten werden für genau diesen Code
|
||||||
|
* freigeschaltet und die Freigabe wird mit Begründung entzogen; der Verlauf bleibt stehen.
|
||||||
|
*/
|
||||||
|
class ViewDiscountCode extends ViewRecord
|
||||||
|
{
|
||||||
|
use ReportsDomainRules;
|
||||||
|
|
||||||
|
protected static string $resource = DiscountCodeResource::class;
|
||||||
|
|
||||||
|
public function getTitle(): string|Htmlable
|
||||||
|
{
|
||||||
|
return (string) $this->getRecord()->code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getHeading(): string|Htmlable
|
||||||
|
{
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getMaxContentWidth(): Width|string|null
|
||||||
|
{
|
||||||
|
return Width::Full;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getHeaderActions(): array
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
public function getBreadcrumbs(): array
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function infolist(Schema $schema): Schema
|
||||||
|
{
|
||||||
|
return $schema->components([
|
||||||
|
View::make('filament.catalog.objekt')->viewData(fn (): array => $this->codeDaten())->columnSpanFull(),
|
||||||
|
])->columns(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function code(): DiscountCode
|
||||||
|
{
|
||||||
|
/** @var DiscountCode $code */
|
||||||
|
$code = $this->getRecord();
|
||||||
|
|
||||||
|
return $code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function editAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('edit')
|
||||||
|
->label('Code bearbeiten')
|
||||||
|
->modalHeading(fn (): string => 'Rabattcode „'.$this->code()->code.'“ bearbeiten')
|
||||||
|
->modalDescription('Bestellungen, die schon aufgegeben sind, behalten ihren gespeicherten Rabatt. Eine Änderung wirkt auf künftige Einlösungen und auf offene Warenkörbe. „Abbrechen“ verwirft die Eingaben.')
|
||||||
|
->modalSubmitActionLabel('Änderungen speichern')
|
||||||
|
->modalWidth('3xl')
|
||||||
|
->fillForm(fn (): array => DiscountCodeForm::fill($this->code()))
|
||||||
|
->schema(DiscountCodeForm::schema())
|
||||||
|
->action(function (array $data): void {
|
||||||
|
$this->report(function () use ($data): void {
|
||||||
|
[$fields, $targets] = DiscountCodeForm::fromForm($data);
|
||||||
|
app(DiscountService::class)->save($fields, $targets, $this->code());
|
||||||
|
}, 'Der Rabattcode ist gespeichert.');
|
||||||
|
$this->refreshRecord();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function toggleAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('toggle')
|
||||||
|
->label(fn (): string => $this->code()->active ? 'Code deaktivieren' : 'Code aktivieren')
|
||||||
|
->color(fn (): string => $this->code()->active ? 'danger' : 'success')
|
||||||
|
->requiresConfirmation()
|
||||||
|
->modalHeading(fn (): string => $this->code()->active ? 'Code „'.$this->code()->code.'“ deaktivieren?' : 'Code „'.$this->code()->code.'“ aktivieren?')
|
||||||
|
->modalDescription(fn (): string => $this->code()->active
|
||||||
|
? 'Der Code lässt sich danach nicht mehr einlösen. In offenen Warenkörben zeigt die Bestellübersicht den Grund; bereits aufgegebene Bestellungen bleiben unverändert. Freigaben und Einstellungen bleiben erhalten.'
|
||||||
|
: 'Der Code lässt sich danach wieder einlösen, soweit sein Gültigkeitszeitraum und die Freigaben es zulassen.')
|
||||||
|
->modalSubmitActionLabel(fn (): string => $this->code()->active ? 'Deaktivieren' : 'Aktivieren')
|
||||||
|
->action(function (): void {
|
||||||
|
$code = $this->code();
|
||||||
|
$this->report(function () use ($code): string {
|
||||||
|
app(DiscountService::class)->setActive($code, ! $code->active);
|
||||||
|
|
||||||
|
return $code->active ? 'Der Code ist aktiviert.' : 'Der Code ist deaktiviert.';
|
||||||
|
}, 'Gespeichert.');
|
||||||
|
$this->refreshRecord();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function releaseAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('release')
|
||||||
|
->label('Konto freischalten')
|
||||||
|
->modalHeading(fn (): string => 'Konto für den Code „'.$this->code()->code.'“ freischalten')
|
||||||
|
->modalDescription('Das Konto darf genau diesen Code einlösen, solange Code und Freigabe gültig sind, auch bei späteren Bestellungen. Die Freigabe gilt nicht für andere Codes. Prüfe vorher die Zertifizierung des Kontos.')
|
||||||
|
->modalSubmitActionLabel('Konto freischalten')
|
||||||
|
->schema([
|
||||||
|
Select::make('user_id')->label('Mitgliedskonto')->required()->searchable()
|
||||||
|
->getSearchResultsUsing(fn (string $search): array => $this->searchMembers($search))
|
||||||
|
->getOptionLabelUsing(fn ($value): ?string => ($user = User::query()->find($value)) === null ? null : $user->name.' ('.$user->email.')')
|
||||||
|
->helperText('Suche nach Name oder E-Mail-Adresse. Nur Konten mit Mitgliedsprofil.'),
|
||||||
|
DatePicker::make('valid_until')->label('Freigabe gültig bis einschließlich')->native(false)->displayFormat('d.m.Y')
|
||||||
|
->helperText('Leer: ohne Ende. Danach gilt der Code für dieses Konto nicht mehr.'),
|
||||||
|
Textarea::make('reason')->label('Grundlage der Freigabe')->rows(2)->maxLength(500)
|
||||||
|
->helperText('Zum Beispiel „Zertifikat vom 12.11.2026 geprüft“. Bleibt im Verlauf stehen.'),
|
||||||
|
])
|
||||||
|
->visible(fn (): bool => $this->code()->restricted())
|
||||||
|
->action(function (array $data): void {
|
||||||
|
$this->report(function () use ($data): string {
|
||||||
|
$member = User::query()->findOrFail($data['user_id']);
|
||||||
|
$until = filled($data['valid_until'] ?? null) ? Carbon::parse((string) $data['valid_until'], config('app.timezone'))->endOfDay() : null;
|
||||||
|
app(DiscountService::class)->release($this->code(), $member, auth('staff')->user() ?? auth()->user(), $until, $data['reason'] ?? null);
|
||||||
|
|
||||||
|
return 'Das Konto von '.$member->name.' ist für den Code freigeschaltet.';
|
||||||
|
}, 'Das Konto ist freigeschaltet.');
|
||||||
|
$this->refreshRecord();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function revokeAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('revoke')
|
||||||
|
->label('Freigabe entziehen')
|
||||||
|
->color('danger')
|
||||||
|
->requiresConfirmation()
|
||||||
|
->modalHeading('Freigabe entziehen?')
|
||||||
|
->modalDescription('Das Konto kann diesen Code danach nicht mehr einlösen. Offene Warenkörbe des Kontos zeigen den Grund und lassen sich erst ohne Code bestellen. Aufgegebene Bestellungen bleiben unverändert; die Freigabe bleibt mit dem Entzug im Verlauf stehen.')
|
||||||
|
->modalSubmitActionLabel('Freigabe entziehen')
|
||||||
|
->schema([
|
||||||
|
Textarea::make('reason')->label('Grund')->rows(2)->maxLength(500),
|
||||||
|
])
|
||||||
|
->action(function (array $data, array $arguments): void {
|
||||||
|
$this->report(function () use ($data, $arguments): string {
|
||||||
|
$release = DiscountRelease::query()->where('discount_code_id', $this->code()->id)->findOrFail((int) ($arguments['release'] ?? 0));
|
||||||
|
app(DiscountService::class)->revoke($release, auth('staff')->user() ?? auth()->user(), $data['reason'] ?? null);
|
||||||
|
|
||||||
|
return 'Die Freigabe ist entzogen.';
|
||||||
|
}, 'Die Freigabe ist entzogen.');
|
||||||
|
$this->refreshRecord();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private function refreshRecord(): void
|
||||||
|
{
|
||||||
|
$this->getRecord()->unsetRelations();
|
||||||
|
$this->getRecord()->refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
private function searchMembers(string $search): array
|
||||||
|
{
|
||||||
|
$like = '%'.mb_strtolower(trim($search)).'%';
|
||||||
|
|
||||||
|
return User::query()
|
||||||
|
->whereNotNull('party_id')
|
||||||
|
->where(fn ($query) => $query->whereRaw('LOWER(name) LIKE ?', [$like])->orWhereRaw('LOWER(email) LIKE ?', [$like]))
|
||||||
|
->orderBy('name')
|
||||||
|
->limit(20)
|
||||||
|
->get()
|
||||||
|
->mapWithKeys(fn (User $user): array => [$user->id => $user->name.' ('.$user->email.')'])
|
||||||
|
->all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function codeDaten(): array
|
||||||
|
{
|
||||||
|
$code = $this->code();
|
||||||
|
$code->loadMissing('targets');
|
||||||
|
$state = $code->stateAt(now());
|
||||||
|
$date = fn (?Carbon $value): string => $value === null ? '' : $value->timezone(config('app.timezone'))->format('d.m.Y');
|
||||||
|
$targets = [];
|
||||||
|
|
||||||
|
foreach ($code->targets as $target) {
|
||||||
|
$targets[] = match ($target->target_type) {
|
||||||
|
DiscountCode::TARGET_OFFER => 'Angebot „'.(Offer::query()->find($target->target_id)?->name ?? 'gelöscht').'“',
|
||||||
|
DiscountCode::TARGET_ARTICLE => 'Lizenzartikel '.(LicenseArticle::query()->find($target->target_id)?->code ?? 'gelöscht'),
|
||||||
|
DiscountCode::TARGET_BUNDLE => 'Paket „'.(Bundle::query()->find($target->target_id)?->name ?? 'gelöscht').'“',
|
||||||
|
default => 'Ziel',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$releases = $code->releases()->with(['user', 'grantor'])->get();
|
||||||
|
$active = $releases->filter(fn (DiscountRelease $release): bool => $release->revoked_at === null);
|
||||||
|
$past = $releases->filter(fn (DiscountRelease $release): bool => $release->revoked_at !== null);
|
||||||
|
$orders = Order::query()->where('discount_code_id', $code->id)->with('user')->latest('id')->limit(10)->get();
|
||||||
|
$paid = Order::query()->where('discount_code_id', $code->id)->where('status', 'bezahlt')->count();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'kopf' => [
|
||||||
|
'brot' => [['label' => 'Rabattcodes', 'href' => DiscountCodeResource::getUrl('index')], $code->code],
|
||||||
|
'titel' => $code->code,
|
||||||
|
'typ' => 'Rabattcode · '.$code->label,
|
||||||
|
'status' => match ($state) {
|
||||||
|
'aktiv' => ['text' => 'Gerade gültig'.($code->valid_until ? ' bis einschließlich '.$date($code->valid_until) : ''), 'ton' => 'gut'],
|
||||||
|
'abgelaufen' => ['text' => 'Abgelaufen am '.$date($code->valid_until).'. Der Code lässt sich nicht mehr einlösen.', 'ton' => 'offen'],
|
||||||
|
'noch_nicht' => ['text' => 'Gilt erst ab dem '.$date($code->valid_from).'.', 'ton' => 'offen'],
|
||||||
|
default => ['text' => 'Deaktiviert. Der Code lässt sich nicht einlösen.', 'ton' => 'offen'],
|
||||||
|
},
|
||||||
|
'aktionen' => [
|
||||||
|
['label' => 'Code bearbeiten', 'wire' => "mountAction('edit')", 'art' => 'primary'],
|
||||||
|
...($code->restricted() ? [['label' => 'Konto freischalten', 'wire' => "mountAction('release')", 'art' => 'line']] : []),
|
||||||
|
['label' => $code->active ? 'Code deaktivieren' : 'Code aktivieren', 'wire' => "mountAction('toggle')", 'art' => 'line'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
'haupt' => [
|
||||||
|
[
|
||||||
|
'titel' => 'Der Code auf einen Blick',
|
||||||
|
'hilfe' => 'Geltungsbereich und Einlösungsberechtigung sind zwei getrennte Einstellungen. Der Rabatt ändert den Preis, nie den Nutzungsumfang.',
|
||||||
|
'zeilen' => [
|
||||||
|
['text' => 'Rabatt: '.$code->valueLabel(), 'neben' => $code->kind === DiscountCode::PERCENT ? 'Je Position gerundet.' : 'Je Bestellung, anteilig auf die betroffenen Positionen verteilt.'],
|
||||||
|
['text' => 'Geltungsbereich: '.($code->forSelection() ? 'nur ausgewählte Ziele' : 'gesamter Warenkorb'), 'neben' => $code->forSelection() ? 'Ein Paket ist ein eigenes Ziel und folgt nicht aus einem enthaltenen Artikel.' : null],
|
||||||
|
...array_map(fn (string $target): array => ['text' => '· '.$target, 'neben' => null], $targets),
|
||||||
|
['text' => 'Einlösung: '.($code->restricted() ? 'nur freigeschaltete Konten' : 'allgemein, für alle angemeldeten Käufer'), 'neben' => 'Pro Bestellung gilt höchstens ein Code.'],
|
||||||
|
['text' => 'Gültigkeit: '.($code->valid_from ? 'ab '.$date($code->valid_from) : 'sofort').($code->valid_until ? ' bis einschließlich '.$date($code->valid_until) : ', unbegrenzt'), 'neben' => $code->active ? 'Aktiv' : 'Deaktiviert'],
|
||||||
|
...(filled($code->note) ? [['text' => 'Notiz: '.$code->note, 'neben' => null]] : []),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'titel' => $code->restricted() ? 'Freigeschaltete Konten' : 'Freigaben',
|
||||||
|
'zusatz' => $code->restricted() ? $active->count().' aktiv' : null,
|
||||||
|
'hilfe' => $code->restricted()
|
||||||
|
? 'Nur diese Konten können den Code einlösen. Die Freigabe gilt nur für diesen Code und wiederholt, solange Code und Freigabe gültig sind.'
|
||||||
|
: 'Der Code ist allgemein einlösbar. Freigaben sind nicht nötig. Stelle „Einlösung“ auf freigeschaltete Konten, um den Code zu beschränken.',
|
||||||
|
'zeilen' => $code->restricted() ? $active->map(fn (DiscountRelease $release): array => [
|
||||||
|
'text' => ($release->user?->name ?? 'Konto').' ('.($release->user?->email ?? '').')',
|
||||||
|
'neben' => 'freigeschaltet am '.$date($release->granted_at).($release->grantor ? ' von '.$release->grantor->name : '').($release->valid_until ? ', gültig bis einschließlich '.$date($release->valid_until) : '').(filled($release->reason) ? ' · '.$release->reason : ''),
|
||||||
|
'aktion' => ['label' => 'Entziehen', 'wire' => "mountAction('revoke', { release: ".$release->id.' })'],
|
||||||
|
])->values()->all() : [],
|
||||||
|
'leer' => ['titel' => $code->restricted() ? 'Noch kein Konto freigeschaltet' : 'Keine Freigaben nötig', 'text' => $code->restricted() ? 'Mit „Konto freischalten“ oben gibst du ein Konto für diesen Code frei, zum Beispiel nach der Prüfung eines Zertifikats.' : 'Jeder angemeldete Käufer kann den Code einlösen.'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
'seite' => [
|
||||||
|
[
|
||||||
|
'titel' => 'Verwendung',
|
||||||
|
'zeilen' => $orders->map(fn (Order $order): array => [
|
||||||
|
'text' => 'Bestellung '.$order->id.' · −'.Money::format((int) $order->discount_cents),
|
||||||
|
'zustand' => ['label' => match ($order->status) {
|
||||||
|
'bezahlt' => 'Bezahlt', 'erstattet' => 'Erstattet', 'fehlgeschlagen' => 'Fehlgeschlagen', default => 'Offen'
|
||||||
|
}, 'ton' => $order->status === 'bezahlt' ? 'gut' : 'leise'],
|
||||||
|
'neben' => ($order->user?->name ?? '').' · '.$date($order->created_at),
|
||||||
|
])->all(),
|
||||||
|
'leer' => 'Der Code wurde noch in keiner Bestellung verwendet.',
|
||||||
|
'hilfe' => $orders->isEmpty() ? null : $paid.' bezahlte Bestellung'.($paid === 1 ? '' : 'en').' mit diesem Code. Gezeigt werden die letzten zehn.',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'titel' => 'Entzogene Freigaben',
|
||||||
|
'zeilen' => $past->map(fn (DiscountRelease $release): array => [
|
||||||
|
'text' => ($release->user?->name ?? 'Konto'),
|
||||||
|
'neben' => 'entzogen am '.$date($release->revoked_at).(filled($release->reason) ? ' · '.$release->reason : ''),
|
||||||
|
])->values()->all(),
|
||||||
|
'leer' => 'Keine Freigabe wurde entzogen.',
|
||||||
|
'hilfe' => 'Der Verlauf bleibt erhalten.',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
use App\Domain\Catalog\Composition;
|
use App\Domain\Catalog\Composition;
|
||||||
use App\Domain\Catalog\CompositionVersion;
|
use App\Domain\Catalog\CompositionVersion;
|
||||||
use App\Domain\Catalog\DomainRuleException;
|
use App\Domain\Catalog\DomainRuleException;
|
||||||
|
use App\Domain\Catalog\LicenceScope;
|
||||||
use App\Domain\Catalog\LicenseArticle;
|
use App\Domain\Catalog\LicenseArticle;
|
||||||
use App\Domain\Catalog\Offer;
|
use App\Domain\Catalog\Offer;
|
||||||
use App\Domain\Catalog\OfferService;
|
use App\Domain\Catalog\OfferService;
|
||||||
@@ -17,11 +18,13 @@
|
|||||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||||
use App\Domain\Commerce\Money;
|
use App\Domain\Commerce\Money;
|
||||||
use App\Domain\Commerce\ProductOptions;
|
use App\Domain\Commerce\ProductOptions;
|
||||||
|
use App\Filament\Pages\Zahlungsjournal;
|
||||||
use App\Filament\Resources\Offers\OfferResource;
|
use App\Filament\Resources\Offers\OfferResource;
|
||||||
use App\Filament\Support\CatalogLabels;
|
use App\Filament\Support\CatalogLabels;
|
||||||
use App\Filament\Support\CatalogOptions;
|
use App\Filament\Support\CatalogOptions;
|
||||||
use App\Filament\Support\PublicationReadiness;
|
use App\Filament\Support\PublicationReadiness;
|
||||||
use App\Filament\Support\ReportsDomainRules;
|
use App\Filament\Support\ReportsDomainRules;
|
||||||
|
use App\Filament\Support\ShopAccess;
|
||||||
use Filament\Actions\Action;
|
use Filament\Actions\Action;
|
||||||
use Filament\Forms\Components\Repeater;
|
use Filament\Forms\Components\Repeater;
|
||||||
use Filament\Forms\Components\Select;
|
use Filament\Forms\Components\Select;
|
||||||
@@ -45,6 +48,9 @@ class ViewOffer extends ViewRecord
|
|||||||
|
|
||||||
protected static string $resource = OfferResource::class;
|
protected static string $resource = OfferResource::class;
|
||||||
|
|
||||||
|
/** Wert der Auswahl „Produktseite“ für ein Paket mit eigener Seite. */
|
||||||
|
private const OWN_BUNDLE_PAGE = '__paket';
|
||||||
|
|
||||||
public function getTitle(): string|Htmlable
|
public function getTitle(): string|Htmlable
|
||||||
{
|
{
|
||||||
return (string) $this->getRecord()->name;
|
return (string) $this->getRecord()->name;
|
||||||
@@ -120,6 +126,16 @@ public function activateAction(): Action
|
|||||||
'organisation' => 'Organisationen und Vereine',
|
'organisation' => 'Organisationen und Vereine',
|
||||||
])->required()
|
])->required()
|
||||||
->helperText('Wähle die Eignung passend zu den Rechten: Organisationslizenzen brauchen institutionelle Rechte. Das System erzwingt diese Kopplung nicht.'),
|
->helperText('Wähle die Eignung passend zu den Rechten: Organisationslizenzen brauchen institutionelle Rechte. Das System erzwingt diese Kopplung nicht.'),
|
||||||
|
Select::make('licence_scope')->label('Nutzerkreis')
|
||||||
|
->options(LicenceScope::options())
|
||||||
|
->required()
|
||||||
|
->live()
|
||||||
|
->helperText('Wie viele Trainer die Inhalte einsetzen dürfen. Das ist unabhängig vom Lizenzinhaber (Person oder Verein), vom Nutzungszweck der Rechte und vom Preis; es wird aus keinem davon abgeleitet. Der Download bleibt zum Start beim bestellenden Konto. Der Wert wird mit der Bestellung festgehalten.'),
|
||||||
|
TextInput::make('trainer_count')->label('Anzahl Trainer')
|
||||||
|
->numeric()->minValue(2)->maxValue(LicenceScope::MAX_TRAINERS)->integer()
|
||||||
|
->required(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
|
||||||
|
->visible(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
|
||||||
|
->helperText('Höchstzahl der Trainer, die die Inhalte einsetzen dürfen, mindestens 2. Eine Einzellizenz gilt immer für genau einen Trainer.'),
|
||||||
Select::make('grant_kind')->label('Vergabe')->options([
|
Select::make('grant_kind')->label('Vergabe')->options([
|
||||||
'kauf' => 'Kauf',
|
'kauf' => 'Kauf',
|
||||||
'auf_abruf' => 'Auf Abruf',
|
'auf_abruf' => 'Auf Abruf',
|
||||||
@@ -201,13 +217,16 @@ public function activateAction(): Action
|
|||||||
$version = DB::transaction(function () use ($service, $offer, $data, $lines, $kept, $price) {
|
$version = DB::transaction(function () use ($service, $offer, $data, $lines, $kept, $price) {
|
||||||
$service->assignProduct(
|
$service->assignProduct(
|
||||||
$offer,
|
$offer,
|
||||||
filled($data['composition_id'] ?? null) ? (int) $data['composition_id'] : null,
|
filled($data['composition_id'] ?? null) && $data['composition_id'] !== self::OWN_BUNDLE_PAGE ? (int) $data['composition_id'] : null,
|
||||||
$data['option_label'] ?? null,
|
$data['option_label'] ?? null,
|
||||||
|
($data['composition_id'] ?? null) === self::OWN_BUNDLE_PAGE,
|
||||||
);
|
);
|
||||||
|
|
||||||
return $service->activate($offer, $lines, [
|
return $service->activate($offer, $lines, [
|
||||||
...$kept,
|
...$kept,
|
||||||
'holder_kind' => $data['holder_kind'],
|
'holder_kind' => $data['holder_kind'],
|
||||||
|
'licence_scope' => $data['licence_scope'] ?? null,
|
||||||
|
'trainer_count' => $data['trainer_count'] ?? null,
|
||||||
'grant_kind' => $data['grant_kind'],
|
'grant_kind' => $data['grant_kind'],
|
||||||
'price_cents' => $price,
|
'price_cents' => $price,
|
||||||
'composition_version_id' => filled($data['composition_version_id'] ?? null) ? (int) $data['composition_version_id'] : null,
|
'composition_version_id' => filled($data['composition_version_id'] ?? null) ? (int) $data['composition_version_id'] : null,
|
||||||
@@ -267,7 +286,7 @@ private function productPages(): array
|
|||||||
{
|
{
|
||||||
$catalog = app(PublicCatalogReader::class);
|
$catalog = app(PublicCatalogReader::class);
|
||||||
|
|
||||||
return Composition::query()
|
return [self::OWN_BUNDLE_PAGE => 'Eigene Paketseite · zeigt den Umfang des Pakets (nur für ein Angebot aus genau einer Paketfassung)'] + Composition::query()
|
||||||
->with('editorialContentKind')
|
->with('editorialContentKind')
|
||||||
->whereNull('archived_at')
|
->whereNull('archived_at')
|
||||||
->orderBy('designation')
|
->orderBy('designation')
|
||||||
@@ -291,15 +310,17 @@ private function formFromActive(): array
|
|||||||
$active = $this->activeVersion();
|
$active = $this->activeVersion();
|
||||||
/** @var Offer $offer */
|
/** @var Offer $offer */
|
||||||
$offer = $this->getRecord();
|
$offer = $this->getRecord();
|
||||||
$option = ['option_label' => $offer->option_label, 'composition_id' => $offer->composition_id];
|
$option = ['option_label' => $offer->option_label, 'composition_id' => $offer->standalone_bundle ? self::OWN_BUNDLE_PAGE : $offer->composition_id];
|
||||||
|
|
||||||
if ($active === null) {
|
if ($active === null) {
|
||||||
return [...$option, 'holder_kind' => 'person', 'grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]];
|
return [...$option, 'holder_kind' => 'person', 'licence_scope' => LicenceScope::SINGLE, 'grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]];
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
...$option,
|
...$option,
|
||||||
'holder_kind' => $active->holder_kind,
|
'holder_kind' => $active->holder_kind,
|
||||||
|
'licence_scope' => $active->licence_scope,
|
||||||
|
'trainer_count' => $active->trainer_count,
|
||||||
'grant_kind' => $active->grant_kind,
|
'grant_kind' => $active->grant_kind,
|
||||||
'price_euro' => $active->price_cents === null ? null : number_format($active->price_cents / 100, 2, ',', ''),
|
'price_euro' => $active->price_cents === null ? null : number_format($active->price_cents / 100, 2, ',', ''),
|
||||||
'lines' => $active->lines->sortBy('position')->map(fn ($line): array => [
|
'lines' => $active->lines->sortBy('position')->map(fn ($line): array => [
|
||||||
@@ -347,6 +368,11 @@ private function angebotDaten(): array
|
|||||||
'wire' => "mountAction('end')",
|
'wire' => "mountAction('end')",
|
||||||
'art' => 'line',
|
'art' => 'line',
|
||||||
]] : []),
|
]] : []),
|
||||||
|
...(ShopAccess::allowed() ? [[
|
||||||
|
'label' => 'Zahlungen zu diesem Angebot',
|
||||||
|
'href' => Zahlungsjournal::getUrl(['angebot' => $offer->id, 'zeitraum' => 'jahr', 'betrieb' => 'alle']),
|
||||||
|
'art' => 'quiet',
|
||||||
|
]] : []),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
'voraussetzungen' => app(PublicationReadiness::class)->forOffer($offer),
|
'voraussetzungen' => app(PublicationReadiness::class)->forOffer($offer),
|
||||||
@@ -400,6 +426,7 @@ private function optionAbschnitt(Offer $offer, OfferVersion $active): array
|
|||||||
->unique()
|
->unique()
|
||||||
->implode('; ');
|
->implode('; ');
|
||||||
$seite = $offer->composition;
|
$seite = $offer->composition;
|
||||||
|
$eigeneSeite = $offer->standalone_bundle;
|
||||||
$kaufbar = app(OfferService::class)->purchasableVersion($offer) !== null;
|
$kaufbar = app(OfferService::class)->purchasableVersion($offer) !== null;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
@@ -409,10 +436,11 @@ private function optionAbschnitt(Offer $offer, OfferVersion $active): array
|
|||||||
'zeilen' => [
|
'zeilen' => [
|
||||||
['text' => 'Preis: '.$option['price'], 'neben' => $active->grant_kind === 'kauf' ? 'Kauf mit Testzahlung' : CatalogLabels::vergabe($active)],
|
['text' => 'Preis: '.$option['price'], 'neben' => $active->grant_kind === 'kauf' ? 'Kauf mit Testzahlung' : CatalogLabels::vergabe($active)],
|
||||||
['text' => 'Geeignet für: '.$option['for'], 'neben' => $option['term']],
|
['text' => 'Geeignet für: '.$option['for'], 'neben' => $option['term']],
|
||||||
|
['text' => 'Nutzerkreis: '.$option['licence'], 'neben' => $option['licence_scope'] === null ? 'Mit „Geänderte Fassung aktivieren“ festlegen.' : 'Lizenzinhaber, Nutzerkreis und Downloadkonto sind getrennte Angaben.'],
|
||||||
['text' => 'Rechte: '.($rechte !== '' ? $rechte : 'keine'), 'neben' => null],
|
['text' => 'Rechte: '.($rechte !== '' ? $rechte : 'keine'), 'neben' => null],
|
||||||
['text' => 'Zugrunde liegender Inhalt: '.($inhalt !== '' ? $inhalt : '–'), 'neben' => null],
|
['text' => 'Zugrunde liegender Inhalt: '.($inhalt !== '' ? $inhalt : '–'), 'neben' => null],
|
||||||
['text' => 'Status: '.($kaufbar ? 'Öffentlich kaufbar' : 'Nicht als Kauf angeboten'), 'neben' => $kaufbar ? 'Aktive Fassung '.$active->number : null],
|
['text' => 'Status: '.($kaufbar ? 'Öffentlich kaufbar' : 'Nicht als Kauf angeboten'), 'neben' => $kaufbar ? 'Aktive Fassung '.$active->number : null],
|
||||||
['text' => 'Produktseite: '.($seite !== null ? ($seite->display_title ?: $seite->designation) : 'noch nicht zugeordnet'), 'neben' => $seite !== null ? 'Option „'.$offer->optionName().'“' : 'Mit „Geänderte Fassung aktivieren“ zuordnen.'],
|
['text' => 'Produktseite: '.($eigeneSeite ? 'eigene Paketseite mit dem Umfang des Pakets' : ($seite !== null ? ($seite->display_title ?: $seite->designation) : 'noch nicht zugeordnet')), 'neben' => $eigeneSeite || $seite !== null ? 'Option „'.$offer->optionName().'“' : 'Mit „Geänderte Fassung aktivieren“ zuordnen.'],
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\Orders;
|
||||||
|
|
||||||
|
use App\Domain\Commerce\Order;
|
||||||
|
use App\Filament\Resources\Orders\Pages\ListOrders;
|
||||||
|
use App\Filament\Resources\Orders\Pages\ViewOrder;
|
||||||
|
use App\Filament\Support\ShopAccess;
|
||||||
|
use Filament\Resources\Resource;
|
||||||
|
use Filament\Schemas\Schema;
|
||||||
|
use Filament\Tables\Columns\TextColumn;
|
||||||
|
use Filament\Tables\Table;
|
||||||
|
use Illuminate\Auth\Access\Response;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bestellverwaltung (PAY-006): Bestellungen lesen, bei Kauf auf Rechnung den Zahlungseingang bestätigen und
|
||||||
|
* bezahlte Bestellungen vollständig erstatten. Es gibt keine Bearbeitung der gespeicherten Konditionen.
|
||||||
|
*/
|
||||||
|
class OrderResource extends Resource
|
||||||
|
{
|
||||||
|
protected static ?string $model = Order::class;
|
||||||
|
|
||||||
|
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||||
|
|
||||||
|
protected static ?string $navigationLabel = 'Bestellungen';
|
||||||
|
|
||||||
|
protected static ?string $modelLabel = 'Bestellung';
|
||||||
|
|
||||||
|
protected static ?string $pluralModelLabel = 'Bestellungen';
|
||||||
|
|
||||||
|
protected static ?int $navigationSort = 1;
|
||||||
|
|
||||||
|
public static function canViewAny(): bool
|
||||||
|
{
|
||||||
|
return ShopAccess::allowed();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function canCreate(): bool
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function getViewAuthorizationResponse(Model $record): Response
|
||||||
|
{
|
||||||
|
return ShopAccess::allowed() ? Response::allow() : Response::deny();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function form(Schema $schema): Schema
|
||||||
|
{
|
||||||
|
return $schema;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function table(Table $table): Table
|
||||||
|
{
|
||||||
|
return $table->columns([
|
||||||
|
TextColumn::make('id')->label('Bestellung'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function getPages(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'index' => ListOrders::route('/'),
|
||||||
|
'view' => ViewOrder::route('/{record}'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\Orders\Pages;
|
||||||
|
|
||||||
|
use App\Domain\Commerce\Money;
|
||||||
|
use App\Domain\Commerce\Order;
|
||||||
|
use App\Filament\Resources\Orders\OrderResource;
|
||||||
|
use App\Filament\Support\ListsCatalog;
|
||||||
|
use Filament\Resources\Pages\ListRecords;
|
||||||
|
use Illuminate\Contracts\Support\Htmlable;
|
||||||
|
|
||||||
|
class ListOrders extends ListRecords
|
||||||
|
{
|
||||||
|
use ListsCatalog;
|
||||||
|
|
||||||
|
protected static string $resource = OrderResource::class;
|
||||||
|
|
||||||
|
public function getSubheading(): string|Htmlable|null
|
||||||
|
{
|
||||||
|
return 'Bestellungen mit Lizenzinhaber, Zahlungsweg und Zahlbetrag. Bei Kauf auf Rechnung bestätigst du hier den Zahlungseingang; bezahlte Bestellungen erstattest du vollständig.';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getHeaderActions(): array
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function catalogRows(): array
|
||||||
|
{
|
||||||
|
$rows = [];
|
||||||
|
|
||||||
|
foreach (Order::query()->with(['lines', 'user', 'party'])->orderByDesc('id')->limit(300)->get() as $order) {
|
||||||
|
$url = OrderResource::getUrl('view', ['record' => $order]);
|
||||||
|
$zustand = [$order->status];
|
||||||
|
$chips = [
|
||||||
|
match ($order->status) {
|
||||||
|
'bezahlt' => ['label' => 'Bezahlt', 'ton' => 'gut'],
|
||||||
|
'erstattet' => ['label' => 'Erstattet', 'ton' => 'leise'],
|
||||||
|
'fehlgeschlagen' => ['label' => 'Fehlgeschlagen', 'ton' => 'leise'],
|
||||||
|
default => ['label' => $order->payment_method === 'rechnung' ? 'Offen: wartet auf Zahlungseingang' : 'Offen', 'ton' => 'offen'],
|
||||||
|
},
|
||||||
|
['label' => match ($order->payment_method) {
|
||||||
|
'rechnung' => 'Rechnung', 'stripe' => 'Stripe', default => 'Testzahlung'
|
||||||
|
}, 'ton' => 'neutral'],
|
||||||
|
['label' => Money::format($order->payable()), 'ton' => 'neutral'],
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($order->discount_cents > 0) {
|
||||||
|
$chips[] = ['label' => 'Rabatt '.($order->discount_snapshot['code'] ?? ''), 'ton' => 'neutral'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($order->withdrawal_requested_at !== null) {
|
||||||
|
$chips[] = ['label' => 'Widerruf erklärt', 'ton' => 'offen'];
|
||||||
|
$zustand[] = 'widerruf';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($order->payment_method === 'rechnung' && $order->status === 'offen') {
|
||||||
|
$zustand[] = 'rechnung_offen';
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows[] = [
|
||||||
|
'schluessel' => 'o'.$order->id,
|
||||||
|
'titel' => 'Bestellung '.$order->id,
|
||||||
|
'meta' => ($order->party?->display_name ?? '–').' · bestellt von '.($order->user?->name ?? '–'),
|
||||||
|
'text' => $order->lines->pluck('offer_name')->implode('; '),
|
||||||
|
'suchtext' => (string) ($order->user?->email ?? ''),
|
||||||
|
'symbol' => 'etikett',
|
||||||
|
'url' => $url,
|
||||||
|
'chips' => $chips,
|
||||||
|
'zustand' => $zustand,
|
||||||
|
'aktionen' => [['label' => 'Öffnen', 'href' => $url]],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function zustandOptionen(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'alle' => 'Jeder Zustand',
|
||||||
|
'rechnung_offen' => 'Rechnung: wartet auf Zahlungseingang',
|
||||||
|
'widerruf' => 'Widerruf erklärt',
|
||||||
|
'offen' => 'Offen',
|
||||||
|
'bezahlt' => 'Bezahlt',
|
||||||
|
'erstattet' => 'Erstattet',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function suchPlatzhalter(): string
|
||||||
|
{
|
||||||
|
return 'Nummer, Name, E-Mail oder Angebot';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function einheit(): array
|
||||||
|
{
|
||||||
|
return ['Bestellung', 'Bestellungen'];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function leer(): array
|
||||||
|
{
|
||||||
|
return ['titel' => 'Noch keine Bestellungen', 'text' => 'Sobald im Shop bestellt wird, erscheinen die Bestellungen hier.'];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\Orders\Pages;
|
||||||
|
|
||||||
|
use App\Domain\Catalog\LicenceScope;
|
||||||
|
use App\Domain\Commerce\Checkout;
|
||||||
|
use App\Domain\Commerce\LedgerEntry;
|
||||||
|
use App\Domain\Commerce\Money;
|
||||||
|
use App\Domain\Commerce\Order;
|
||||||
|
use App\Domain\Commerce\OrderLine;
|
||||||
|
use App\Domain\Commerce\Payment;
|
||||||
|
use App\Domain\Commerce\PaymentJournal;
|
||||||
|
use App\Filament\Resources\Orders\OrderResource;
|
||||||
|
use App\Filament\Support\ReportsDomainRules;
|
||||||
|
use Filament\Actions\Action;
|
||||||
|
use Filament\Facades\Filament;
|
||||||
|
use Filament\Forms\Components\DatePicker;
|
||||||
|
use Filament\Forms\Components\Textarea;
|
||||||
|
use Filament\Forms\Components\TextInput;
|
||||||
|
use Filament\Resources\Pages\ViewRecord;
|
||||||
|
use Filament\Schemas\Components\View;
|
||||||
|
use Filament\Schemas\Schema;
|
||||||
|
use Filament\Support\Enums\Width;
|
||||||
|
use Illuminate\Contracts\Support\Htmlable;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bestellung im gemeinsamen Rahmen. Die gespeicherten Konditionen sind unveränderlich; der Betreiber bestätigt bei
|
||||||
|
* Kauf auf Rechnung den Zahlungseingang und erstattet bezahlte Bestellungen vollständig (Bundles als Einheit).
|
||||||
|
*/
|
||||||
|
class ViewOrder extends ViewRecord
|
||||||
|
{
|
||||||
|
use ReportsDomainRules;
|
||||||
|
|
||||||
|
protected static string $resource = OrderResource::class;
|
||||||
|
|
||||||
|
public function getTitle(): string|Htmlable
|
||||||
|
{
|
||||||
|
return 'Bestellung '.$this->order()->id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getHeading(): string|Htmlable
|
||||||
|
{
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getMaxContentWidth(): Width|string|null
|
||||||
|
{
|
||||||
|
return Width::Full;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getHeaderActions(): array
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, string>
|
||||||
|
*/
|
||||||
|
public function getBreadcrumbs(): array
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function infolist(Schema $schema): Schema
|
||||||
|
{
|
||||||
|
return $schema->components([
|
||||||
|
View::make('filament.catalog.objekt')->viewData(fn (): array => $this->bestellDaten())->columnSpanFull(),
|
||||||
|
])->columns(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hasStripePayment(): bool
|
||||||
|
{
|
||||||
|
return $this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function order(): Order
|
||||||
|
{
|
||||||
|
/** @var Order $order */
|
||||||
|
$order = $this->getRecord();
|
||||||
|
|
||||||
|
return $order;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function confirmInvoiceAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('confirmInvoice')
|
||||||
|
->label('Zahlungseingang bestätigen')
|
||||||
|
->modalHeading(fn (): string => 'Zahlungseingang für Bestellung '.$this->order()->id.' bestätigen')
|
||||||
|
->modalDescription(fn (): string => 'Du bestätigst, dass '.Money::format($this->order()->payable()).' für die Rechnung eingegangen sind. Die Inhalte werden sofort für das bestellende Konto freigeschaltet; Lizenzinhaber bleibt '.($this->order()->party?->display_name ?? 'der Käufer').'. Die Bestätigung lässt sich nicht zurücknehmen, nur die Bestellung erstatten.')
|
||||||
|
->modalSubmitActionLabel('Zahlungseingang bestätigen')
|
||||||
|
->schema([
|
||||||
|
TextInput::make('reference')->label('Rechnungsnummer oder Buchungsreferenz')->required()->maxLength(120)
|
||||||
|
->helperText('Bleibt an der Zahlung gespeichert, zum Beispiel „RE-2026-014“.'),
|
||||||
|
DatePicker::make('received_on')->label('Zahlungseingang am')->required()->native(false)->displayFormat('d.m.Y')
|
||||||
|
->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||||
|
->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||||
|
->helperText('Der Tag, an dem das Geld auf dem Konto einging. Er bestimmt, in welchen Zeitraum die Einnahme im Zahlungsjournal fällt.'),
|
||||||
|
])
|
||||||
|
->visible(fn (): bool => $this->order()->payment_method === 'rechnung' && $this->order()->status === 'offen')
|
||||||
|
->action(function (array $data): void {
|
||||||
|
$this->report(function () use ($data): string {
|
||||||
|
app(Checkout::class)->confirmInvoicePayment($this->order(), (string) $data['reference'], Filament::auth()->user(), (string) $data['received_on']);
|
||||||
|
|
||||||
|
return 'Der Zahlungseingang ist bestätigt. Die Inhalte sind freigeschaltet.';
|
||||||
|
}, 'Bestätigt.');
|
||||||
|
$this->order()->unsetRelations();
|
||||||
|
$this->order()->refresh();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function refundAction(): Action
|
||||||
|
{
|
||||||
|
return Action::make('refund')
|
||||||
|
->label('Bestellung erstatten')
|
||||||
|
->color('danger')
|
||||||
|
->modalHeading(fn (): string => 'Bestellung '.$this->order()->id.' vollständig erstatten?')
|
||||||
|
->modalDescription(fn (): string => 'Alle Positionen dieser Bestellung werden zurückgegeben: Die Berechtigungen daraus werden widerrufen, andere Erwerbsquellen (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Pakete sind eine Einheit; Teilerstattungen gibt es zum Start nicht. '.(
|
||||||
|
$this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists()
|
||||||
|
? 'Die Rückzahlung von '.Money::format($this->order()->payable()).' wird bei Stripe veranlasst; nur wenn Stripe sie annimmt, werden die Rechte entzogen.'
|
||||||
|
: 'Die Rückzahlung selbst veranlasst du außerhalb dieser Anwendung, zum Beispiel per Überweisung.'
|
||||||
|
))
|
||||||
|
->modalSubmitActionLabel('Vollständig erstatten')
|
||||||
|
->schema([
|
||||||
|
Textarea::make('reason')->label('Begründung')->required()->rows(2)->maxLength(500)
|
||||||
|
->helperText('Bleibt am Widerruf der Berechtigungen und im Zahlungsjournal stehen, zum Beispiel „Widerruf geprüft, Frist gewahrt“.'),
|
||||||
|
DatePicker::make('refunded_on')->label('Rückzahlung am')->native(false)->displayFormat('d.m.Y')
|
||||||
|
->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||||
|
->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||||
|
->visible(fn (): bool => ! $this->hasStripePayment())
|
||||||
|
->helperText('Der Tag, an dem du das Geld zurücküberwiesen hast. Bei Stripe gilt der Zeitpunkt von Stripe.'),
|
||||||
|
TextInput::make('refund_reference')->label('Referenz der Rückzahlung')->maxLength(120)
|
||||||
|
->visible(fn (): bool => ! $this->hasStripePayment())
|
||||||
|
->helperText('Optional, zum Beispiel Buchungstext oder Gutschriftnummer.'),
|
||||||
|
])
|
||||||
|
->visible(fn (): bool => $this->order()->status === 'bezahlt')
|
||||||
|
->action(function (array $data): void {
|
||||||
|
$this->report(function () use ($data): string {
|
||||||
|
app(Checkout::class)->refund(
|
||||||
|
$this->order(),
|
||||||
|
(string) $data['reason'],
|
||||||
|
null,
|
||||||
|
Filament::auth()->user(),
|
||||||
|
$this->hasStripePayment() ? null : ($data['refunded_on'] ?? null),
|
||||||
|
$this->hasStripePayment() ? null : ($data['refund_reference'] ?? null),
|
||||||
|
);
|
||||||
|
|
||||||
|
return 'Die Bestellung ist erstattet. Die Berechtigungen sind widerrufen.';
|
||||||
|
}, 'Erstattet.');
|
||||||
|
$this->order()->unsetRelations();
|
||||||
|
$this->order()->refresh();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function bestellDaten(): array
|
||||||
|
{
|
||||||
|
$order = $this->order();
|
||||||
|
$order->loadMissing(['lines', 'user', 'party', 'payments']);
|
||||||
|
$date = fn (?Carbon $value): string => $value === null ? '' : $value->timezone(config('app.timezone'))->format('d.m.Y H:i');
|
||||||
|
$method = match ($order->payment_method) {
|
||||||
|
'rechnung' => 'Überweisung auf Rechnung (manuell)',
|
||||||
|
'stripe' => 'Stripe',
|
||||||
|
default => 'Testzahlung',
|
||||||
|
};
|
||||||
|
|
||||||
|
return [
|
||||||
|
'kopf' => [
|
||||||
|
'brot' => [['label' => 'Bestellungen', 'href' => OrderResource::getUrl('index')], 'Bestellung '.$order->id],
|
||||||
|
'titel' => 'Bestellung '.$order->id,
|
||||||
|
'typ' => 'Lizenzinhaber: '.($order->party?->display_name ?? '–').' · bestellt von '.($order->user?->name ?? '–').' ('.($order->user?->email ?? '').')',
|
||||||
|
'status' => [
|
||||||
|
['text' => match ($order->status) {
|
||||||
|
'bezahlt' => 'Bezahlt ('.$method.')',
|
||||||
|
'erstattet' => 'Erstattet. Die Berechtigungen sind widerrufen.',
|
||||||
|
'fehlgeschlagen' => 'Zahlung fehlgeschlagen. Es wurde nichts freigeschaltet.',
|
||||||
|
default => $order->payment_method === 'rechnung' ? 'Offen: Rechnung erstellen und Zahlungseingang bestätigen.' : 'Offen: Zahlung steht aus.',
|
||||||
|
}, 'ton' => $order->status === 'bezahlt' ? 'gut' : 'offen'],
|
||||||
|
$order->withdrawal_requested_at !== null ? ['text' => 'Widerruf erklärt am '.$date($order->withdrawal_requested_at).'. Prüfen und gegebenenfalls erstatten.', 'ton' => 'offen'] : null,
|
||||||
|
],
|
||||||
|
'aktionen' => [
|
||||||
|
...($order->payment_method === 'rechnung' && $order->status === 'offen' ? [['label' => 'Zahlungseingang bestätigen', 'wire' => "mountAction('confirmInvoice')", 'art' => 'primary']] : []),
|
||||||
|
...($order->status === 'bezahlt' ? [['label' => 'Bestellung erstatten', 'wire' => "mountAction('refund')", 'art' => 'line']] : []),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
'haupt' => [
|
||||||
|
[
|
||||||
|
'titel' => 'Positionen',
|
||||||
|
'hilfe' => 'Fassung, Preis, Rabatt, Nutzerkreis und Umfang sind beim Kauf festgehalten und ändern sich nicht.',
|
||||||
|
'zeilen' => $order->lines->map(fn (OrderLine $line): array => [
|
||||||
|
'text' => ($line->offer_name ?: 'Angebot').': '.Money::format((int) $line->price_cents).($line->discount_cents > 0 ? ' − Rabatt '.Money::format((int) $line->discount_cents).' = '.Money::format($line->payable()) : ''),
|
||||||
|
'neben' => LicenceScope::label($line->licence_scope, $line->trainer_count).' · Angebotsfassung '.($line->offerVersion?->number ?? '–'),
|
||||||
|
])->values()->all(),
|
||||||
|
'leer' => ['titel' => 'Keine Positionen', 'text' => 'Diese Bestellung hat keine Positionen.'],
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'titel' => 'Beträge',
|
||||||
|
'zeilen' => [
|
||||||
|
['text' => 'Zwischensumme (Listenpreise): '.Money::format($order->subtotal()), 'neben' => null],
|
||||||
|
...($order->discount_cents > 0 ? [['text' => 'Rabatt: −'.Money::format((int) $order->discount_cents), 'neben' => 'Code '.($order->discount_snapshot['code'] ?? '').' · '.($order->discount_snapshot['label'] ?? '')]] : []),
|
||||||
|
['text' => 'Zahlbetrag: '.Money::format($order->payable()), 'neben' => 'Dieser Betrag ging an '.$method.'.'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'titel' => 'Zahlungen',
|
||||||
|
'zeilen' => $order->payments->map(fn (Payment $payment): array => [
|
||||||
|
'text' => match ($payment->provider) {
|
||||||
|
'stripe' => 'Stripe', 'ueberweisung' => 'Überweisung', default => 'Testzahlung'
|
||||||
|
}.' · '.match ($payment->status) {
|
||||||
|
'bestaetigt' => 'bestätigt', 'erstattet' => 'erstattet', 'offen' => 'offen', 'abgelaufen' => 'abgelaufen', 'zu_pruefen' => 'zu prüfen', 'fehlgeschlagen' => 'fehlgeschlagen', default => $payment->status
|
||||||
|
},
|
||||||
|
'neben' => $payment->provider_reference.($payment->amount_cents !== null ? ' · '.Money::format((int) $payment->amount_cents) : ''),
|
||||||
|
])->values()->all(),
|
||||||
|
'leer' => ['titel' => 'Noch keine Zahlung', 'text' => 'Es gibt noch keinen Zahlungsvorgang zu dieser Bestellung.'],
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'titel' => 'Buchungen im Zahlungsjournal',
|
||||||
|
'hilfe' => 'Unveränderlich festgehalten, mit Datum, Beleg beim Anbieter und Rechnungsempfänger zum Zeitpunkt der Buchung. Alle Buchungen eines Zeitraums und den Export findest du unter „Einnahmen und Erstattungen“.',
|
||||||
|
'zeilen' => LedgerEntry::query()->where('order_id', $order->id)->orderBy('occurred_at')->orderBy('id')->get()->map(fn (LedgerEntry $entry): array => [
|
||||||
|
'text' => PaymentJournal::local($entry->occurred_at)->format('d.m.Y').' · '.($entry->isRefund() ? 'Erstattung −' : 'Zahlungseingang ').Money::format(abs($entry->amount_cents)).($entry->live ? '' : ' (Test, kein Umsatz)').($entry->derived ? ' (nachgetragen)' : ''),
|
||||||
|
'neben' => PaymentJournal::providerLabel($entry->provider).' · '.$entry->provider_reference.(filled($entry->actor_name) ? ' · gebucht von '.$entry->actor_name : ''),
|
||||||
|
])->values()->all(),
|
||||||
|
'leer' => ['titel' => 'Noch keine Buchung', 'text' => 'Zahlungseingang und Erstattung dieser Bestellung erscheinen hier.'],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
'seite' => [
|
||||||
|
[
|
||||||
|
'titel' => 'Zustimmung',
|
||||||
|
'zeilen' => $order->terms_accepted_at === null ? [] : [
|
||||||
|
['text' => 'Zugestimmt am '.$date($order->terms_accepted_at), 'neben' => 'Fassung der Texte: '.($order->terms_snapshot['version'] ?? '–')],
|
||||||
|
...collect($order->terms_snapshot['consents'] ?? [])->map(fn (string $wording): array => ['text' => $wording, 'neben' => null])->values()->all(),
|
||||||
|
],
|
||||||
|
'leer' => 'Zu dieser Bestellung ist keine Zustimmung festgehalten (Bestellung vor dem Verkaufsstart oder über den Testweg).',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'titel' => 'Widerruf',
|
||||||
|
'zeilen' => $order->withdrawal_requested_at === null ? [] : [
|
||||||
|
['text' => 'Erklärt am '.$date($order->withdrawal_requested_at), 'neben' => filled($order->withdrawal_note) ? $order->withdrawal_note : null],
|
||||||
|
],
|
||||||
|
'leer' => 'Kein Widerruf erklärt.',
|
||||||
|
'hilfe' => 'Der Widerruf entzieht nichts. Du prüfst ihn (bei sofortiger Bereitstellung mit Zustimmung kann das Recht erloschen sein) und erstattest bei Bedarf über „Bestellung erstatten“.',
|
||||||
|
],
|
||||||
|
],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\Practices\Pages;
|
||||||
|
|
||||||
|
use App\Filament\Resources\Compositions\Pages\EditComposition;
|
||||||
|
use App\Filament\Resources\Practices\PracticeResource;
|
||||||
|
|
||||||
|
class EditPractice extends EditComposition
|
||||||
|
{
|
||||||
|
protected static string $resource = PracticeResource::class;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\Practices\Pages;
|
||||||
|
|
||||||
|
use App\Domain\Catalog\CompositionKind;
|
||||||
|
use App\Filament\Resources\Compositions\Pages\ListCompositionKind;
|
||||||
|
use App\Filament\Resources\Practices\PracticeResource;
|
||||||
|
|
||||||
|
class ListPractices extends ListCompositionKind
|
||||||
|
{
|
||||||
|
protected static string $resource = PracticeResource::class;
|
||||||
|
|
||||||
|
protected function kind(): CompositionKind
|
||||||
|
{
|
||||||
|
return CompositionKind::Exercise;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Resources\Practices;
|
||||||
|
|
||||||
|
use App\Domain\Catalog\CompositionKind;
|
||||||
|
use App\Filament\Resources\Compositions\CompositionKindResource;
|
||||||
|
use App\Filament\Resources\Practices\Pages\EditPractice;
|
||||||
|
use App\Filament\Resources\Practices\Pages\ListPractices;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Die fachliche Übung. Der ältere Eintrag „Module“ (`ExerciseResource`, Adresse `uebungen`) bleibt unverändert und
|
||||||
|
* zeigt die Zusammenstellungen der Art `uebung`; hier stehen die Übungen mit Varianten.
|
||||||
|
*/
|
||||||
|
class PracticeResource extends CompositionKindResource
|
||||||
|
{
|
||||||
|
protected static ?string $slug = 'fachuebungen';
|
||||||
|
|
||||||
|
protected static ?string $navigationLabel = 'Übungen';
|
||||||
|
|
||||||
|
protected static ?string $modelLabel = 'Übung';
|
||||||
|
|
||||||
|
protected static ?string $pluralModelLabel = 'Übungen';
|
||||||
|
|
||||||
|
protected static ?int $navigationSort = 5;
|
||||||
|
|
||||||
|
public static function kind(): CompositionKind
|
||||||
|
{
|
||||||
|
return CompositionKind::Exercise;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function getPages(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'index' => ListPractices::route('/'),
|
||||||
|
'edit' => EditPractice::route('/{record}'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,7 +37,7 @@ public static function assignmentTargets(?int $exceptCompositionId = null): arra
|
|||||||
$media['element:'.$version->id] = self::elementLabel($version);
|
$media['element:'.$version->id] = self::elementLabel($version);
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->with('composition.editorialContentKind')->orderBy('id')->get() as $version) {
|
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->whereHas('composition')->with('composition.editorialContentKind')->orderBy('id')->get() as $version) {
|
||||||
if ($exceptCompositionId !== null && (int) $version->composition_id === $exceptCompositionId) {
|
if ($exceptCompositionId !== null && (int) $version->composition_id === $exceptCompositionId) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -94,7 +94,7 @@ public static function readyTargets(): array
|
|||||||
$options['element:'.$version->id] = self::elementLabel($version);
|
$options['element:'.$version->id] = self::elementLabel($version);
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->with('composition.editorialContentKind')->orderBy('id')->get() as $version) {
|
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->whereHas('composition')->with('composition.editorialContentKind')->orderBy('id')->get() as $version) {
|
||||||
$options['composition:'.$version->id] = self::compositionLabel($version);
|
$options['composition:'.$version->id] = self::compositionLabel($version);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -266,7 +266,7 @@ public function elementUsage(ContentElement $element): array
|
|||||||
->get();
|
->get();
|
||||||
|
|
||||||
foreach ($members as $member) {
|
foreach ($members as $member) {
|
||||||
$lines[] = self::compositionLabel($member->compositionVersion->composition)
|
$lines[] = self::compositionLabelOf($member->compositionVersion->composition)
|
||||||
.' · Fassung '.$member->compositionVersion->number
|
.' · Fassung '.$member->compositionVersion->number
|
||||||
.' · Rolle '.$member->role;
|
.' · Rolle '.$member->role;
|
||||||
}
|
}
|
||||||
@@ -280,7 +280,9 @@ public function elementUsage(ContentElement $element): array
|
|||||||
foreach ($contents as $content) {
|
foreach ($contents as $content) {
|
||||||
$lines[] = 'Lizenzartikel '.$content->release->article->code
|
$lines[] = 'Lizenzartikel '.$content->release->article->code
|
||||||
.' · Stand '.$content->release->number
|
.' · Stand '.$content->release->number
|
||||||
.' · '.$content->path;
|
.' · '.$content->path
|
||||||
|
.($content->variant_key !== null ? ' · Variante '.$content->variant_key : '')
|
||||||
|
.($content->requirement === CompositionMember::SUPPLEMENTARY ? ' · ergänzend' : '');
|
||||||
}
|
}
|
||||||
|
|
||||||
return $lines === []
|
return $lines === []
|
||||||
@@ -313,7 +315,7 @@ public function compositionMembers(Composition $composition): array
|
|||||||
}
|
}
|
||||||
|
|
||||||
$nested = $member->nestedCompositionVersion;
|
$nested = $member->nestedCompositionVersion;
|
||||||
$lines[] = $member->role.' — '.($nested === null ? 'fehlt' : self::compositionLabel($nested->composition));
|
$lines[] = $member->role.' — '.($nested === null ? 'fehlt' : self::compositionLabelOf($nested->composition));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $lines;
|
return $lines;
|
||||||
@@ -365,7 +367,7 @@ public function compositionUsage(Composition $composition): array
|
|||||||
->get();
|
->get();
|
||||||
|
|
||||||
foreach ($parents as $member) {
|
foreach ($parents as $member) {
|
||||||
$lines[] = self::compositionLabel($member->compositionVersion->composition)
|
$lines[] = self::compositionLabelOf($member->compositionVersion->composition)
|
||||||
.' · Fassung '.$member->compositionVersion->number
|
.' · Fassung '.$member->compositionVersion->number
|
||||||
.' · Rolle '.$member->role;
|
.' · Rolle '.$member->role;
|
||||||
}
|
}
|
||||||
@@ -448,6 +450,16 @@ private function purpose(string $purpose): string
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Eine Zusammenstellung, die dieser Programmstand nicht kennt, erscheint nur als Hinweis ohne Namen und Inhalt.
|
||||||
|
*/
|
||||||
|
private static function compositionLabelOf(?Composition $composition): string
|
||||||
|
{
|
||||||
|
return $composition === null
|
||||||
|
? 'Zusammenstellung einer neueren Programmversion'
|
||||||
|
: self::compositionLabel($composition);
|
||||||
|
}
|
||||||
|
|
||||||
private static function compositionLabel(Composition $composition): string
|
private static function compositionLabel(Composition $composition): string
|
||||||
{
|
{
|
||||||
$kind = $composition->kind;
|
$kind = $composition->kind;
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Support;
|
||||||
|
|
||||||
|
use App\Domain\Catalog\Bundle;
|
||||||
|
use App\Domain\Catalog\Offer;
|
||||||
|
use App\Domain\Commerce\Discount\DiscountCode;
|
||||||
|
use Filament\Forms\Components\DatePicker;
|
||||||
|
use Filament\Forms\Components\Select;
|
||||||
|
use Filament\Forms\Components\Textarea;
|
||||||
|
use Filament\Forms\Components\TextInput;
|
||||||
|
use Filament\Forms\Components\Toggle;
|
||||||
|
use Filament\Schemas\Components\Utilities\Get;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Die eine Maske für Rabattcodes: Anlegen und Bearbeiten nutzen dieselben Felder (FACH-20). Geltungsbereich und
|
||||||
|
* Einlösungsberechtigung sind zwei voneinander unabhängige Einstellungen.
|
||||||
|
*/
|
||||||
|
final class DiscountCodeForm
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return list<mixed>
|
||||||
|
*/
|
||||||
|
public static function schema(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
TextInput::make('code')->label('Code')->required()->maxLength(40)
|
||||||
|
->helperText('So gibt ihn der Käufer ein, 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich. Groß- und Kleinschreibung spielen keine Rolle.'),
|
||||||
|
TextInput::make('label')->label('Name für die Verwaltung')->required()->maxLength(120)
|
||||||
|
->helperText('Nur intern, zum Beispiel „Zertifizierungscode 2026“. Der Käufer sieht ihn nicht.'),
|
||||||
|
Select::make('kind')->label('Art des Rabatts')->options([
|
||||||
|
DiscountCode::PERCENT => 'Prozent',
|
||||||
|
DiscountCode::AMOUNT => 'Fester Betrag in Euro',
|
||||||
|
])->required()->live(),
|
||||||
|
TextInput::make('percent')->label('Prozent')->numeric()->minValue(1)->maxValue(100)->integer()->suffix('%')
|
||||||
|
->required(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT)
|
||||||
|
->visible(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT)
|
||||||
|
->helperText('Je Position gerundet. Der Zahlbetrag der Bestellung darf 0,50 € nicht unterschreiten.'),
|
||||||
|
TextInput::make('amount_euro')->label('Rabattbetrag')->suffix('€')
|
||||||
|
->required(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT)
|
||||||
|
->visible(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT)
|
||||||
|
->helperText('Gilt je Bestellung und wird anteilig auf die betroffenen Positionen verteilt, zum Beispiel 5,00.'),
|
||||||
|
Select::make('scope')->label('Geltungsbereich')->options([
|
||||||
|
DiscountCode::SCOPE_CART => 'Gesamter Warenkorb',
|
||||||
|
DiscountCode::SCOPE_SELECTED => 'Nur ausdrücklich ausgewählte Angebote, Lizenzartikel oder Pakete',
|
||||||
|
])->required()->live()
|
||||||
|
->helperText('Wofür der Rabatt gilt. Unabhängig davon legst du unten fest, wer den Code einlösen darf.'),
|
||||||
|
Select::make('offer_ids')->label('Angebote')->multiple()->searchable()
|
||||||
|
->options(fn (): array => Offer::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||||
|
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
|
||||||
|
->helperText('Die gewählte Lizenzoption selbst (Fassung egal).'),
|
||||||
|
Select::make('article_ids')->label('Lizenzartikel')->multiple()->searchable()
|
||||||
|
->options(fn (): array => app(PublicationReadiness::class)->articleOptions())
|
||||||
|
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
|
||||||
|
->helperText('Gilt für Angebote, die diesen Artikel unmittelbar als Position führen. Ein Artikel in einem Paket macht das Paket nicht rabattfähig.'),
|
||||||
|
Select::make('bundle_ids')->label('Pakete')->multiple()->searchable()
|
||||||
|
->options(fn (): array => Bundle::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||||
|
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
|
||||||
|
->helperText('Ein Paket wird gezielt gewählt. Es folgt nicht aus einem enthaltenen Artikel.'),
|
||||||
|
Select::make('eligibility')->label('Wer darf den Code einlösen?')->options([
|
||||||
|
DiscountCode::OPEN => 'Alle angemeldeten Käufer (allgemein einlösbar)',
|
||||||
|
DiscountCode::RESTRICTED => 'Nur ausdrücklich freigeschaltete Konten',
|
||||||
|
])->required()
|
||||||
|
->helperText('Bei „freigeschaltete Konten“ schaltest du einzelne Konten auf der Seite des Codes frei und entziehst die Freigabe wieder. Eine Freigabe gilt nur für diesen Code.'),
|
||||||
|
DatePicker::make('valid_from')->label('Gültig ab')->native(false)->displayFormat('d.m.Y')
|
||||||
|
->helperText('Leer: sofort.'),
|
||||||
|
DatePicker::make('valid_until')->label('Gültig bis einschließlich')->native(false)->displayFormat('d.m.Y')
|
||||||
|
->helperText('Leer: unbegrenzt. Am Tag danach gilt der Code nicht mehr.'),
|
||||||
|
Toggle::make('active')->label('Aktiv')->default(true)
|
||||||
|
->helperText('Deaktivierte Codes lassen sich nicht einlösen; bereits aufgegebene Bestellungen bleiben unverändert.'),
|
||||||
|
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(500)
|
||||||
|
->helperText('Zum Beispiel, woran die Berechtigung geprüft wird.'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formularwerte → Angaben und Ziele des Dienstes.
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $data
|
||||||
|
* @return array{0: array<string, mixed>, 1: list<array{type: string, id: int}>}
|
||||||
|
*/
|
||||||
|
public static function fromForm(array $data): array
|
||||||
|
{
|
||||||
|
$targets = [];
|
||||||
|
|
||||||
|
foreach ([
|
||||||
|
DiscountCode::TARGET_OFFER => 'offer_ids',
|
||||||
|
DiscountCode::TARGET_ARTICLE => 'article_ids',
|
||||||
|
DiscountCode::TARGET_BUNDLE => 'bundle_ids',
|
||||||
|
] as $type => $key) {
|
||||||
|
foreach ((array) ($data[$key] ?? []) as $id) {
|
||||||
|
$targets[] = ['type' => $type, 'id' => (int) $id];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$data, $targets];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vorbelegung der Maske aus einem vorhandenen Code.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public static function fill(DiscountCode $code): array
|
||||||
|
{
|
||||||
|
$code->loadMissing('targets');
|
||||||
|
$ids = fn (string $type): array => $code->targets->where('target_type', $type)->pluck('target_id')->map(fn ($id): int => (int) $id)->values()->all();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'code' => $code->code,
|
||||||
|
'label' => $code->label,
|
||||||
|
'kind' => $code->kind,
|
||||||
|
'percent' => $code->percent,
|
||||||
|
'amount_euro' => $code->amount_cents === null ? null : number_format($code->amount_cents / 100, 2, ',', ''),
|
||||||
|
'scope' => $code->scope,
|
||||||
|
'offer_ids' => $ids(DiscountCode::TARGET_OFFER),
|
||||||
|
'article_ids' => $ids(DiscountCode::TARGET_ARTICLE),
|
||||||
|
'bundle_ids' => $ids(DiscountCode::TARGET_BUNDLE),
|
||||||
|
'eligibility' => $code->eligibility,
|
||||||
|
'valid_from' => $code->valid_from?->timezone(config('app.timezone'))->toDateString(),
|
||||||
|
'valid_until' => $code->valid_until?->timezone(config('app.timezone'))->toDateString(),
|
||||||
|
'active' => $code->active,
|
||||||
|
'note' => $code->note,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@
|
|||||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||||
use App\Filament\Resources\Courses\CourseResource;
|
use App\Filament\Resources\Courses\CourseResource;
|
||||||
use App\Filament\Resources\Exercises\ExerciseResource;
|
use App\Filament\Resources\Exercises\ExerciseResource;
|
||||||
|
use App\Filament\Resources\Practices\PracticeResource;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -33,6 +34,7 @@ class EditorialCatalog
|
|||||||
public function rows(CompositionVersion $version, int $exceptCompositionId): array
|
public function rows(CompositionVersion $version, int $exceptCompositionId): array
|
||||||
{
|
{
|
||||||
$version->loadMissing([
|
$version->loadMissing([
|
||||||
|
'members.variant',
|
||||||
'members.contentElementVersion.element.editorialContentKind',
|
'members.contentElementVersion.element.editorialContentKind',
|
||||||
'members.nestedCompositionVersion.composition.editorialContentKind',
|
'members.nestedCompositionVersion.composition.editorialContentKind',
|
||||||
]);
|
]);
|
||||||
@@ -50,6 +52,10 @@ public function rows(CompositionVersion $version, int $exceptCompositionId): arr
|
|||||||
|
|
||||||
$row['role'] = $member->role;
|
$row['role'] = $member->role;
|
||||||
$row['note'] = trim((string) ($member->placement_note ?? ''));
|
$row['note'] = trim((string) ($member->placement_note ?? ''));
|
||||||
|
$row['variant'] = $member->variant?->key;
|
||||||
|
$row['requirement'] = $member->requirement ?: 'erforderlich';
|
||||||
|
$row['selection'] = is_array($member->variant_selection) ? $member->variant_selection : null;
|
||||||
|
$row['origin'] = $member->origin ?: 'lokal';
|
||||||
$rows[] = $row;
|
$rows[] = $row;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,6 +146,12 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
|
|||||||
}
|
}
|
||||||
|
|
||||||
$composition = $version->composition;
|
$composition = $version->composition;
|
||||||
|
|
||||||
|
// Art, die dieser Programmstand nicht kennt: nicht anbieten und nicht laden (Rückfallschutz).
|
||||||
|
if ($composition === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
$kind = $composition->editorialContentKind?->label
|
$kind = $composition->editorialContentKind?->label
|
||||||
?: ($composition->kind instanceof CompositionKind ? $composition->kind->deskLabel() : 'Zusammenstellung');
|
?: ($composition->kind instanceof CompositionKind ? $composition->kind->deskLabel() : 'Zusammenstellung');
|
||||||
|
|
||||||
@@ -238,7 +250,11 @@ public function search(string $query, string $scope, int $exceptCompositionId):
|
|||||||
->with('composition.editorialContentKind')
|
->with('composition.editorialContentKind')
|
||||||
->whereHas('composition', function ($builder) use ($scope, $query, $like): void {
|
->whereHas('composition', function ($builder) use ($scope, $query, $like): void {
|
||||||
if ($scope === 'module') {
|
if ($scope === 'module') {
|
||||||
$builder->where('kind', CompositionKind::Uebung);
|
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($scope === 'uebungen') {
|
||||||
|
$builder->where('kind', CompositionKind::Exercise);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($query === '') {
|
if ($query === '') {
|
||||||
@@ -311,7 +327,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
|||||||
->where('composition_id', '!=', $exceptCompositionId)
|
->where('composition_id', '!=', $exceptCompositionId)
|
||||||
->whereHas('composition', function ($builder) use ($query, $like, $kind, $dimensionId, $pillarId): void {
|
->whereHas('composition', function ($builder) use ($query, $like, $kind, $dimensionId, $pillarId): void {
|
||||||
if ($kind === 'modul') {
|
if ($kind === 'modul') {
|
||||||
$builder->where('kind', CompositionKind::Uebung);
|
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($dimensionId > 0) {
|
if ($dimensionId > 0) {
|
||||||
@@ -357,7 +373,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
|||||||
$builder->where('status', ContentVersionStatus::Bereit);
|
$builder->where('status', ContentVersionStatus::Bereit);
|
||||||
})
|
})
|
||||||
->when($kind === 'modul', function ($builder): void {
|
->when($kind === 'modul', function ($builder): void {
|
||||||
$builder->where('kind', CompositionKind::Uebung);
|
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
|
||||||
})
|
})
|
||||||
->orderByDesc('id')
|
->orderByDesc('id')
|
||||||
->get();
|
->get();
|
||||||
@@ -1028,6 +1044,10 @@ private function suggestPicture(array $members, array $seen = []): ?array
|
|||||||
|
|
||||||
$nested = $version->composition;
|
$nested = $version->composition;
|
||||||
|
|
||||||
|
if ($nested === null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if ($this->cardUrl('komposition', $nested->id, $nested->thumbnail_path) !== null) {
|
if ($this->cardUrl('komposition', $nested->id, $nested->thumbnail_path) !== null) {
|
||||||
return [
|
return [
|
||||||
'kind' => 'komposition',
|
'kind' => 'komposition',
|
||||||
@@ -1063,6 +1083,7 @@ public function create(string $designation, CompositionKind $kind): Composition
|
|||||||
$slug = match ($kind) {
|
$slug = match ($kind) {
|
||||||
CompositionKind::Kurs => 'programm',
|
CompositionKind::Kurs => 'programm',
|
||||||
CompositionKind::Uebung => 'modul',
|
CompositionKind::Uebung => 'modul',
|
||||||
|
CompositionKind::Exercise => 'uebung',
|
||||||
default => null,
|
default => null,
|
||||||
};
|
};
|
||||||
$editorial = $slug === null ? null : EditorialContentKind::query()->where('slug', $slug)->first();
|
$editorial = $slug === null ? null : EditorialContentKind::query()->where('slug', $slug)->first();
|
||||||
@@ -1084,6 +1105,7 @@ public static function editUrl(Composition $composition): string
|
|||||||
CompositionKind::Kurs => CourseResource::class,
|
CompositionKind::Kurs => CourseResource::class,
|
||||||
CompositionKind::Kombination => CombinationResource::class,
|
CompositionKind::Kombination => CombinationResource::class,
|
||||||
CompositionKind::Uebung => ExerciseResource::class,
|
CompositionKind::Uebung => ExerciseResource::class,
|
||||||
|
CompositionKind::Exercise => PracticeResource::class,
|
||||||
};
|
};
|
||||||
|
|
||||||
return $resource::getUrl('edit', ['record' => $composition]);
|
return $resource::getUrl('edit', ['record' => $composition]);
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ public function bestand(): array
|
|||||||
$einheit = match ($fixed) {
|
$einheit = match ($fixed) {
|
||||||
CompositionKind::Kurs => ['Programm', 'Programme'],
|
CompositionKind::Kurs => ['Programm', 'Programme'],
|
||||||
CompositionKind::Uebung => ['Modul', 'Module'],
|
CompositionKind::Uebung => ['Modul', 'Module'],
|
||||||
|
CompositionKind::Exercise => ['Übung', 'Übungen'],
|
||||||
CompositionKind::Kombination => ['Fachliche Kombination', 'Fachliche Kombinationen'],
|
CompositionKind::Kombination => ['Fachliche Kombination', 'Fachliche Kombinationen'],
|
||||||
default => ['Programm oder Modul', 'Programme und Module'],
|
default => ['Programm oder Modul', 'Programme und Module'],
|
||||||
};
|
};
|
||||||
@@ -188,7 +189,7 @@ public function entries(): array
|
|||||||
$rows[] = [
|
$rows[] = [
|
||||||
'schluessel' => 'c'.$composition->id,
|
'schluessel' => 'c'.$composition->id,
|
||||||
'titel' => $title,
|
'titel' => $title,
|
||||||
'meta' => $kind->deskLabel().($title !== $composition->designation ? ' · '.$composition->designation : ''),
|
'meta' => $kind->deskLabel().($title !== $composition->designation ? ' · '.$composition->designation : '').($kind === CompositionKind::Exercise ? ' · Herkunft: lokal' : ''),
|
||||||
'text' => $summary,
|
'text' => $summary,
|
||||||
'bild' => $cover['url'],
|
'bild' => $cover['url'],
|
||||||
'bildFehlt' => 'Kein Titelbild',
|
'bildFehlt' => 'Kein Titelbild',
|
||||||
@@ -219,11 +220,19 @@ public function entries(): array
|
|||||||
*/
|
*/
|
||||||
protected function createCompositionAction(CompositionKind $kind): Action
|
protected function createCompositionAction(CompositionKind $kind): Action
|
||||||
{
|
{
|
||||||
$label = $kind === CompositionKind::Kurs ? 'Programm' : 'Modul';
|
$label = match ($kind) {
|
||||||
|
CompositionKind::Kurs => 'Programm',
|
||||||
|
CompositionKind::Exercise => 'Übung',
|
||||||
|
default => 'Modul',
|
||||||
|
};
|
||||||
|
|
||||||
return Action::make($kind === CompositionKind::Kurs ? 'createProgram' : 'createModule')
|
return Action::make(match ($kind) {
|
||||||
|
CompositionKind::Kurs => 'createProgram',
|
||||||
|
CompositionKind::Exercise => 'createExercise',
|
||||||
|
default => 'createModule',
|
||||||
|
})
|
||||||
->label($label.' anlegen')
|
->label($label.' anlegen')
|
||||||
->modalHeading('Neues '.$label)
|
->modalHeading(($kind === CompositionKind::Exercise ? 'Neue ' : 'Neues ').$label)
|
||||||
->modalDescription('Der Name genügt. Danach öffnet sich der Aufbau; Texte, Bilder und Einordnung folgen dort und in der Redaktion.')
|
->modalDescription('Der Name genügt. Danach öffnet sich der Aufbau; Texte, Bilder und Einordnung folgen dort und in der Redaktion.')
|
||||||
->modalSubmitActionLabel($label.' anlegen')
|
->modalSubmitActionLabel($label.' anlegen')
|
||||||
->modalWidth('lg')
|
->modalWidth('lg')
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
use App\Domain\Catalog\BundleStatus;
|
use App\Domain\Catalog\BundleStatus;
|
||||||
use App\Domain\Catalog\BundleVersion;
|
use App\Domain\Catalog\BundleVersion;
|
||||||
use App\Domain\Catalog\DomainRuleException;
|
use App\Domain\Catalog\DomainRuleException;
|
||||||
|
use App\Domain\Catalog\LicenceScope;
|
||||||
use App\Domain\Catalog\LicenseArticle;
|
use App\Domain\Catalog\LicenseArticle;
|
||||||
use App\Domain\Catalog\Offer;
|
use App\Domain\Catalog\Offer;
|
||||||
use App\Domain\Catalog\OfferService;
|
use App\Domain\Catalog\OfferService;
|
||||||
@@ -227,7 +228,8 @@ public function forOffer(Offer $offer): array
|
|||||||
$missing = $this->unusableArticles($articleIds);
|
$missing = $this->unusableArticles($articleIds);
|
||||||
$buyable = $hasActive && $this->offers->purchasableVersion($offer) !== null;
|
$buyable = $hasActive && $this->offers->purchasableVersion($offer) !== null;
|
||||||
$page = $offer->composition;
|
$page = $offer->composition;
|
||||||
$shown = $page !== null && $this->catalog->shownVersion($page) !== null;
|
$own = (bool) $offer->standalone_bundle;
|
||||||
|
$shown = $own || ($page !== null && $this->catalog->shownVersion($page) !== null);
|
||||||
$pageName = $page !== null ? (string) ($page->display_title ?: $page->designation) : '';
|
$pageName = $page !== null ? (string) ($page->display_title ?: $page->designation) : '';
|
||||||
$activate = ['label' => $hasActive ? 'Geänderte Fassung aktivieren' : 'Angebot konfigurieren', 'wire' => "mountAction('activate')"];
|
$activate = ['label' => $hasActive ? 'Geänderte Fassung aktivieren' : 'Angebot konfigurieren', 'wire' => "mountAction('activate')"];
|
||||||
|
|
||||||
@@ -258,21 +260,36 @@ public function forOffer(Offer $offer): array
|
|||||||
'stand' => $buyable ? 'erledigt' : 'offen',
|
'stand' => $buyable ? 'erledigt' : 'offen',
|
||||||
'aktion' => $buyable ? null : ($hasActive ? $activate : null),
|
'aktion' => $buyable ? null : ($hasActive ? $activate : null),
|
||||||
],
|
],
|
||||||
|
[
|
||||||
|
'titel' => 'Nutzerkreis festlegen',
|
||||||
|
'text' => ! $hasActive
|
||||||
|
? 'Wird mit der Fassung festgelegt: Einzellizenz (ein Trainer) oder Mehrfachlizenz (Zahl der Trainer).'
|
||||||
|
: ($active->licence_scope !== null
|
||||||
|
? LicenceScope::label($active->licence_scope, $active->trainer_count).'. Der Käufer sieht das auf der Produktseite und in der Bestellung.'
|
||||||
|
: 'Diese Fassung hat keinen festgelegten Nutzerkreis. Käufer sehen „Nutzerkreis nicht festgelegt“. Lege ihn mit „Geänderte Fassung aktivieren“ fest.'),
|
||||||
|
'stand' => $hasActive && $active->licence_scope !== null ? 'erledigt' : 'offen',
|
||||||
|
'aktion' => $hasActive && $active->licence_scope === null ? $activate : null,
|
||||||
|
'pflicht' => false,
|
||||||
|
],
|
||||||
[
|
[
|
||||||
'titel' => 'Produktseite zuordnen',
|
'titel' => 'Produktseite zuordnen',
|
||||||
'text' => $page !== null
|
'text' => $own
|
||||||
? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.'
|
? 'Eigene Paketseite: Sie zeigt den Umfang des Pakets. Optionen desselben Pakets sind Alternativen im Warenkorb.'
|
||||||
: 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket braucht eine eigene Produktseite, sonst ist es Alternative zu den Einzelangeboten dieser Seite.',
|
: ($page !== null
|
||||||
'stand' => $page !== null ? 'erledigt' : 'offen',
|
? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.'
|
||||||
'aktion' => $page !== null ? null : $activate,
|
: 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket, das für sich verkauft wird, erhält dort „Eigene Paketseite“ und zeigt seinen Umfang; sonst erscheint es auf der Seite eines fremden Programms.'),
|
||||||
|
'stand' => $own || $page !== null ? 'erledigt' : 'offen',
|
||||||
|
'aktion' => $own || $page !== null ? null : $activate,
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'titel' => 'Produktseite öffentlich',
|
'titel' => 'Produktseite öffentlich',
|
||||||
'text' => $page === null
|
'text' => ! $own && $page === null
|
||||||
? 'Wird geprüft, sobald eine Produktseite zugeordnet ist.'
|
? 'Wird geprüft, sobald eine Produktseite zugeordnet ist.'
|
||||||
: ($shown
|
: ($own
|
||||||
|
? 'Die eigene Paketseite ist öffentlich, sobald die aktive Fassung ein Kauf mit Preis ist.'
|
||||||
|
: ($shown
|
||||||
? 'Das Programm ist zur Anzeige freigegeben. Das Angebot erscheint in der Shop-Suche und auf der Produktseite.'
|
? 'Das Programm ist zur Anzeige freigegeben. Das Angebot erscheint in der Shop-Suche und auf der Produktseite.'
|
||||||
: 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.'),
|
: 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.')),
|
||||||
'stand' => $shown ? 'erledigt' : 'offen',
|
'stand' => $shown ? 'erledigt' : 'offen',
|
||||||
'aktion' => $page === null || $shown ? null : ['label' => 'Programm öffnen', 'href' => EditorialCatalog::editUrl($page)],
|
'aktion' => $page === null || $shown ? null : ['label' => 'Programm öffnen', 'href' => EditorialCatalog::editUrl($page)],
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Filament\Support;
|
||||||
|
|
||||||
|
use App\Domain\Identity\StaffRole;
|
||||||
|
use App\Models\User;
|
||||||
|
use Filament\Facades\Filament;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wer Rabattcodes, Freigaben und Bestellungen verwalten darf: Katalogverwalter und Kundenbetreuung. Die
|
||||||
|
* Berechtigung zum Verkaufen und Erstatten ist eine Betreiberaufgabe, nicht die der Redaktion.
|
||||||
|
*/
|
||||||
|
final class ShopAccess
|
||||||
|
{
|
||||||
|
public static function allowed(): bool
|
||||||
|
{
|
||||||
|
$user = Filament::auth()->user();
|
||||||
|
|
||||||
|
return $user instanceof User
|
||||||
|
&& ($user->hasStaffRole(StaffRole::Katalogverwalter) || $user->hasStaffRole(StaffRole::Kundenbetreuung));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
use App\Domain\Cms\Widgets\WidgetRegistry;
|
use App\Domain\Cms\Widgets\WidgetRegistry;
|
||||||
use App\Domain\Cms\Widgets\WidgetRenderer;
|
use App\Domain\Cms\Widgets\WidgetRenderer;
|
||||||
use App\Domain\Cms\Widgets\WidgetType;
|
use App\Domain\Cms\Widgets\WidgetType;
|
||||||
|
use App\Domain\Design\DesignSettings;
|
||||||
use Filament\Actions\Action;
|
use Filament\Actions\Action;
|
||||||
use Filament\Forms\Components\Builder;
|
use Filament\Forms\Components\Builder;
|
||||||
use Filament\Forms\Components\Builder\Block;
|
use Filament\Forms\Components\Builder\Block;
|
||||||
@@ -16,6 +17,7 @@
|
|||||||
use Filament\Forms\Components\ToggleButtons;
|
use Filament\Forms\Components\ToggleButtons;
|
||||||
use Filament\Notifications\Notification;
|
use Filament\Notifications\Notification;
|
||||||
use Filament\Schemas\Components\Grid;
|
use Filament\Schemas\Components\Grid;
|
||||||
|
use Filament\Schemas\Components\Group;
|
||||||
use Filament\Schemas\Components\Section;
|
use Filament\Schemas\Components\Section;
|
||||||
use Filament\Schemas\Components\Tabs;
|
use Filament\Schemas\Components\Tabs;
|
||||||
use Filament\Schemas\Components\Tabs\Tab;
|
use Filament\Schemas\Components\Tabs\Tab;
|
||||||
@@ -120,45 +122,92 @@ public static function slotBuilder(string $name = 'widget'): Builder
|
|||||||
->columnSpanFull();
|
->columnSpanFull();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erklärung als kleines (i) neben der Bezeichnung: erscheint beim Überfahren und beim Fokussieren.
|
||||||
|
*/
|
||||||
|
private static function withInfo(ToggleButtons|Select $component, ?string $help): ToggleButtons|Select
|
||||||
|
{
|
||||||
|
return filled($help)
|
||||||
|
? $component->hintIcon('heroicon-m-information-circle', tooltip: $help)->hintColor('gray')
|
||||||
|
: $component;
|
||||||
|
}
|
||||||
|
|
||||||
public static function block(WidgetType $type): Block
|
public static function block(WidgetType $type): Block
|
||||||
{
|
{
|
||||||
$icons = $type->optionIcons();
|
$icons = $type->optionIcons();
|
||||||
$display = [];
|
$display = [];
|
||||||
|
|
||||||
|
// Aufbau: Anordnung (Variante) und gemeinsame Höhe. Erklärungen stehen im (i) neben der Bezeichnung.
|
||||||
|
$layout = [];
|
||||||
if (count($type->variants()) > 1) {
|
if (count($type->variants()) > 1) {
|
||||||
$display[] = ToggleButtons::make('variant')
|
$layout[] = self::withInfo(ToggleButtons::make('variant')
|
||||||
->label('Darstellung')
|
->label('Anordnung')
|
||||||
->options($type->variants())
|
->options($type->variants())
|
||||||
->icons($icons['variant'] ?? [])
|
->icons($icons['variant'] ?? [])
|
||||||
->default($type->defaultVariant())
|
->default($type->defaultVariant())
|
||||||
->inline()
|
->inline()
|
||||||
->required()
|
->required()
|
||||||
->live();
|
->live(), 'Wie Bild und Text zueinander stehen. Bei wenig Platz stellt sich jede Anordnung selbständig um; die gespeicherte Seite bleibt erhalten.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$settings = [];
|
$options = $type->settingOptions();
|
||||||
$labels = $type->settingLabels();
|
$labels = $type->settingLabels();
|
||||||
foreach ($type->settingOptions() as $key => $options) {
|
$hiddenWhen = $type->settingHiddenWhen();
|
||||||
|
|
||||||
|
$field = function (string $key) use ($options, $labels, $type, $icons, $hiddenWhen): Select|ToggleButtons {
|
||||||
|
$help = $labels[$key][1] ?? null;
|
||||||
// Gemeinsame Höhe (ADR-38): immer als sichtbare Auswahl mit Vorgabe, nie als freie Eingabe.
|
// Gemeinsame Höhe (ADR-38): immer als sichtbare Auswahl mit Vorgabe, nie als freie Eingabe.
|
||||||
$settings[] = $key === 'height'
|
$component = $key === 'height'
|
||||||
? ToggleButtons::make('height')
|
? ToggleButtons::make('height')
|
||||||
->label('Höhe')
|
->label('Höhe')
|
||||||
->helperText('Gestaltungsparameter, keine Begrenzung: Längere Inhalte erhalten immer den nötigen Platz.')
|
->options($options['height'])
|
||||||
->options($options)
|
|
||||||
->icons($icons['height'] ?? [])
|
->icons($icons['height'] ?? [])
|
||||||
->default($type->defaultHeight())
|
->default($type->defaultHeight())
|
||||||
->inline()
|
->inline()
|
||||||
->live()
|
->live()
|
||||||
: Select::make($key)
|
: Select::make($key)
|
||||||
->label($labels[$key][0] ?? Str::headline($key))
|
->label($labels[$key][0] ?? Str::headline($key))
|
||||||
->helperText($labels[$key][1] ?? null)
|
|
||||||
->placeholder('Vorgabe der Darstellung')
|
->placeholder('Vorgabe der Darstellung')
|
||||||
->options($options)
|
->options($options[$key])
|
||||||
->live();
|
->live();
|
||||||
|
|
||||||
|
if ($key === 'height') {
|
||||||
|
$help = 'Gestaltungsparameter, keine Begrenzung: Längere Inhalte erhalten immer den nötigen Platz.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($hiddenWhen[$key])) {
|
||||||
|
[$controller, $value] = $hiddenWhen[$key];
|
||||||
|
// Ausgeblendete Werte bleiben gespeichert, damit ein späteres Einblenden nichts zurücksetzt.
|
||||||
|
$component->hidden(fn (Get $get): bool => ($get($controller) ?? null) === $value)->dehydratedWhenHidden();
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::withInfo($component, $help);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isset($options['height'])) {
|
||||||
|
$layout[] = Group::make([$field('height')])->statePath('settings');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($settings !== []) {
|
if ($layout !== []) {
|
||||||
$display[] = Grid::make(['default' => 1, 'md' => 2])->schema($settings)->statePath('settings');
|
$display[] = Section::make('Aufbau')->compact()->schema($layout);
|
||||||
|
}
|
||||||
|
|
||||||
|
$grouped = [];
|
||||||
|
foreach ($type->settingGroups() as $title => $keys) {
|
||||||
|
$keys = array_values(array_filter($keys, fn (string $key): bool => isset($options[$key]) && $key !== 'height'));
|
||||||
|
$grouped = [...$grouped, ...$keys];
|
||||||
|
if ($keys !== []) {
|
||||||
|
$display[] = Section::make($title)->compact()->schema([
|
||||||
|
Grid::make(['default' => 1, 'md' => 2])->schema(array_map($field, $keys))->statePath('settings'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$rest = array_values(array_filter(array_keys($options), fn (string $key): bool => $key !== 'height' && ! in_array($key, $grouped, true)));
|
||||||
|
if ($rest !== []) {
|
||||||
|
$display[] = Section::make($grouped === [] && $layout === [] ? 'Einstellungen' : 'Weitere Einstellungen')->compact()->schema([
|
||||||
|
Grid::make(['default' => 1, 'md' => 2])->schema(array_map($field, $rest))->statePath('settings'),
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$variantField = count($type->variants()) > 1 ? [] : [Hidden::make('variant')->default($type->defaultVariant())];
|
$variantField = count($type->variants()) > 1 ? [] : [Hidden::make('variant')->default($type->defaultVariant())];
|
||||||
@@ -426,7 +475,7 @@ public static function renderPreview(string $type, array $state): string
|
|||||||
public static function previewStylesheets(): string
|
public static function previewStylesheets(): string
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
return app(Vite::class)(['resources/css/app.css'])->toHtml();
|
return app(Vite::class)(['resources/css/app.css'])->toHtml().DesignSettings::styleTag()->toHtml();
|
||||||
} catch (Throwable) {
|
} catch (Throwable) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
use App\Domain\Commerce\Cart;
|
use App\Domain\Commerce\Cart;
|
||||||
use App\Domain\Commerce\Money;
|
use App\Domain\Commerce\Money;
|
||||||
use App\Domain\Commerce\OrderHolders;
|
use App\Domain\Commerce\OrderHolders;
|
||||||
|
use App\Domain\Commerce\ProductOptions;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\View\View;
|
use Illuminate\View\View;
|
||||||
@@ -31,9 +32,8 @@ public function show(Request $request, Cart $cart, OrderHolders $holders): View
|
|||||||
public function add(Offer $offer, Cart $cart, PublicCatalogReader $catalog): RedirectResponse
|
public function add(Offer $offer, Cart $cart, PublicCatalogReader $catalog): RedirectResponse
|
||||||
{
|
{
|
||||||
$page = $offer->composition;
|
$page = $offer->composition;
|
||||||
$result = $page !== null && $catalog->shownVersion($page) !== null
|
$listed = $offer->standalone_bundle || ($page !== null && $catalog->shownVersion($page) !== null);
|
||||||
? $cart->add($offer)
|
$result = $listed ? $cart->add($offer) : Cart::UNAVAILABLE;
|
||||||
: Cart::UNAVAILABLE;
|
|
||||||
$back = $this->productPage($offer);
|
$back = $this->productPage($offer);
|
||||||
|
|
||||||
return match ($result) {
|
return match ($result) {
|
||||||
@@ -81,8 +81,8 @@ public function accept(Offer $offer, Cart $cart): RedirectResponse
|
|||||||
|
|
||||||
private function productPage(Offer $offer): RedirectResponse
|
private function productPage(Offer $offer): RedirectResponse
|
||||||
{
|
{
|
||||||
return $offer->composition_id !== null
|
$url = app(ProductOptions::class)->pageUrl($offer);
|
||||||
? redirect()->route('public.program', $offer->composition_id)
|
|
||||||
: redirect()->route('cart');
|
return $url !== null ? redirect()->to($url) : redirect()->route('cart');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,12 +7,15 @@
|
|||||||
use App\Domain\Catalog\OfferStatus;
|
use App\Domain\Catalog\OfferStatus;
|
||||||
use App\Domain\Commerce\Cart;
|
use App\Domain\Commerce\Cart;
|
||||||
use App\Domain\Commerce\Checkout;
|
use App\Domain\Commerce\Checkout;
|
||||||
|
use App\Domain\Commerce\LedgerEntry;
|
||||||
use App\Domain\Commerce\Order;
|
use App\Domain\Commerce\Order;
|
||||||
use App\Domain\Commerce\OrderHolders;
|
use App\Domain\Commerce\OrderHolders;
|
||||||
|
use App\Domain\Commerce\SalesTerms;
|
||||||
use App\Domain\Commerce\Shop;
|
use App\Domain\Commerce\Shop;
|
||||||
use App\Domain\Commerce\StaleOverview;
|
use App\Domain\Commerce\StaleOverview;
|
||||||
use App\Domain\Commerce\Stripe\StripeGateway;
|
use App\Domain\Commerce\Stripe\StripeGateway;
|
||||||
use App\Domain\Entitlement\GrantIssuer;
|
use App\Domain\Entitlement\GrantIssuer;
|
||||||
|
use App\Domain\Identity\PartyType;
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -39,7 +42,7 @@ public function claim(Request $request, Offer $offer, GrantIssuer $issuer): Redi
|
|||||||
return back()->withErrors(['offer' => $exception->getMessage()]);
|
return back()->withErrors(['offer' => $exception->getMessage()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return redirect()->route('member.library')->with('status', 'Das Angebot liegt in Ihrer Bibliothek.');
|
return redirect()->route('member.library')->with('status', 'Das Angebot liegt in deiner Bibliothek.');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function place(Request $request, Offer $offer, Checkout $checkout): RedirectResponse
|
public function place(Request $request, Offer $offer, Checkout $checkout): RedirectResponse
|
||||||
@@ -67,9 +70,38 @@ public function checkout(Request $request, Cart $cart, OrderHolders $holders): V
|
|||||||
return view('shop.checkout', [
|
return view('shop.checkout', [
|
||||||
'review' => $review,
|
'review' => $review,
|
||||||
'holders' => $holders->for($request->user()),
|
'holders' => $holders->for($request->user()),
|
||||||
|
'consents' => SalesTerms::consents(),
|
||||||
|
'legalPages' => SalesTerms::pages(),
|
||||||
|
'invoice' => Shop::invoice() && $review->holder?->type === PartyType::Organisation,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rabattcode einlösen. Höchstens ein Code je Bestellung; ein zweiter ersetzt den ersten. Gilt der Code nicht,
|
||||||
|
* bleibt der bisherige Stand und die Meldung nennt den Grund.
|
||||||
|
*/
|
||||||
|
public function applyCode(Request $request, Cart $cart): RedirectResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate(['code' => ['required', 'string', 'max:60'], 'bestellen_als' => ['nullable', 'integer']], [
|
||||||
|
'code.required' => 'Gib einen Rabattcode ein.',
|
||||||
|
]);
|
||||||
|
$holderId = isset($data['bestellen_als']) ? (int) $data['bestellen_als'] : null;
|
||||||
|
$result = $cart->applyCode($data['code'], $request->user(), $holderId);
|
||||||
|
$back = redirect()->route('checkout', array_filter(['bestellen_als' => $holderId]));
|
||||||
|
|
||||||
|
return $result->applied()
|
||||||
|
? $back->with('status', 'Der Rabattcode '.$result->code->code.' ist angewendet.')
|
||||||
|
: $back->withErrors(['code' => $result->message ?? 'Der Code kann nicht angewendet werden.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function removeCode(Request $request, Cart $cart): RedirectResponse
|
||||||
|
{
|
||||||
|
$cart->removeCode();
|
||||||
|
$holderId = $request->integer('bestellen_als') ?: null;
|
||||||
|
|
||||||
|
return redirect()->route('checkout', array_filter(['bestellen_als' => $holderId]))->with('status', 'Der Rabattcode ist entfernt.');
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Legt die Bestellung an, aber nur, wenn die serverseitige Prüfung zur gezeigten Übersicht passt.
|
* Legt die Bestellung an, aber nur, wenn die serverseitige Prüfung zur gezeigten Übersicht passt.
|
||||||
*/
|
*/
|
||||||
@@ -78,19 +110,28 @@ public function placeOrder(Request $request, Cart $cart, Checkout $checkout): Re
|
|||||||
$data = $request->validate([
|
$data = $request->validate([
|
||||||
'digest' => ['required', 'string'],
|
'digest' => ['required', 'string'],
|
||||||
'bestellen_als' => ['nullable', 'integer'],
|
'bestellen_als' => ['nullable', 'integer'],
|
||||||
|
'zahlungsweg' => ['nullable', 'in:online,rechnung'],
|
||||||
|
'zustimmung' => ['nullable', 'array'],
|
||||||
]);
|
]);
|
||||||
$holderId = isset($data['bestellen_als']) ? (int) $data['bestellen_als'] : null;
|
$holderId = isset($data['bestellen_als']) ? (int) $data['bestellen_als'] : null;
|
||||||
$back = redirect()->route('checkout', array_filter(['bestellen_als' => $holderId]));
|
$back = redirect()->route('checkout', array_filter(['bestellen_als' => $holderId]));
|
||||||
|
$method = ($data['zahlungsweg'] ?? 'online') === 'rechnung' ? 'rechnung' : null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$order = $checkout->placeFromCart($request->user(), $cart, $holderId, $data['digest']);
|
// Die Zustimmungen sind eine Pflichtangabe und werden serverseitig geprüft, nicht nur im Formular.
|
||||||
|
SalesTerms::proof((array) ($data['zustimmung'] ?? []));
|
||||||
|
$order = $checkout->placeFromCart($request->user(), $cart, $holderId, $data['digest'], (array) ($data['zustimmung'] ?? []), $method);
|
||||||
} catch (StaleOverview $exception) {
|
} catch (StaleOverview $exception) {
|
||||||
return $back->withErrors(['checkout' => $exception->getMessage()]);
|
return $back->withErrors(['checkout' => $exception->getMessage()]);
|
||||||
} catch (DomainRuleException $exception) {
|
} catch (DomainRuleException $exception) {
|
||||||
return $back->withErrors(['checkout' => $exception->getMessage()]);
|
return $back->withErrors(['checkout' => $exception->getMessage()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return redirect()->route('member.order', $order)->with('status', 'Die Bestellung ist angelegt. Bestätige jetzt die Testzahlung.');
|
return redirect()->route('member.order', $order)->with('status', match (true) {
|
||||||
|
$order->payment_method === 'rechnung' => 'Deine Bestellung auf Rechnung ist eingegangen. Wir senden dir die Rechnung. Die Inhalte sind nach Zahlungseingang in der Bibliothek.',
|
||||||
|
Shop::stripe() => 'Die Bestellung ist angelegt. Bezahle jetzt sicher bei Stripe.',
|
||||||
|
default => 'Die Bestellung ist angelegt. Bestätige jetzt die Testzahlung.',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $request, Order $order): View
|
public function show(Request $request, Order $order): View
|
||||||
@@ -103,9 +144,26 @@ public function show(Request $request, Order $order): View
|
|||||||
'testPayment' => ! app()->isProduction() && config('services.payment.driver') === 'test',
|
'testPayment' => ! app()->isProduction() && config('services.payment.driver') === 'test',
|
||||||
'stripePayment' => Shop::stripe(),
|
'stripePayment' => Shop::stripe(),
|
||||||
'zahlung' => $request->query('zahlung'),
|
'zahlung' => $request->query('zahlung'),
|
||||||
|
'live' => Shop::live(),
|
||||||
|
'receipts' => LedgerEntry::query()->where('order_id', $order->id)->where('derived', false)->orderBy('occurred_at')->orderBy('id')->get(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Erklärt den Widerruf; der Betreiber prüft und erstattet gegebenenfalls in der Bestellverwaltung. */
|
||||||
|
public function withdraw(Request $request, Order $order, Checkout $checkout): RedirectResponse
|
||||||
|
{
|
||||||
|
abort_unless($order->user_id === $request->user()->id, 403);
|
||||||
|
$data = $request->validate(['note' => ['nullable', 'string', 'max:1000']]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$checkout->requestWithdrawal($order, (string) ($data['note'] ?? ''));
|
||||||
|
} catch (DomainRuleException $exception) {
|
||||||
|
return back()->withErrors(['payment' => $exception->getMessage()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()->route('member.order', $order)->with('status', 'Dein Widerruf ist eingegangen. Wir prüfen ihn und melden uns per E-Mail.');
|
||||||
|
}
|
||||||
|
|
||||||
/** Leitet zur Stripe-Kasse (Testmodus). Freigeschaltet wird erst durch die signierte Meldung von Stripe. */
|
/** Leitet zur Stripe-Kasse (Testmodus). Freigeschaltet wird erst durch die signierte Meldung von Stripe. */
|
||||||
public function pay(Request $request, Order $order, StripeGateway $stripe): RedirectResponse
|
public function pay(Request $request, Order $order, StripeGateway $stripe): RedirectResponse
|
||||||
{
|
{
|
||||||
@@ -150,6 +208,8 @@ public function fail(Request $request, Order $order, Checkout $checkout): Redire
|
|||||||
public function refund(Request $request, Order $order, Checkout $checkout): RedirectResponse
|
public function refund(Request $request, Order $order, Checkout $checkout): RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless($order->user_id === $request->user()->id, 403);
|
abort_unless($order->user_id === $request->user()->id, 403);
|
||||||
|
// Nur der Testzahlungsweg erstattet auf Knopfdruck. Echte Zahlungen erstattet der Betreiber nach Prüfung.
|
||||||
|
abort_unless(! app()->isProduction() && Shop::driver() === 'test', 404);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$checkout->refund($order, 'Widerruf durch das Mitglied im Testmodus');
|
$checkout->refund($order, 'Widerruf durch das Mitglied im Testmodus');
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Member;
|
||||||
|
|
||||||
|
use App\Domain\Catalog\ArticleRelease;
|
||||||
|
use App\Domain\Catalog\CompositionVersion;
|
||||||
|
use App\Domain\Catalog\ExerciseGuide;
|
||||||
|
use App\Domain\Catalog\ExercisePdf;
|
||||||
|
use App\Domain\Catalog\LicenseArticle;
|
||||||
|
use App\Domain\Media\DeliveryLog;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Http\SignedLink;
|
||||||
|
use Illuminate\Contracts\View\View;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Response;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Die Übung als formatierte Anleitung innerhalb des erworbenen Moduls oder Programms und ihre PDF-Ausgabe. Beide zeigen
|
||||||
|
* die im Artikel-Stand gebundene Übungsfassung und die dort angebotenen Varianten. Über jeden Abschnitt und jedes
|
||||||
|
* Medium entscheidet `DecideAccess`; auch die direkte PDF-Adresse wird bei jedem Abruf neu entschieden.
|
||||||
|
*/
|
||||||
|
class ExerciseController extends Controller
|
||||||
|
{
|
||||||
|
public function show(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): View
|
||||||
|
{
|
||||||
|
[$guide, $located] = $this->load($request, $article, $release, $path);
|
||||||
|
$user = $request->user();
|
||||||
|
$copy = DeliveryLog::newCopyId();
|
||||||
|
$shown = false;
|
||||||
|
|
||||||
|
foreach ($guide['entries'] as $index => $entry) {
|
||||||
|
$link = fn (string $action) => SignedLink::temporary('member.media', now()->addMinutes(10), [
|
||||||
|
'article' => $article->id,
|
||||||
|
'release' => $release->id,
|
||||||
|
'version' => $entry['version']->id,
|
||||||
|
'action' => $action,
|
||||||
|
'reader' => $user->id,
|
||||||
|
]);
|
||||||
|
$guide['entries'][$index]['url'] = $entry['allowed'] && $entry['class'] !== 'text' ? $link($entry['action']) : null;
|
||||||
|
$guide['entries'][$index]['download_url'] = $entry['allowed'] && $entry['may_download'] && $entry['class'] !== 'text' ? $link('laden') : null;
|
||||||
|
|
||||||
|
if ($entry['allowed'] && $entry['class'] === 'text' && $entry['grant'] !== null) {
|
||||||
|
app(DeliveryLog::class)->write($entry['grant'], $article, $release, $entry['version'], 'ansehen', 'text', hash('sha256', (string) $entry['version']->body), 'k2', $copy, $located['version']->id);
|
||||||
|
$shown = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$pdfAllowed = app(ExercisePdf::class)->sections($guide) !== null;
|
||||||
|
|
||||||
|
return view('member.exercise', [
|
||||||
|
'guide' => $guide,
|
||||||
|
'article' => $article,
|
||||||
|
'release' => $release,
|
||||||
|
'path' => $path,
|
||||||
|
'reader' => $user->name,
|
||||||
|
'copy' => $shown ? $copy : null,
|
||||||
|
'pdfUrl' => $pdfAllowed ? SignedLink::temporary('member.exercise.pdf', now()->addMinutes(10), [
|
||||||
|
'article' => $article->id,
|
||||||
|
'release' => $release->id,
|
||||||
|
'path' => $path,
|
||||||
|
'variante' => $guide['chosen'],
|
||||||
|
'reader' => $user->id,
|
||||||
|
]) : null,
|
||||||
|
'variantUrl' => fn (string $key): string => route('member.exercise', ['article' => $article, 'release' => $release, 'path' => $path, 'variante' => $key]),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function pdf(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): Response
|
||||||
|
{
|
||||||
|
abort_unless((int) $request->query('reader') === $request->user()->id, 403);
|
||||||
|
|
||||||
|
[$guide, $located] = $this->load($request, $article, $release, $path);
|
||||||
|
$pdf = app(ExercisePdf::class);
|
||||||
|
$sections = $pdf->sections($guide);
|
||||||
|
abort_if($sections === null, 403, 'Für dieses PDF fehlt die Berechtigung oder ein erforderlicher Bestandteil.');
|
||||||
|
|
||||||
|
$copy = DeliveryLog::newCopyId();
|
||||||
|
$variant = collect($guide['variants'])->firstWhere('key', $guide['chosen']);
|
||||||
|
$content = $pdf->render(
|
||||||
|
$guide,
|
||||||
|
$sections,
|
||||||
|
$request->user()->name,
|
||||||
|
$copy,
|
||||||
|
(string) ($variant['name'] ?? ''),
|
||||||
|
route('member.exercise', ['article' => $article, 'release' => $release, 'path' => $path, 'variante' => $guide['chosen']]),
|
||||||
|
);
|
||||||
|
$checksum = hash('sha256', $content);
|
||||||
|
|
||||||
|
foreach ($sections as $section) {
|
||||||
|
$grant = $section['download_grant'] ?? $section['grant'];
|
||||||
|
|
||||||
|
if ($grant !== null) {
|
||||||
|
app(DeliveryLog::class)->write($grant, $article, $release, $section['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$name = str($guide['title'])->slug()->value() ?: 'uebung';
|
||||||
|
|
||||||
|
return response($content, 200, [
|
||||||
|
'Content-Type' => 'application/pdf',
|
||||||
|
'Content-Disposition' => 'attachment; filename="'.$name.'.pdf"',
|
||||||
|
'X-License-Copy' => $copy,
|
||||||
|
'Cache-Control' => 'private, no-store',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{0: array<string, mixed>, 1: array{version: CompositionVersion, selection: list<string>|null}}
|
||||||
|
*/
|
||||||
|
private function load(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): array
|
||||||
|
{
|
||||||
|
$guides = app(ExerciseGuide::class);
|
||||||
|
abort_unless($guides->mayOpen($request->user(), $article, $release), 403);
|
||||||
|
$located = $guides->locate($release, $path);
|
||||||
|
abort_if($located === null, 404);
|
||||||
|
|
||||||
|
$variant = $request->query('variante');
|
||||||
|
|
||||||
|
return [
|
||||||
|
$guides->build($request->user(), $article, $release, $located['version'], $located['selection'], is_string($variant) ? $variant : null),
|
||||||
|
$located,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
use App\Domain\Catalog\Composition;
|
use App\Domain\Catalog\Composition;
|
||||||
use App\Domain\Catalog\ContentElement;
|
use App\Domain\Catalog\ContentElement;
|
||||||
use App\Domain\Catalog\ContentElementVersion;
|
use App\Domain\Catalog\ContentElementVersion;
|
||||||
|
use App\Domain\Catalog\ContentVersionStatus;
|
||||||
use App\Domain\Catalog\EditorialVocabulary;
|
use App\Domain\Catalog\EditorialVocabulary;
|
||||||
use App\Domain\Catalog\IdentityDimension;
|
use App\Domain\Catalog\IdentityDimension;
|
||||||
use App\Domain\Catalog\LicenseArticle;
|
use App\Domain\Catalog\LicenseArticle;
|
||||||
@@ -21,8 +22,10 @@
|
|||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use App\Http\CourseOutline;
|
use App\Http\CourseOutline;
|
||||||
use App\Http\LibraryCatalog;
|
use App\Http\LibraryCatalog;
|
||||||
|
use App\Http\MemberLicenses;
|
||||||
use App\Http\SignedLink;
|
use App\Http\SignedLink;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Response;
|
use Illuminate\Http\Response;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
@@ -32,12 +35,28 @@
|
|||||||
|
|
||||||
class LibraryController extends Controller
|
class LibraryController extends Controller
|
||||||
{
|
{
|
||||||
|
/** Inhaltsarten der Bibliothek (Schlüssel der Adresse und des Filters). */
|
||||||
|
public const TYPES = [
|
||||||
|
'programm' => 'Programme',
|
||||||
|
'modul' => 'Module',
|
||||||
|
'film' => 'Filme',
|
||||||
|
'material' => 'Materialien',
|
||||||
|
];
|
||||||
|
|
||||||
public function index(Request $request, ?string $sicht = null): View
|
public function index(Request $request, ?string $sicht = null): View
|
||||||
{
|
{
|
||||||
$catalog = app(LibraryCatalog::class)->index($request->user());
|
$catalog = app(LibraryCatalog::class)->index($request->user());
|
||||||
$untouched = $catalog['programs'] === [] && $catalog['modules'] === [] && $catalog['materials'] === [];
|
$items = [...$catalog['programs'], ...$catalog['modules'], ...$catalog['materials']];
|
||||||
|
$untouched = $items === [];
|
||||||
$query = trim((string) $request->query('q', ''));
|
$query = trim((string) $request->query('q', ''));
|
||||||
$nutzung = (string) $request->query('nutzung', '');
|
$nutzung = (string) $request->query('nutzung', '');
|
||||||
|
$sortierung = $request->query('sortierung') === 'titel' ? 'titel' : 'standard';
|
||||||
|
$art = match ($sicht) {
|
||||||
|
'programme' => 'programm',
|
||||||
|
'module' => 'modul',
|
||||||
|
default => (string) $request->query('art', ''),
|
||||||
|
};
|
||||||
|
$art = array_key_exists($art, self::TYPES) ? $art : '';
|
||||||
$dimensionIds = array_values(array_filter(array_map(intval(...), (array) $request->query('dimension', []))));
|
$dimensionIds = array_values(array_filter(array_map(intval(...), (array) $request->query('dimension', []))));
|
||||||
$saeuleIds = array_values(array_filter(array_map(intval(...), (array) $request->query('saeule', []))));
|
$saeuleIds = array_values(array_filter(array_map(intval(...), (array) $request->query('saeule', []))));
|
||||||
$dimensions = app(IdentityDimension::class);
|
$dimensions = app(IdentityDimension::class);
|
||||||
@@ -52,94 +71,60 @@ public function index(Request $request, ?string $sicht = null): View
|
|||||||
|
|
||||||
$dimensionIds = array_values($dimensionIds);
|
$dimensionIds = array_values($dimensionIds);
|
||||||
$saeuleIds = array_values(array_unique($saeuleIds));
|
$saeuleIds = array_values(array_unique($saeuleIds));
|
||||||
$pillarOptions = $this->visiblePillars($catalog, $saeuleIds);
|
$pillarOptions = $this->visiblePillars($items, $saeuleIds);
|
||||||
|
|
||||||
foreach (['programs', 'modules'] as $shelf) {
|
// Gemeinsame Filter für alle Inhaltsarten. Die Zahl je Art zeigt, was die übrigen Filter übrig lassen.
|
||||||
if ($query !== '') {
|
$matching = array_values(array_filter($items, function (array $card) use ($query, $nutzung, $dimensionIds, $saeuleIds, $dimensions): bool {
|
||||||
$catalog[$shelf] = array_values(array_filter(
|
return ($query === '' || $this->matches($card, $query))
|
||||||
$catalog[$shelf],
|
&& ($dimensionIds === [] || $dimensions->matches($card['subject'], $dimensionIds))
|
||||||
fn (array $card): bool => $this->matches($card, $query),
|
&& ($saeuleIds === [] || $this->hasPillar($card['subject'], $saeuleIds))
|
||||||
));
|
&& (! in_array($nutzung, ['nutzbar', 'teilweise', 'nicht enthalten'], true) || ($card['coverage'] ?? '') === $nutzung);
|
||||||
}
|
}));
|
||||||
if ($dimensionIds !== []) {
|
$counts = array_fill_keys(array_keys(self::TYPES), 0);
|
||||||
$catalog[$shelf] = array_values(array_filter(
|
|
||||||
$catalog[$shelf],
|
foreach ($matching as $card) {
|
||||||
fn (array $card): bool => $dimensions->matches($card['composition'], $dimensionIds),
|
$counts[$card['type']]++;
|
||||||
));
|
}
|
||||||
}
|
|
||||||
if ($saeuleIds !== []) {
|
$shown = $art === '' ? $matching : array_values(array_filter($matching, fn (array $card): bool => $card['type'] === $art));
|
||||||
$catalog[$shelf] = array_values(array_filter(
|
|
||||||
$catalog[$shelf],
|
if ($sortierung === 'titel') {
|
||||||
fn (array $card): bool => $this->hasPillar($card['composition'], $saeuleIds),
|
usort($shown, fn (array $left, array $right): int => strcoll(mb_strtolower($left['title']), mb_strtolower($right['title'])));
|
||||||
));
|
}
|
||||||
}
|
|
||||||
if (in_array($nutzung, ['nutzbar', 'teilweise', 'nicht enthalten'], true)) {
|
$shelves = [];
|
||||||
$catalog[$shelf] = array_values(array_filter(
|
|
||||||
$catalog[$shelf],
|
foreach (self::TYPES as $type => $label) {
|
||||||
fn (array $card): bool => ($card['coverage'] ?? '') === $nutzung,
|
$cards = array_values(array_filter($shown, fn (array $card): bool => $card['type'] === $type));
|
||||||
));
|
|
||||||
|
if ($cards !== []) {
|
||||||
|
$shelves[$type] = ['label' => $label, 'cards' => $cards];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($query !== '') {
|
$filterActive = $query !== '' || $nutzung !== '' || $dimensionIds !== [] || $saeuleIds !== [] || $art !== '';
|
||||||
$catalog['materials'] = array_values(array_filter(
|
|
||||||
$catalog['materials'],
|
|
||||||
fn (array $card): bool => $this->matches($card, $query),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($dimensionIds !== []) {
|
|
||||||
$catalog['materials'] = array_values(array_filter(
|
|
||||||
$catalog['materials'],
|
|
||||||
function (array $card) use ($dimensions, $dimensionIds): bool {
|
|
||||||
$release = $card['article']->currentRelease;
|
|
||||||
$subject = $release?->rootCompositionVersion?->composition
|
|
||||||
?? $release?->rootElementVersion?->element
|
|
||||||
?? $card['article'];
|
|
||||||
|
|
||||||
return $dimensions->matches($subject, $dimensionIds);
|
|
||||||
},
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($saeuleIds !== []) {
|
|
||||||
$catalog['materials'] = array_values(array_filter(
|
|
||||||
$catalog['materials'],
|
|
||||||
fn (array $card): bool => $this->hasPillar($this->materialSubject($card), $saeuleIds),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($nutzung === 'teilweise' || $nutzung === 'nicht enthalten') {
|
|
||||||
$catalog['materials'] = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return view('member.library', [
|
return view('member.library', [
|
||||||
...$catalog,
|
'shelves' => $shelves,
|
||||||
|
'total' => count($shown),
|
||||||
|
'counts' => $counts,
|
||||||
|
'allCount' => count($matching),
|
||||||
|
'art' => $art,
|
||||||
|
'types' => self::TYPES,
|
||||||
'query' => $query,
|
'query' => $query,
|
||||||
'sicht' => $sicht,
|
'sicht' => $sicht,
|
||||||
'nutzung' => $nutzung,
|
'nutzung' => $nutzung,
|
||||||
|
'sortierung' => $sortierung,
|
||||||
'dimensionIds' => $dimensionIds,
|
'dimensionIds' => $dimensionIds,
|
||||||
'saeuleIds' => $saeuleIds,
|
'saeuleIds' => $saeuleIds,
|
||||||
'filterPillars' => $pillarOptions,
|
'filterPillars' => $pillarOptions,
|
||||||
'filterDimensions' => app(EditorialVocabulary::class)->memberFilterDimensions(array_map(intval(...), $dimensionIds)),
|
'filterDimensions' => app(EditorialVocabulary::class)->memberFilterDimensions(array_map(intval(...), $dimensionIds)),
|
||||||
'libraryEmpty' => $untouched,
|
'libraryEmpty' => $untouched,
|
||||||
|
'filterActive' => $filterActive,
|
||||||
|
'filterCount' => count($dimensionIds) + count($saeuleIds) + ($nutzung !== '' ? 1 : 0),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Subjekt eines Materialkarte: Programm oder Modul, Medium oder der Artikel selbst.
|
|
||||||
*
|
|
||||||
* @param array<string, mixed> $card
|
|
||||||
*/
|
|
||||||
private function materialSubject(array $card): Model
|
|
||||||
{
|
|
||||||
$release = $card['article']->currentRelease;
|
|
||||||
|
|
||||||
return $release?->rootCompositionVersion?->composition
|
|
||||||
?? $release?->rootElementVersion?->element
|
|
||||||
?? $card['article'];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Direkte Säulenzuordnung des Objekts selbst; die Säulen enthaltener Medien zählen hier nicht.
|
* Direkte Säulenzuordnung des Objekts selbst; die Säulen enthaltener Medien zählen hier nicht.
|
||||||
*
|
*
|
||||||
@@ -154,22 +139,16 @@ private function hasPillar(Model $subject, array $pillarIds): bool
|
|||||||
* Säulen für den Filter: nur solche, die ein sichtbares Objekt der Bibliothek tatsächlich trägt, und eine bereits
|
* Säulen für den Filter: nur solche, die ein sichtbares Objekt der Bibliothek tatsächlich trägt, und eine bereits
|
||||||
* gewählte. So erscheinen neue oder interne Säulen ohne Zuordnung nicht in der Bibliothek.
|
* gewählte. So erscheinen neue oder interne Säulen ohne Zuordnung nicht in der Bibliothek.
|
||||||
*
|
*
|
||||||
* @param array<string, mixed> $catalog
|
* @param list<array<string, mixed>> $items
|
||||||
* @param list<int> $selected
|
* @param list<int> $selected
|
||||||
* @return Collection<int, Pillar>
|
* @return Collection<int, Pillar>
|
||||||
*/
|
*/
|
||||||
private function visiblePillars(array $catalog, array $selected)
|
private function visiblePillars(array $items, array $selected)
|
||||||
{
|
{
|
||||||
$used = [];
|
$used = [];
|
||||||
|
|
||||||
foreach (array_merge($catalog['programs'], $catalog['modules']) as $card) {
|
foreach ($items as $card) {
|
||||||
foreach ($card['composition']->pillars()->pluck('pillars.id') as $id) {
|
foreach ($card['subject']->pillars()->pluck('pillars.id') as $id) {
|
||||||
$used[(int) $id] = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($catalog['materials'] as $card) {
|
|
||||||
foreach ($this->materialSubject($card)->pillars()->pluck('pillars.id') as $id) {
|
|
||||||
$used[(int) $id] = true;
|
$used[(int) $id] = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -193,20 +172,55 @@ public function program(Request $request, Composition $composition): View
|
|||||||
return view('member.program', app(LibraryCatalog::class)->program($request->user(), $composition));
|
return view('member.program', app(LibraryCatalog::class)->program($request->user(), $composition));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function materials(Request $request): View
|
/**
|
||||||
|
* Film oder Material im Zusammenhang seines Programms oder Moduls. Die Seite zeigt nur Stellen, die in der
|
||||||
|
* angezeigten Fassung des Programms stehen; die Wiedergabe- und Downloadadressen kommen aus DecideAccess.
|
||||||
|
*/
|
||||||
|
public function content(Request $request, Composition $composition, int $version): View|Response
|
||||||
{
|
{
|
||||||
return view('member.materials', [
|
$data = app(LibraryCatalog::class)->content($request->user(), $composition, $version);
|
||||||
'grants' => $this->grantQuery($request)->with('article.currentRelease.contents.elementVersion.element')->get(),
|
abort_if($data === null, 404);
|
||||||
]);
|
|
||||||
|
return response()->view('member.content', $data, $data['allowed'] ? 200 : 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Die frühere Seite „Materialien“ ist ein Filter der Bibliothek (eine Navigation statt zwei). */
|
||||||
|
public function materials(): RedirectResponse
|
||||||
|
{
|
||||||
|
return redirect()->route('member.library', ['art' => 'material']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function grants(Request $request): View
|
public function grants(Request $request): View
|
||||||
{
|
{
|
||||||
|
$entries = app(MemberLicenses::class)->overview($request->user());
|
||||||
|
$filter = in_array($request->query('status'), ['aktiv', 'inaktiv'], true) ? (string) $request->query('status') : 'alle';
|
||||||
|
|
||||||
return view('member.grants', [
|
return view('member.grants', [
|
||||||
'grants' => $this->grantQuery($request)->get(),
|
'entries' => match ($filter) {
|
||||||
|
'aktiv' => $entries->where('active', true)->values(),
|
||||||
|
'inaktiv' => $entries->where('active', false)->values(),
|
||||||
|
default => $entries,
|
||||||
|
},
|
||||||
|
'filter' => $filter,
|
||||||
|
'counts' => [
|
||||||
|
'aktiv' => $entries->where('active', true)->count(),
|
||||||
|
'inaktiv' => $entries->where('active', false)->count(),
|
||||||
|
'alle' => $entries->count(),
|
||||||
|
],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Eine einzelne Berechtigung. Nur eigene (oder die der eigenen Organisation mit Bestellrecht); sonst nicht gefunden. */
|
||||||
|
public function grant(Request $request, Grant $grant): View
|
||||||
|
{
|
||||||
|
abort_unless(
|
||||||
|
Grant::query()->usableBy($request->user())->whereKey($grant->id)->exists(),
|
||||||
|
404,
|
||||||
|
);
|
||||||
|
|
||||||
|
return view('member.grant', app(MemberLicenses::class)->detail($request->user(), $grant));
|
||||||
|
}
|
||||||
|
|
||||||
public function show(Request $request, LicenseArticle $article): View
|
public function show(Request $request, LicenseArticle $article): View
|
||||||
{
|
{
|
||||||
$release = $article->currentRelease()->with('contents.elementVersion.element.pillars')->first();
|
$release = $article->currentRelease()->with('contents.elementVersion.element.pillars')->first();
|
||||||
@@ -219,8 +233,11 @@ public function show(Request $request, LicenseArticle $article): View
|
|||||||
$metadata = is_array($version->metadata) ? $version->metadata : [];
|
$metadata = is_array($version->metadata) ? $version->metadata : [];
|
||||||
$action = $class === 'film' || $class === 'audio' ? 'streamen' : 'ansehen';
|
$action = $class === 'film' || $class === 'audio' ? 'streamen' : 'ansehen';
|
||||||
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, $action);
|
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, $action);
|
||||||
|
$download = app(DecideAccess::class)($request->user(), $article, $release, $version, 'laden');
|
||||||
$file = $metadata['file'] ?? null;
|
$file = $metadata['file'] ?? null;
|
||||||
$entries[] = [
|
$entries[] = [
|
||||||
|
'title' => app(LibraryCatalog::class)->text($version->element)['title'],
|
||||||
|
'class' => $class,
|
||||||
'content' => $content,
|
'content' => $content,
|
||||||
'version' => $version,
|
'version' => $version,
|
||||||
'role' => $content->role,
|
'role' => $content->role,
|
||||||
@@ -232,6 +249,15 @@ public function show(Request $request, LicenseArticle $article): View
|
|||||||
: null,
|
: null,
|
||||||
'playable' => $decision->allowed && is_string($file) && $file !== '' && ($class === 'film' || $class === 'audio'),
|
'playable' => $decision->allowed && is_string($file) && $file !== '' && ($class === 'film' || $class === 'audio'),
|
||||||
'playback' => app(FilmPlayback::class)->mode($version->id),
|
'playback' => app(FilmPlayback::class)->mode($version->id),
|
||||||
|
'download_url' => $download->allowed
|
||||||
|
? SignedLink::temporary('member.media', now()->addMinutes(10), [
|
||||||
|
'article' => $article->id,
|
||||||
|
'release' => $release->id,
|
||||||
|
'version' => $version->id,
|
||||||
|
'action' => 'laden',
|
||||||
|
'reader' => $request->user()->id,
|
||||||
|
])
|
||||||
|
: null,
|
||||||
'pillars' => $version->element->pillars->pluck('name')->all(),
|
'pillars' => $version->element->pillars->pluck('name')->all(),
|
||||||
'url' => $decision->allowed
|
'url' => $decision->allowed
|
||||||
? SignedLink::temporary('member.media', now()->addMinutes(10), [
|
? SignedLink::temporary('member.media', now()->addMinutes(10), [
|
||||||
@@ -352,7 +378,7 @@ public function thumbnail(Request $request, string $kind, int $subject): Streame
|
|||||||
*/
|
*/
|
||||||
private function matches(array $card, string $query): bool
|
private function matches(array $card, string $query): bool
|
||||||
{
|
{
|
||||||
$haystack = mb_strtolower(($card['title'] ?? '').' '.($card['summary'] ?? ''));
|
$haystack = mb_strtolower(($card['title'] ?? '').' '.($card['summary'] ?? '').' '.($card['subject']->search_terms ?? ''));
|
||||||
|
|
||||||
return str_contains($haystack, mb_strtolower($query));
|
return str_contains($haystack, mb_strtolower($query));
|
||||||
}
|
}
|
||||||
@@ -424,10 +450,34 @@ private function fileResponse(
|
|||||||
'k0',
|
'k0',
|
||||||
);
|
);
|
||||||
|
|
||||||
return $disk->response($file, basename($file), [
|
// Dateiname aus dem Anzeigetitel statt aus der Adresse („laden.mp4“); Laravel setzt Content-Disposition mit
|
||||||
'Content-Disposition' => $action === 'laden' ? 'attachment' : 'inline',
|
// ASCII-Rückfall und UTF-8-Name.
|
||||||
'X-License-Copy' => $delivery->copy_id,
|
return $disk->response(
|
||||||
]);
|
$file,
|
||||||
|
$this->downloadName($version, $file),
|
||||||
|
['X-License-Copy' => $delivery->copy_id],
|
||||||
|
$action === 'laden' ? 'attachment' : 'inline',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dateiname für Ansicht und Download: Anzeigetitel des Mediums (Mitgliedertext, sonst Arbeitstitel) mit der
|
||||||
|
* Endung der gespeicherten Datei. Zeichen, die in Dateinamen nicht erlaubt sind, entfallen.
|
||||||
|
*/
|
||||||
|
private function downloadName(ContentElementVersion $version, string $file): string
|
||||||
|
{
|
||||||
|
$element = $version->element;
|
||||||
|
$title = $element === null ? '' : app(LibraryCatalog::class)->text($element)['title'];
|
||||||
|
$title = (string) preg_replace('/[\x00-\x1F\x7F\/\\\\:*?"<>|]+/u', ' ', $title);
|
||||||
|
$title = trim((string) preg_replace('/\s+/u', ' ', $title));
|
||||||
|
$title = rtrim(mb_substr($title, 0, 120), '. ');
|
||||||
|
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
|
||||||
|
|
||||||
|
if ($title === '') {
|
||||||
|
return basename($file);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $extension === '' ? $title : $title.'.'.$extension;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function renditionBelongsTo(int $versionId, string $path): bool
|
private function renditionBelongsTo(int $versionId, string $path): bool
|
||||||
@@ -452,8 +502,10 @@ private function maySeeThumbnail(Request $request, string $kind, int $subject):
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ein gesperrtes Medium zeigt auch kein Vorschaubild mehr (Sperre gilt für Ausgaben und Ableitungen).
|
||||||
if ($kind === 'element' && $release->contents->contains(
|
if ($kind === 'element' && $release->contents->contains(
|
||||||
fn ($content): bool => $content->elementVersion?->content_element_id === $subject,
|
fn ($content): bool => $content->elementVersion?->content_element_id === $subject
|
||||||
|
&& $content->elementVersion->status !== ContentVersionStatus::Gesperrt,
|
||||||
)) {
|
)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,9 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers\Member;
|
namespace App\Http\Controllers\Member;
|
||||||
|
|
||||||
use App\Domain\Identity\AccountStatus;
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use App\Http\LibraryCatalog;
|
use App\Http\LibraryCatalog;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use App\Http\MemberLicenses;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\View\View;
|
use Illuminate\View\View;
|
||||||
|
|
||||||
@@ -14,35 +13,17 @@ class MemberController extends Controller
|
|||||||
public function dashboard(Request $request): View
|
public function dashboard(Request $request): View
|
||||||
{
|
{
|
||||||
$catalog = app(LibraryCatalog::class)->index($request->user());
|
$catalog = app(LibraryCatalog::class)->index($request->user());
|
||||||
|
$films = array_filter($catalog['materials'], fn (array $card): bool => $card['type'] === 'film');
|
||||||
|
|
||||||
return view('member.dashboard', [
|
return view('member.dashboard', [
|
||||||
'programCount' => count($catalog['programs']),
|
'programs' => array_slice($catalog['programs'], 0, 4),
|
||||||
'moduleCount' => count($catalog['modules']),
|
'counts' => [
|
||||||
'materialCount' => count($catalog['materials']),
|
'programm' => count($catalog['programs']),
|
||||||
|
'modul' => count($catalog['modules']),
|
||||||
|
'film' => count($films),
|
||||||
|
'material' => count($catalog['materials']) - count($films),
|
||||||
|
],
|
||||||
|
'licenseCount' => app(MemberLicenses::class)->overview($request->user())->where('active', true)->count(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function profile(): View
|
|
||||||
{
|
|
||||||
return view('member.profile');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function updateProfile(Request $request): RedirectResponse
|
|
||||||
{
|
|
||||||
$user = $request->user();
|
|
||||||
|
|
||||||
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
|
||||||
|
|
||||||
$data = $request->validate([
|
|
||||||
'name' => ['required', 'string', 'max:120'],
|
|
||||||
]);
|
|
||||||
|
|
||||||
$user->name = $data['name'];
|
|
||||||
$user->save();
|
|
||||||
|
|
||||||
$user->party?->update(['display_name' => $data['name']]);
|
|
||||||
$user->party?->profile?->update(['display_name' => $data['name']]);
|
|
||||||
|
|
||||||
return redirect()->route('member.profile')->with('status', 'Der Name ist gespeichert. Er ist nicht öffentlich.');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Member;
|
||||||
|
|
||||||
|
use App\Domain\Commerce\LedgerEntry;
|
||||||
|
use App\Domain\Commerce\PaymentJournal;
|
||||||
|
use App\Domain\Commerce\Receipt\PaymentReceipt;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Contracts\View\View;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Response;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zahlungshistorie des Mitglieds mit Einzelbeleg. Sie zeigt nur Buchungen zu Bestellungen, die das angemeldete Konto
|
||||||
|
* selbst aufgegeben hat (bei Vereinskäufen also nur das bestellende Konto, wie beim Download). Der Beleg wird aus den
|
||||||
|
* festgehaltenen Angaben der Buchung gebaut (PaymentReceipt).
|
||||||
|
*/
|
||||||
|
class PaymentController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request): View
|
||||||
|
{
|
||||||
|
$entries = LedgerEntry::query()
|
||||||
|
->whereHas('order', fn ($orders) => $orders->where('user_id', $request->user()->id))
|
||||||
|
->orderByDesc('occurred_at')
|
||||||
|
->orderByDesc('id')
|
||||||
|
->get();
|
||||||
|
|
||||||
|
return view('member.payments', [
|
||||||
|
'rows' => $entries->map(fn (LedgerEntry $entry): array => [
|
||||||
|
'id' => $entry->id,
|
||||||
|
'order' => $entry->order_id,
|
||||||
|
'refund' => $entry->isRefund(),
|
||||||
|
'date' => PaymentJournal::local($entry->occurred_at)->format('d.m.Y'),
|
||||||
|
'products' => collect((array) (($entry->order_snapshot ?? [])['lines'] ?? []))->pluck('name')->filter()->values()->all(),
|
||||||
|
'amount' => $entry->amount_cents,
|
||||||
|
'provider' => PaymentJournal::providerLabel($entry->provider),
|
||||||
|
'test' => ! $entry->live,
|
||||||
|
'receipt' => PaymentReceipt::available($entry),
|
||||||
|
])->all(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function receipt(Request $request, LedgerEntry $entry): Response
|
||||||
|
{
|
||||||
|
$entry->loadMissing('order');
|
||||||
|
abort_unless($entry->order?->user_id === $request->user()->id, 403);
|
||||||
|
abort_unless(PaymentReceipt::available($entry), 404);
|
||||||
|
|
||||||
|
return response(PaymentReceipt::render($entry), 200, [
|
||||||
|
'Content-Type' => 'application/pdf',
|
||||||
|
'Content-Disposition' => 'attachment; filename="'.PaymentReceipt::filename($entry).'"',
|
||||||
|
'Cache-Control' => 'private, no-store',
|
||||||
|
'X-Content-Type-Options' => 'nosniff',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Member;
|
||||||
|
|
||||||
|
use App\Domain\Identity\AccountStatus;
|
||||||
|
use App\Domain\Identity\BillingAddress;
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Notifications\ConfirmNewEmailAddress;
|
||||||
|
use App\Notifications\EmailChangeRequested;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Illuminate\Support\Facades\Notification;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Illuminate\Validation\Rules\Password;
|
||||||
|
use Illuminate\View\View;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mitgliederprofil: Name, E-Mail-Adresse, Passwort und Rechnungsadresse. Jeder Block hat seine eigene Speicherhandlung
|
||||||
|
* und seine eigenen Fehlermeldungen; nichts wird verdeckt mitgespeichert. Sicherheitsrelevante Änderungen (Adresse,
|
||||||
|
* Passwort) verlangen das aktuelle Passwort.
|
||||||
|
*/
|
||||||
|
class ProfileController extends Controller
|
||||||
|
{
|
||||||
|
public function show(Request $request): View
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
|
||||||
|
return view('member.profile', [
|
||||||
|
'address' => $user->party?->billingAddress,
|
||||||
|
'countries' => BillingAddress::COUNTRIES,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updateName(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||||
|
|
||||||
|
$data = $request->validateWithBag('name', [
|
||||||
|
'name' => ['required', 'string', 'max:120'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user->name = $data['name'];
|
||||||
|
$user->save();
|
||||||
|
|
||||||
|
$user->party?->update(['display_name' => $data['name']]);
|
||||||
|
$user->party?->profile?->update(['display_name' => $data['name']]);
|
||||||
|
|
||||||
|
return redirect()->route('member.profile')->with('status', 'Der Name ist gespeichert. Er ist nicht öffentlich.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Die neue Adresse gilt erst nach Bestätigung über einen Link an sie. Bis dahin bleibt die bisherige Adresse
|
||||||
|
* in Kraft und erhält einen Hinweis.
|
||||||
|
*/
|
||||||
|
public function requestEmail(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||||
|
|
||||||
|
$data = $request->validateWithBag('email', [
|
||||||
|
'email' => ['required', 'string', 'email:rfc', 'max:255', Rule::unique('users', 'email')],
|
||||||
|
'current_password' => ['required', 'current_password'],
|
||||||
|
], [
|
||||||
|
'email.unique' => 'Diese Adresse ist bereits vergeben.',
|
||||||
|
'current_password.current_password' => 'Das Passwort stimmt nicht.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$new = mb_strtolower(trim($data['email']));
|
||||||
|
|
||||||
|
if ($new === mb_strtolower($user->email)) {
|
||||||
|
return back()->withErrors(['email' => 'Das ist bereits deine Adresse.'], 'email');
|
||||||
|
}
|
||||||
|
|
||||||
|
$user->forceFill(['pending_email' => $new])->save();
|
||||||
|
Notification::route('mail', $new)->notify(new ConfirmNewEmailAddress($user->id, $new));
|
||||||
|
$user->notify(new EmailChangeRequested($new));
|
||||||
|
|
||||||
|
return redirect()->route('member.profile')->with('status', 'Wir haben einen Bestätigungslink an '.$new.' geschickt. Die Adresse wechselt, sobald du ihn öffnest.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function confirmEmail(Request $request, int $id, string $hash): RedirectResponse
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
abort_unless($user->id === $id, 403);
|
||||||
|
$pending = $user->pending_email;
|
||||||
|
|
||||||
|
if (! is_string($pending) || $pending === '' || ! hash_equals(sha1($pending), $hash)) {
|
||||||
|
return redirect()->route('member.profile')->withErrors(['email' => 'Dieser Link gilt nicht mehr. Fordere die Änderung bitte erneut an.'], 'email');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (User::query()->where('email', $pending)->whereKeyNot($user->id)->exists()) {
|
||||||
|
$user->forceFill(['pending_email' => null])->save();
|
||||||
|
|
||||||
|
return redirect()->route('member.profile')->withErrors(['email' => 'Diese Adresse ist inzwischen vergeben.'], 'email');
|
||||||
|
}
|
||||||
|
|
||||||
|
$user->forceFill(['email' => $pending, 'pending_email' => null, 'email_verified_at' => now()])->save();
|
||||||
|
|
||||||
|
return redirect()->route('member.profile')->with('status', 'Deine E-Mail-Adresse ist geändert.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function cancelEmail(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$request->user()->forceFill(['pending_email' => null])->save();
|
||||||
|
|
||||||
|
return redirect()->route('member.profile')->with('status', 'Die Änderung der E-Mail-Adresse ist verworfen.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updatePassword(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||||
|
|
||||||
|
$data = $request->validateWithBag('password', [
|
||||||
|
'current_password' => ['required', 'current_password'],
|
||||||
|
'password' => ['required', 'confirmed', Password::defaults(), 'different:current_password'],
|
||||||
|
], [
|
||||||
|
'current_password.current_password' => 'Das bisherige Passwort stimmt nicht.',
|
||||||
|
'password.different' => 'Das neue Passwort muss sich vom bisherigen unterscheiden.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user->forceFill(['password' => Hash::make($data['password'])])->save();
|
||||||
|
$request->session()->regenerate();
|
||||||
|
|
||||||
|
return redirect()->route('member.profile')->with('status', 'Dein Passwort ist geändert.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function updateAddress(Request $request): RedirectResponse
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
abort_if($user->status !== AccountStatus::Aktiv || $user->party === null, 403);
|
||||||
|
|
||||||
|
$data = $request->validateWithBag('address', [
|
||||||
|
'recipient' => ['required', 'string', 'max:160'],
|
||||||
|
'line2' => ['nullable', 'string', 'max:160'],
|
||||||
|
'street' => ['required', 'string', 'max:160'],
|
||||||
|
'postal_code' => ['required', 'string', 'max:16'],
|
||||||
|
'city' => ['required', 'string', 'max:120'],
|
||||||
|
'country' => ['required', Rule::in(array_keys(BillingAddress::COUNTRIES))],
|
||||||
|
], [
|
||||||
|
'recipient.required' => 'Bitte gib Name oder Firma an.',
|
||||||
|
'street.required' => 'Bitte gib Straße und Hausnummer an.',
|
||||||
|
'postal_code.required' => 'Bitte gib die Postleitzahl an.',
|
||||||
|
'city.required' => 'Bitte gib den Ort an.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
BillingAddress::query()->updateOrCreate(['party_id' => $user->party_id], $data);
|
||||||
|
|
||||||
|
return redirect()->route('member.profile')->with('status', 'Die Rechnungsadresse ist gespeichert.');
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 363 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user