Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4584dcd013 | ||
|
|
cf8189623c | ||
|
|
9140e731f9 | ||
|
|
bb08b9b3fa | ||
|
|
e5b3eea7de | ||
|
|
b901b02cce | ||
|
|
79998f6347 | ||
|
|
26ca79cd22 | ||
|
|
bcda189267 | ||
|
|
bc140a0e83 | ||
|
|
ad03eee41f | ||
|
|
881703ba0e | ||
|
|
bbee288e69 | ||
|
|
d1f97a351a | ||
|
|
ef56befc0e | ||
|
|
0022fd50cb | ||
|
|
1d1f0ebb1f | ||
|
|
da02e0bbda | ||
|
|
3f9e463dfa | ||
|
|
03737a5fc7 | ||
|
|
b453a8be10 | ||
|
|
a3c159a729 | ||
|
|
b3fb619bda | ||
|
|
78c8870e4e | ||
|
|
dd3cc83057 | ||
|
|
32272e8e40 | ||
|
|
9db3a98440 | ||
|
|
f87e67ce02 | ||
|
|
fe39e1efb6 |
No files matched your search
@@ -70,3 +70,8 @@ PAYMENT_DRIVER=test
|
||||
MEDIA_PUBLIC_PATH=
|
||||
MEDIA_DERIVED_PATH=
|
||||
MEDIA_ORIGINALS_PATH=
|
||||
|
||||
# Übernahme von Übungen aus Shinkan. Die Adresse ist je Umgebung vorgegeben. Der Zugangsschlüssel kann hier stehen (hat
|
||||
# Vorrang) oder in der Verwaltung hinterlegt werden (Inhalte -> Übungen aus Shinkan). Werte nie ins Repository.
|
||||
SHINKAN_DISTRIBUTION_URL=
|
||||
SHINKAN_DISTRIBUTION_KEY=
|
||||
@@ -41,6 +41,7 @@ ## Server und Umgebungen
|
||||
|
||||
- Test und Prod laufen vorerst **beide auf `llm-node` (192.168.2.144)**, getrennt durch Compose-Projekt (`luf-test`, `luf-prod`), Verzeichnis, Env-Datei, Volumes und Zugangsdaten. Der Raspberry Pi ist als späteres Testsystem vorgesehen (Umzug über die Variablen in `deploy-test.yml`).
|
||||
- Secrets liegen nur in `/etc/luf/test.env` und `/etc/luf/prod.env` auf dem Server. **Keine Secrets, Passwörter, Keys oder `.env`-Dateien ins Repo, in Commits, Logs oder Chat-Ausgaben.**
|
||||
- **Ausnahme Shinkan-Zugangsschlüssel (ADR-49, Nachtrag vom 23.11.2026):** Dieser eine Schlüssel darf zusätzlich von Katalog- und Systemverwaltern in der Verwaltung hinterlegt werden (Inhalte → Übungen aus Shinkan). Er liegt je Umgebung getrennt mit dem Anwendungsschlüssel verschlüsselt in der Datenbank, wird nie angezeigt, zurückgegeben oder protokolliert. Ein Wert in `SHINKAN_DISTRIBUTION_KEY` (Serverdatei) hat Vorrang. Die Adresse (`SHINKAN_DISTRIBUTION_URL`) bleibt je Umgebung in der Serverdatei. Für alle anderen Schlüssel gilt die Regel unverändert.
|
||||
- **Auf Servern wird nur nach ausdrücklicher Freigabe geschrieben.** Rein lesende Abfragen über vorhandene SSH-Zugänge sind erlaubt. Keine SSH-Schlüssel, Benutzer, Firewall-, Proxy- oder Runner-Änderungen. Andere Anwendungen auf den Servern (Shinkan, Gitea, mindnet, qdrant, …) dürfen nicht verändert werden.
|
||||
- Ports werden nicht geraten: Vor jedem neuen Host-Port die tatsächliche Belegung prüfen (`ss`, `docker ps`). Aktuell vorgesehen: Test 3011, Prod 3010 (Stand 2026-11-15). Datenbank und PHP-FPM veröffentlichen keine Host-Ports.
|
||||
- Der Reverse Proxy (Synology NAS) wird von Lars verwaltet.
|
||||
|
||||
@@ -57,6 +57,8 @@ public function publishRelease(
|
||||
'content_element_version_id' => $row['version_id'],
|
||||
'role' => $row['role'] !== '' ? $row['role'] : $row['path'],
|
||||
'path' => $row['path'],
|
||||
'requirement' => $row['requirement'] ?? null,
|
||||
'variant_key' => $row['variant'] ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -141,6 +143,10 @@ private function checkedRows(ContentElementVersion|CompositionVersion $root): ar
|
||||
{
|
||||
$root->refresh();
|
||||
|
||||
if (app(ForeignCompositions::class)->reaches($root)) {
|
||||
throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Er wird hier nicht veröffentlicht, damit nichts fehlt oder zu viel ausgegeben wird.');
|
||||
}
|
||||
|
||||
if ($root->status !== ContentVersionStatus::Bereit) {
|
||||
throw new DomainRuleException('Ein Artikel-Stand kann nur eine bereitgestellte Fassung festschreiben.');
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ class CompatibilityAttestation extends Model
|
||||
protected $fillable = [
|
||||
'composition_version_id',
|
||||
'resolved_hash',
|
||||
'structure_hash',
|
||||
'confirmed_by',
|
||||
'confirmed_at',
|
||||
'note',
|
||||
|
||||
@@ -36,6 +36,11 @@ protected function casts(): array
|
||||
];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::addGlobalScope(new SupportedKindScope);
|
||||
}
|
||||
|
||||
public function editorialContentKind(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EditorialContentKind::class);
|
||||
|
||||
@@ -7,13 +7,24 @@ enum CompositionKind: string
|
||||
case Kombination = 'kombination';
|
||||
case Uebung = 'uebung';
|
||||
case Kurs = 'kurs';
|
||||
/** Seit der Übungsverwaltung: die fachliche Übung. Der ältere Wert `uebung` bezeichnet in der Verwaltung das Modul. */
|
||||
case Exercise = 'exercise';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_map(fn (self $case): string => $case->value, self::cases());
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombination',
|
||||
self::Uebung => 'Übung',
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Kurs',
|
||||
self::Exercise => 'Übung',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -21,8 +32,9 @@ public function plural(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombinationen',
|
||||
self::Uebung => 'Übungen',
|
||||
self::Uebung => 'Module',
|
||||
self::Kurs => 'Kurse',
|
||||
self::Exercise => 'Übungen',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -30,8 +42,9 @@ public function createLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Kombination anlegen',
|
||||
self::Uebung => 'Übung anlegen',
|
||||
self::Uebung => 'Modul anlegen',
|
||||
self::Kurs => 'Kurs anlegen',
|
||||
self::Exercise => 'Übung anlegen',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,6 +54,7 @@ public function explanation(): string
|
||||
self::Kombination => 'Didaktische oder thematische Zusammenstellung, zum Beispiel ein Materialsatz. Sie wird in Übungen und Kursen wiederverwendet und ist selbst kein Kurs.',
|
||||
self::Uebung => 'Eine konkrete Lernsituation, zum Beispiel aus Film und Merkblatt. Dieselben Medien können in mehreren Übungen stecken.',
|
||||
self::Kurs => 'Ein Ablauf für den Kursbetrieb aus Übungen, Kombinationen und Medien. Ein Kurs ist keine Übung.',
|
||||
self::Exercise => 'Eine Übung mit Lernziel, Vorbereitung, Durchführung und Varianten, mit Texten und Medien in fester Abfolge. Sie wird in Module und Programme aufgenommen.',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -50,6 +64,7 @@ public function deskLabel(): string
|
||||
self::Kombination => 'Fachliche Kombination',
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Programm',
|
||||
self::Exercise => 'Übung',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -59,6 +74,7 @@ public function deskExplanation(): string
|
||||
self::Kombination => $this->explanation(),
|
||||
self::Uebung => 'Ein Modul mit Lernziel, Zeit, Material und geordneten Bestandteilen. Dieselben Medien können in mehreren Modulen stecken.',
|
||||
self::Kurs => 'Ein Programm aus Modulen und weiteren Inhalten.',
|
||||
self::Exercise => $this->explanation(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,21 @@ class CompositionMember extends Model
|
||||
'placement_note',
|
||||
'content_element_version_id',
|
||||
'nested_composition_version_id',
|
||||
'variant_id',
|
||||
'requirement',
|
||||
'variant_selection',
|
||||
'origin',
|
||||
];
|
||||
|
||||
public const REQUIRED = 'erforderlich';
|
||||
|
||||
public const SUPPLEMENTARY = 'ergaenzend';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['variant_selection' => 'array'];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (CompositionMember $member): void {
|
||||
@@ -41,6 +54,11 @@ public function contentElementVersion(): BelongsTo
|
||||
return $this->belongsTo(ContentElementVersion::class);
|
||||
}
|
||||
|
||||
public function variant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersionVariant::class, 'variant_id');
|
||||
}
|
||||
|
||||
public function nestedCompositionVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id');
|
||||
|
||||
@@ -54,6 +54,7 @@ public function publish(
|
||||
?string $note,
|
||||
array $didactic,
|
||||
bool $consent,
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
$review = $this->review($host, $members);
|
||||
|
||||
@@ -67,8 +68,8 @@ public function publish(
|
||||
|
||||
$this->publishedDrafts = [];
|
||||
|
||||
return DB::transaction(function () use ($host, $members, $actor, $note, $didactic): CompositionVersion {
|
||||
return $this->materialize($host, $members, $didactic, $actor, $note, []);
|
||||
return DB::transaction(function () use ($host, $members, $actor, $note, $didactic, $variants): CompositionVersion {
|
||||
return $this->materialize($host, $members, $didactic, $actor, $note, [], $variants);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -220,6 +221,12 @@ private function inspectReleasedComposition(
|
||||
): void {
|
||||
$version = CompositionVersion::query()->with('composition', 'members')->find($id);
|
||||
|
||||
if ($version instanceof CompositionVersion && $version->composition === null && app(ForeignCompositions::class)->isForeignVersion($version->id)) {
|
||||
$blocked[] = $this->block('Bestandteil', 'Dieser Bestandteil stammt aus einer neueren Programmversion und kann hier nicht freigegeben werden.', $depth, null);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $version instanceof CompositionVersion || $version->composition === null) {
|
||||
$blocked[] = $this->block('Modul', 'Ein Bestandteil ist nicht mehr vorhanden.', $depth, null);
|
||||
|
||||
@@ -324,6 +331,7 @@ private function materialize(
|
||||
?User $actor,
|
||||
?string $note,
|
||||
array $stack,
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
if (isset($this->publishedDrafts[$composition->id])) {
|
||||
return $this->publishedDrafts[$composition->id];
|
||||
@@ -341,6 +349,10 @@ private function materialize(
|
||||
'role' => trim((string) ($member['role'] ?? '')),
|
||||
'note' => trim((string) ($member['note'] ?? '')),
|
||||
'target' => $this->resolveTarget((string) ($member['target'] ?? ''), $actor, $stack),
|
||||
'variant' => isset($member['variant']) && $member['variant'] !== '' ? (string) $member['variant'] : null,
|
||||
'requirement' => $member['requirement'] ?? 'erforderlich',
|
||||
'selection' => is_array($member['selection'] ?? null) && $member['selection'] !== [] ? array_values($member['selection']) : null,
|
||||
'origin' => $member['origin'] ?? 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -352,8 +364,11 @@ private function materialize(
|
||||
[
|
||||
'learning_goal' => $didactic['learning_goal'] ?? null,
|
||||
'duration_minutes' => $didactic['duration_minutes'] ?? null,
|
||||
'duration_max' => $didactic['duration_max'] ?? null,
|
||||
'material_note' => $didactic['material_note'] ?? null,
|
||||
'prerequisites' => $didactic['prerequisites'] ?? null,
|
||||
],
|
||||
$variants,
|
||||
);
|
||||
$this->publishedDrafts[$composition->id] = $version;
|
||||
|
||||
@@ -414,11 +429,14 @@ private function resolveTarget(string $target, ?User $actor, array $stack): Cont
|
||||
[
|
||||
'learning_goal' => $draft['learning_goal'] ?? null,
|
||||
'duration_minutes' => $draft['duration_minutes'] ?? null,
|
||||
'duration_max' => $draft['duration_max'] ?? null,
|
||||
'material_note' => $draft['material_note'] ?? null,
|
||||
'prerequisites' => $draft['prerequisites'] ?? null,
|
||||
],
|
||||
$actor,
|
||||
is_string($draft['revision_note'] ?? null) ? $draft['revision_note'] : null,
|
||||
$stack,
|
||||
is_array($draft['variants'] ?? null) ? $draft['variants'] : [],
|
||||
);
|
||||
app(EditorialWorkingDraft::class)->clear($composition);
|
||||
|
||||
|
||||
@@ -60,6 +60,11 @@ private function members(CompositionVersion $version, array $stack = []): array
|
||||
$nested->loadMissing('composition.editorialContentKind', 'composition');
|
||||
$composition = $nested->composition;
|
||||
|
||||
// Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht anzeigen (Rückfallschutz).
|
||||
if ($composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$nodes[] = new StructureNode(
|
||||
role: $member->role,
|
||||
position: $member->position,
|
||||
|
||||
@@ -17,6 +17,10 @@ class CompositionVersion extends Model
|
||||
'learning_goal',
|
||||
'duration_minutes',
|
||||
'material_note',
|
||||
'duration_max',
|
||||
'prerequisites',
|
||||
'structure_hash',
|
||||
'source_snapshot_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -60,6 +64,11 @@ public function members(): HasMany
|
||||
return $this->hasMany(CompositionMember::class)->orderBy('position');
|
||||
}
|
||||
|
||||
public function variants(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompositionVersionVariant::class)->orderBy('position');
|
||||
}
|
||||
|
||||
public function attestations(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompatibilityAttestation::class);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Durchführungsvariante einer Übungsfassung. Der Schlüssel ist je Fassung eindeutig und bleibt über Fassungen hinweg
|
||||
* gleich, damit eine Auswahl im Modul oder Programm und der Abgleich mit einer Quelle dieselbe Variante meinen.
|
||||
* Wie die Mitglieder ist sie nur im Entwurf der Fassung schreibbar.
|
||||
*/
|
||||
class CompositionVersionVariant extends Model
|
||||
{
|
||||
protected $fillable = ['composition_version_id', 'key', 'position', 'name', 'description', 'origin'];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (CompositionVersionVariant $variant): void {
|
||||
$status = CompositionVersion::query()->whereKey($variant->composition_version_id)->value('status');
|
||||
|
||||
if (StatusValue::of($status) === ContentVersionStatus::Bereit->value) {
|
||||
throw new DomainRuleException('Eine bestätigte Kompositionsfassung nimmt keine weiteren Varianten auf.');
|
||||
}
|
||||
});
|
||||
|
||||
static::updating(function (): void {
|
||||
throw new DomainRuleException('Varianten einer Komposition werden nicht verändert, sondern durch eine neue Fassung ersetzt.');
|
||||
});
|
||||
}
|
||||
|
||||
public function compositionVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ class ContentElement extends Model
|
||||
'preview_path',
|
||||
'editorial_content_kind_id',
|
||||
'archived_at',
|
||||
'source_ref',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
|
||||
@@ -5,9 +5,14 @@
|
||||
class ContentResolver
|
||||
{
|
||||
/**
|
||||
* @return list<array{version_id: int, role: string, path: string}>
|
||||
* Löst eine Wurzel zu den enthaltenen Medienfassungen auf. Eine Übung wird nur mit ihren gemeinsamen Mitgliedern und
|
||||
* den ausgewählten Varianten aufgelöst: Das Mitglied, das die Übungsfassung einbindet, trägt die Auswahl
|
||||
* (`variant_selection`, Liste von Variantenschlüsseln; leer gelassen bedeutet alle Varianten).
|
||||
*
|
||||
* @param list<string>|null $selection Variantenschlüssel, die für diese Fassung gelten; null = alle
|
||||
* @return list<array{version_id: int, role: string, path: string, requirement: string, variant: string|null}>
|
||||
*/
|
||||
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = []): array
|
||||
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = [], ?array $selection = null): array
|
||||
{
|
||||
if ($node instanceof ContentElementVersion) {
|
||||
$node->loadMissing('element');
|
||||
@@ -16,6 +21,8 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'version_id' => $node->id,
|
||||
'role' => $path,
|
||||
'path' => $path !== '' ? $path : $node->element->working_title,
|
||||
'requirement' => CompositionMember::REQUIRED,
|
||||
'variant' => null,
|
||||
]];
|
||||
}
|
||||
|
||||
@@ -26,7 +33,13 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
$stack[] = $node->composition_id;
|
||||
$rows = [];
|
||||
|
||||
foreach ($node->members()->orderBy('position')->get() as $member) {
|
||||
foreach ($node->members()->with('variant')->orderBy('position')->get() as $member) {
|
||||
$variantKey = $member->variant?->key;
|
||||
|
||||
if ($variantKey !== null && $selection !== null && ! in_array($variantKey, $selection, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$segment = $path === '' ? $member->role : $path.' / '.$member->role;
|
||||
|
||||
if ($member->content_element_version_id !== null) {
|
||||
@@ -34,6 +47,8 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'version_id' => $member->content_element_version_id,
|
||||
'role' => $member->role,
|
||||
'path' => $segment,
|
||||
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
|
||||
'variant' => $variantKey,
|
||||
];
|
||||
|
||||
continue;
|
||||
@@ -45,7 +60,20 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.');
|
||||
}
|
||||
|
||||
$rows = array_merge($rows, $this->expand($nested, $segment, $stack));
|
||||
// Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht auflösen (Rückfallschutz).
|
||||
// Veröffentlichen verweigern die aufrufenden Stellen über ForeignCompositions.
|
||||
$nested->loadMissing('composition');
|
||||
|
||||
if ($nested->composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows = array_merge($rows, $this->expand(
|
||||
$nested,
|
||||
$segment,
|
||||
$stack,
|
||||
is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null,
|
||||
));
|
||||
}
|
||||
|
||||
return $rows;
|
||||
|
||||
@@ -225,7 +225,9 @@ public function releaseElementVersion(ContentElementVersion $version): ContentEl
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
|
||||
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion, note?: string|null, variant?: string|null, requirement?: string|null, selection?: list<string>|null}> $members
|
||||
* @param array{learning_goal?: mixed, duration_minutes?: mixed, duration_max?: mixed, material_note?: mixed, prerequisites?: mixed} $didactic
|
||||
* @param list<array{key: string, name: string, description?: string|null, origin?: string}> $variants Durchführungsvarianten einer Übung
|
||||
*/
|
||||
public function publishComposition(
|
||||
Composition $composition,
|
||||
@@ -233,18 +235,21 @@ public function publishComposition(
|
||||
?User $confirmedBy = null,
|
||||
?string $note = null,
|
||||
array $didactic = [],
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
if ($members === []) {
|
||||
throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.');
|
||||
}
|
||||
|
||||
$variants = $this->checkedVariants($variants);
|
||||
$this->assertAcyclic($composition->id, $members);
|
||||
|
||||
foreach ($members as $member) {
|
||||
$this->assertReadyMember($member['target']);
|
||||
$this->assertMemberPlacement($member, $variants);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic): CompositionVersion {
|
||||
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic, $variants): CompositionVersion {
|
||||
$number = ((int) $composition->versions()->max('number')) + 1;
|
||||
$version = $composition->versions()->create([
|
||||
'number' => $number,
|
||||
@@ -253,28 +258,52 @@ public function publishComposition(
|
||||
'resolved_hash' => 'pending',
|
||||
'learning_goal' => $this->optionalText($didactic['learning_goal'] ?? null),
|
||||
'duration_minutes' => isset($didactic['duration_minutes']) ? (int) $didactic['duration_minutes'] : null,
|
||||
'duration_max' => isset($didactic['duration_max']) ? (int) $didactic['duration_max'] : null,
|
||||
'material_note' => $this->optionalText($didactic['material_note'] ?? null),
|
||||
'prerequisites' => $this->optionalText($didactic['prerequisites'] ?? null),
|
||||
'source_snapshot_id' => isset($didactic['source_snapshot_id']) ? (int) $didactic['source_snapshot_id'] : null,
|
||||
]);
|
||||
|
||||
$variantIds = [];
|
||||
|
||||
foreach ($variants as $index => $variant) {
|
||||
$variantIds[$variant['key']] = $version->variants()->create([
|
||||
'key' => $variant['key'],
|
||||
'position' => $index + 1,
|
||||
'name' => $variant['name'],
|
||||
'description' => $variant['description'],
|
||||
'origin' => $variant['origin'],
|
||||
])->id;
|
||||
}
|
||||
|
||||
foreach (array_values($members) as $index => $member) {
|
||||
$target = $member['target'];
|
||||
$selection = $target instanceof CompositionVersion ? ($member['selection'] ?? null) : null;
|
||||
$version->members()->create([
|
||||
'position' => $index + 1,
|
||||
'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'),
|
||||
'placement_note' => $this->optionalText($member['note'] ?? null),
|
||||
'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
||||
'nested_composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
|
||||
'variant_id' => isset($member['variant']) ? $variantIds[$member['variant']] : null,
|
||||
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
|
||||
'variant_selection' => $selection === null ? null : array_values($selection),
|
||||
'origin' => ($member['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
]);
|
||||
}
|
||||
|
||||
$version->load('members.variant', 'variants');
|
||||
$resolvedHash = $this->resolver->resolvedHash($version);
|
||||
$structureHash = $this->structureHash($version);
|
||||
$version->attestations()->create([
|
||||
'resolved_hash' => $resolvedHash,
|
||||
'structure_hash' => $structureHash,
|
||||
'confirmed_by' => $confirmedBy?->id,
|
||||
'confirmed_at' => now(),
|
||||
'note' => $note,
|
||||
]);
|
||||
$version->resolved_hash = $resolvedHash;
|
||||
$version->structure_hash = $structureHash;
|
||||
$version->status = ContentVersionStatus::Bereit;
|
||||
$version->save();
|
||||
|
||||
@@ -282,6 +311,103 @@ public function publishComposition(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Änderungsnachweis einer Fassung: Felder, Varianten und die Verwendung jedes Mitglieds. Anders als der
|
||||
* `resolved_hash` (nur die Menge der enthaltenen Medienfassungen) ändert er sich auch dann, wenn Variante,
|
||||
* Verwendung, Reihenfolge oder Variantenauswahl wechseln und die Medien gleich bleiben.
|
||||
*/
|
||||
public function structureHash(CompositionVersion $version): string
|
||||
{
|
||||
$version->loadMissing('members.variant', 'variants');
|
||||
|
||||
return hash('sha256', json_encode([
|
||||
'fields' => [
|
||||
$version->learning_goal,
|
||||
$version->duration_minutes,
|
||||
$version->duration_max,
|
||||
$version->material_note,
|
||||
$version->prerequisites,
|
||||
],
|
||||
'variants' => $version->variants->map(fn (CompositionVersionVariant $variant): array => [
|
||||
$variant->key, $variant->position, $variant->name, $variant->description, $variant->origin,
|
||||
])->all(),
|
||||
'members' => $version->members->map(fn (CompositionMember $member): array => [
|
||||
$member->position,
|
||||
$member->role,
|
||||
$member->placement_note,
|
||||
$member->content_element_version_id,
|
||||
$member->nested_composition_version_id,
|
||||
$member->variant?->key,
|
||||
$member->requirement,
|
||||
$member->variant_selection,
|
||||
$member->origin,
|
||||
])->all(),
|
||||
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{key?: string, name?: string, description?: string|null}> $variants
|
||||
* @return list<array{key: string, name: string, description: string|null}>
|
||||
*/
|
||||
private function checkedVariants(array $variants): array
|
||||
{
|
||||
$checked = [];
|
||||
$keys = [];
|
||||
|
||||
foreach (array_values($variants) as $variant) {
|
||||
$key = trim((string) ($variant['key'] ?? ''));
|
||||
|
||||
if ($key === '' || in_array($key, $keys, true)) {
|
||||
throw new DomainRuleException('Jede Variante braucht einen eigenen Schlüssel.');
|
||||
}
|
||||
|
||||
$keys[] = $key;
|
||||
$checked[] = [
|
||||
'key' => $key,
|
||||
'name' => $this->required((string) ($variant['name'] ?? ''), 'Jede Variante braucht einen Namen.'),
|
||||
'description' => $this->optionalText($variant['description'] ?? null),
|
||||
'origin' => ($variant['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
return $checked;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{target: ContentElementVersion|CompositionVersion, variant?: string|null, requirement?: string|null, selection?: list<string>|null} $member
|
||||
* @param list<array{key: string, name: string, description: string|null}> $variants
|
||||
*/
|
||||
private function assertMemberPlacement(array $member, array $variants): void
|
||||
{
|
||||
$variant = $member['variant'] ?? null;
|
||||
|
||||
if ($variant !== null && ! in_array($variant, array_column($variants, 'key'), true)) {
|
||||
throw new DomainRuleException('Ein Mitglied verweist auf eine Variante, die es in dieser Fassung nicht gibt.');
|
||||
}
|
||||
|
||||
$requirement = $member['requirement'] ?? CompositionMember::REQUIRED;
|
||||
|
||||
if (! in_array($requirement, [CompositionMember::REQUIRED, CompositionMember::SUPPLEMENTARY], true)) {
|
||||
throw new DomainRuleException('Die Verwendung eines Mitglieds ist erforderlich oder ergänzend.');
|
||||
}
|
||||
|
||||
$selection = $member['selection'] ?? null;
|
||||
|
||||
if ($selection === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $member['target'] instanceof CompositionVersion) {
|
||||
throw new DomainRuleException('Eine Variantenauswahl gibt es nur an einer eingebundenen Übungsfassung.');
|
||||
}
|
||||
|
||||
$offered = $member['target']->variants()->pluck('key')->all();
|
||||
|
||||
if ($selection === [] || array_diff($selection, $offered) !== []) {
|
||||
throw new DomainRuleException('Die Variantenauswahl nennt eine Variante, die die eingebundene Fassung nicht anbietet, oder keine.');
|
||||
}
|
||||
}
|
||||
|
||||
public function createComposition(string $designation, CompositionKind $kind = CompositionKind::Uebung): Composition
|
||||
{
|
||||
return Composition::query()->create([
|
||||
@@ -345,6 +471,10 @@ private function assertAcyclic(int $compositionId, array $members, array $stack
|
||||
|
||||
private function assertReadyMember(ContentElementVersion|CompositionVersion $target): void
|
||||
{
|
||||
if (app(ForeignCompositions::class)->reaches($target)) {
|
||||
throw new DomainRuleException('Dieser Bestandteil stammt aus einer neueren Programmversion und wird hier nicht in eine Fassung aufgenommen.');
|
||||
}
|
||||
|
||||
if ($target->status !== ContentVersionStatus::Bereit) {
|
||||
throw new DomainRuleException('Eine Komposition darf nur bereitgestellte Fassungen enthalten.');
|
||||
}
|
||||
@@ -365,6 +495,9 @@ private function membersHash(array $members): string
|
||||
'note' => $this->optionalText($member['note'] ?? null),
|
||||
'element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
||||
'composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
|
||||
'variant' => $member['variant'] ?? null,
|
||||
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
|
||||
'selection' => $member['selection'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ class EditorialContentKind extends Model
|
||||
public const CONTEXTS = [
|
||||
'medium' => 'Medium',
|
||||
'modul' => 'Modul',
|
||||
'uebung' => 'Übung',
|
||||
'programm' => 'Programm',
|
||||
'lizenzartikel' => 'Lizenzartikel',
|
||||
];
|
||||
@@ -26,7 +27,7 @@ class EditorialContentKind extends Model
|
||||
* Modulen (programm, modul), Vertraulichkeit von Traineranleitungen (traineranleitung). Ihre Bezeichnung bleibt
|
||||
* pflegbar; deaktivieren, Kontexte ändern und löschen sind gesperrt.
|
||||
*/
|
||||
public const SYSTEM_SLUGS = ['programm', 'modul', 'traineranleitung'];
|
||||
public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'traineranleitung'];
|
||||
|
||||
protected $fillable = [
|
||||
'slug',
|
||||
|
||||
@@ -46,6 +46,7 @@ public static function compositionContext(?CompositionKind $kind): ?string
|
||||
return match ($kind) {
|
||||
CompositionKind::Kurs => 'programm',
|
||||
CompositionKind::Uebung => 'modul',
|
||||
CompositionKind::Exercise => 'uebung',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
@@ -137,6 +138,7 @@ private function usedKindIds(string $context): array
|
||||
'lizenzartikel' => DB::table('license_articles'),
|
||||
'programm' => DB::table('compositions')->where('kind', CompositionKind::Kurs->value),
|
||||
'modul' => DB::table('compositions')->where('kind', CompositionKind::Uebung->value),
|
||||
'uebung' => DB::table('compositions')->where('kind', CompositionKind::Exercise->value),
|
||||
default => null,
|
||||
};
|
||||
|
||||
|
||||
@@ -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,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Material-Tags des Brand-Kits (Film, Übung, PDF, Paket, Film + Übungen, Film + Merkblatt).
|
||||
*
|
||||
* Die Zuordnung hängt an Schlüsseln (Ausgabeklasse des Mediums, Kennung der redaktionellen Art), nie an Beschriftungen.
|
||||
* Was nicht eindeutig zuzuordnen ist, bekommt kein Tag und bleibt Text:
|
||||
* - „Paket“ und die beiden Kombinationen werden nicht automatisch vergeben (offen: Paket als Angebot oder als Programm;
|
||||
* Kombinationen aus dem Modulaufbau berechnen oder redaktionell wählen). Die Komponente kann sie darstellen.
|
||||
* - „Dokument“ ist nicht automatisch PDF; das Tag PDF gibt es nur für die Ausgabeklasse „pdf“.
|
||||
*/
|
||||
enum MaterialTag: string
|
||||
{
|
||||
case Film = 'film';
|
||||
case Uebung = 'uebung';
|
||||
case Pdf = 'pdf';
|
||||
case Paket = 'paket';
|
||||
case FilmUebungen = 'film-uebungen';
|
||||
case FilmMerkblatt = 'film-merkblatt';
|
||||
|
||||
private const FILM_KINDS = ['unterrichtsfilm', 'kurzfilm', 'trailer', 'interview'];
|
||||
|
||||
private const EXERCISE_KINDS = ['arbeitsblatt', 'uebungsbeschreibung'];
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Film => 'Film',
|
||||
self::Uebung => 'Übung',
|
||||
self::Pdf => 'PDF',
|
||||
self::Paket => 'Paket',
|
||||
self::FilmUebungen => 'Film + Übungen',
|
||||
self::FilmMerkblatt => 'Film + Merkblatt',
|
||||
};
|
||||
}
|
||||
|
||||
/** Name des Zeichens im Satz „glyphen“ (resources/svg/brand/glyphen). */
|
||||
public function glyph(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Film => 'film',
|
||||
self::Uebung => 'uebung',
|
||||
self::Pdf, self::FilmMerkblatt => 'dokument',
|
||||
self::Paket => 'paket',
|
||||
self::FilmUebungen => 'filmstreifen',
|
||||
};
|
||||
}
|
||||
|
||||
public static function fromContent(?string $outputClass, ?string $editorialKindSlug = null): ?self
|
||||
{
|
||||
return match (true) {
|
||||
$outputClass === 'film' => self::Film,
|
||||
$outputClass === 'pdf' => self::Pdf,
|
||||
in_array($editorialKindSlug, self::FILM_KINDS, true) => self::Film,
|
||||
in_array($editorialKindSlug, self::EXERCISE_KINDS, true) => self::Uebung,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,27 @@ class OfferCoverage
|
||||
{
|
||||
public function __construct(private readonly ContentResolver $resolver) {}
|
||||
|
||||
/**
|
||||
* Bestandteile der Fassung, deren Medienfassung gesperrt ist. Ein Angebot soll nicht aktiviert werden, solange sein
|
||||
* Umfang gesperrte Bestandteile enthält; die Prüfung nennt sie vorab.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function blockedLeaves(CompositionVersion $version): array
|
||||
{
|
||||
$rows = $this->resolver->expand($version);
|
||||
$blocked = ContentElementVersion::query()
|
||||
->whereIn('id', array_column($rows, 'version_id'))
|
||||
->where('status', ContentVersionStatus::Gesperrt->value)
|
||||
->pluck('id')
|
||||
->all();
|
||||
|
||||
return array_values(array_map(
|
||||
fn (array $row): string => $row['path'],
|
||||
array_filter($rows, fn (array $row): bool => in_array($row['version_id'], $blocked, true)),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<LicenseArticle> $articles
|
||||
* @return list<string>
|
||||
|
||||
@@ -277,6 +277,10 @@ private function assertCoverage(array $lines, array $attributes): void
|
||||
}
|
||||
|
||||
$version = CompositionVersion::query()->findOrFail($versionId);
|
||||
|
||||
if (app(ForeignCompositions::class)->reaches($version)) {
|
||||
throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Das Angebot wird hier nicht aktiviert.');
|
||||
}
|
||||
$articles = [];
|
||||
|
||||
foreach ($lines as $line) {
|
||||
@@ -285,6 +289,12 @@ private function assertCoverage(array $lines, array $attributes): void
|
||||
}
|
||||
}
|
||||
|
||||
$blocked = app(OfferCoverage::class)->blockedLeaves($version);
|
||||
|
||||
if ($blocked !== []) {
|
||||
throw new DomainRuleException('Das Angebot enthält gesperrte Bestandteile: '.implode(', ', $blocked));
|
||||
}
|
||||
|
||||
$missing = app(OfferCoverage::class)->missingLeaves($version, $articles);
|
||||
|
||||
if ($missing !== []) {
|
||||
|
||||
@@ -13,6 +13,8 @@ class ReleaseContent extends Model
|
||||
'content_element_version_id',
|
||||
'role',
|
||||
'path',
|
||||
'requirement',
|
||||
'variant_key',
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Design\SiteSetting;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
|
||||
/**
|
||||
* Zugang zum Shinkan-Katalog. Die Adresse ist je Umgebung vorgegeben (`SHINKAN_DISTRIBUTION_URL`). Der Zugangsschlüssel
|
||||
* kommt aus der Umgebung des Servers (`SHINKAN_DISTRIBUTION_KEY`, hat Vorrang und bleibt die bestehende Anbindung) oder
|
||||
* ist in der Verwaltung hinterlegt. So lässt sich der Schlüssel ersetzen, ohne die Umgebung des Servers anzufassen.
|
||||
*
|
||||
* Der in der Verwaltung hinterlegte Schlüssel liegt je Umgebung getrennt und mit dem Anwendungsschlüssel verschlüsselt in
|
||||
* den Einstellungen. Er wird nie zurückgegeben, nie angezeigt und nie protokolliert und steht in keiner Fehlermeldung.
|
||||
*/
|
||||
final class ShinkanConnection
|
||||
{
|
||||
public const SETTING = 'shinkan.anbindung';
|
||||
|
||||
public const SERVER = 'server';
|
||||
|
||||
public const ADMIN = 'verwaltung';
|
||||
|
||||
public function url(): ?string
|
||||
{
|
||||
$value = config('services.shinkan.url');
|
||||
|
||||
if (! is_string($value) || trim($value) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Die Adresse ist die der Shinkan-Installation. Der Pfad `/api/distribution/v1` hängt der Abruf selbst an; wer ihn
|
||||
// (oder nur `/api`) mit einträgt, bekommt trotzdem die richtige Adresse und keinen doppelten Pfad.
|
||||
$base = rtrim(trim($value), '/');
|
||||
$base = (string) preg_replace('#/api(/distribution(/v1)?)?$#', '', $base);
|
||||
|
||||
return $base === '' ? null : $base;
|
||||
}
|
||||
|
||||
public function apiKey(): ?string
|
||||
{
|
||||
$server = $this->serverKey();
|
||||
|
||||
if ($server !== null) {
|
||||
return $server;
|
||||
}
|
||||
|
||||
$encrypted = $this->stored()['key'] ?? null;
|
||||
|
||||
if (! is_string($encrypted) || $encrypted === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return Crypt::decryptString($encrypted);
|
||||
} catch (DecryptException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Woher kommt der Schlüssel? `server`, `verwaltung` oder null.
|
||||
*/
|
||||
public function keySource(): ?string
|
||||
{
|
||||
if ($this->serverKey() !== null) {
|
||||
return self::SERVER;
|
||||
}
|
||||
|
||||
return $this->apiKey() !== null ? self::ADMIN : null;
|
||||
}
|
||||
|
||||
public function configured(): bool
|
||||
{
|
||||
return $this->url() !== null && $this->apiKey() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hinterlegt oder ersetzt den Schlüssel. Der Schlüssel aus der Umgebung des Servers behält den Vorrang.
|
||||
*/
|
||||
public function saveKey(string $key, ?User $by = null): void
|
||||
{
|
||||
$key = trim($key);
|
||||
|
||||
if ($key === '') {
|
||||
throw new DomainRuleException('Der Zugangsschlüssel fehlt.');
|
||||
}
|
||||
|
||||
$this->write(['key' => Crypt::encryptString($key)], $by);
|
||||
}
|
||||
|
||||
public function forgetKey(?User $by = null): void
|
||||
{
|
||||
$this->write([], $by);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function stored(): array
|
||||
{
|
||||
$value = SiteSetting::query()->find(self::SETTING)?->value;
|
||||
|
||||
return is_array($value) ? $value : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $stored
|
||||
*/
|
||||
private function write(array $stored, ?User $by): void
|
||||
{
|
||||
SiteSetting::query()->updateOrCreate(['key' => self::SETTING], ['value' => $stored, 'updated_by' => $by?->id]);
|
||||
}
|
||||
|
||||
private function serverKey(): ?string
|
||||
{
|
||||
$value = config('services.shinkan.key');
|
||||
|
||||
return is_string($value) && trim($value) !== '' ? trim($value) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,827 @@
|
||||
<?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 adoptPreviewed}) und ist danach unveränderlich.
|
||||
* Lokale Ergänzungen (Herkunft „lokal“) bleiben bei einer neuen Quellfassung erhalten. Entfällt die Quellvariante einer
|
||||
* lokalen Ergänzung, legt die Redaktion die neue Zuordnung fest.
|
||||
* - Das Ausblenden an der Quelle setzt nur die Verfügbarkeit. Lokale Fassungen und Verwendungen bleiben unberührt; eine
|
||||
* rechtliche Sperre ist der lokale `block`. Ausgeblendete Quellen sind von der Übernahme ausgeschlossen.
|
||||
* - 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. */
|
||||
public const SECTIONS = [
|
||||
'preparation' => 'Vorbereitung',
|
||||
'execution' => 'Durchführung',
|
||||
'trainer_notes' => 'Trainerhinweise',
|
||||
];
|
||||
|
||||
/** Änderungshinweis der Textfassungen, die die Übernahme angelegt hat. Alles andere ist eine lokale Bearbeitung. */
|
||||
private const IMPORT_NOTE = 'Übernahme aus Shinkan';
|
||||
|
||||
/** Fassungsfelder der Quelle: Katalogfeld => [Feld der lokalen Fassung, Bezeichnung]. */
|
||||
private const FIELDS = [
|
||||
'goal' => ['learning_goal', 'Lernziel'],
|
||||
'duration_min' => ['duration_minutes', 'Dauer (von)'],
|
||||
'duration_max' => ['duration_max', 'Dauer (bis)'],
|
||||
'equipment' => ['material_note', 'Ausstattung'],
|
||||
];
|
||||
|
||||
public function configured(): bool
|
||||
{
|
||||
return app(ShinkanConnection::class)->configured();
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand der Anbindung ohne Werte: ob Adresse und Schlüssel vorhanden sind und woher der Schlüssel kommt.
|
||||
*
|
||||
* @return array{url: bool, key: bool, host: string|null, key_source: string|null}
|
||||
*/
|
||||
public function status(): array
|
||||
{
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$url = $connection->url();
|
||||
|
||||
return [
|
||||
'url' => $url !== null,
|
||||
'key' => $connection->apiKey() !== null,
|
||||
'host' => $url !== null ? (parse_url($url, PHP_URL_HOST) ?: null) : null,
|
||||
'key_source' => $connection->keySource(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Verbindung prüfen, ohne etwas zu speichern. Mit `$candidateKey` wird ein noch nicht hinterlegter Schlüssel
|
||||
* geprüft. Der Katalogabruf legt auf der Seite von Shinkan einen Stand an; hier wird nur gezählt.
|
||||
*
|
||||
* @return array{ok: bool, message: string}
|
||||
*/
|
||||
public function check(?string $candidateKey = null): array
|
||||
{
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$key = filled($candidateKey) ? trim((string) $candidateKey) : $connection->apiKey();
|
||||
|
||||
if ($connection->url() === null || $key === null) {
|
||||
return ['ok' => false, 'message' => 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.'];
|
||||
}
|
||||
|
||||
try {
|
||||
$catalog = $this->get('/catalog', [], $key);
|
||||
} catch (Throwable $exception) {
|
||||
return ['ok' => false, 'message' => 'Die Verbindung ist fehlgeschlagen: '.$this->plain($exception)];
|
||||
}
|
||||
|
||||
$count = count((array) ($catalog['exercises'] ?? []));
|
||||
|
||||
return ['ok' => true, 'message' => 'Die Verbindung funktioniert. Die Quelle stellt '.$count.($count === 1 ? ' Übung' : ' Übungen').' bereit. Es wurde nichts übernommen.'];
|
||||
}
|
||||
|
||||
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 oder Zugangsschlüssel fehlen.');
|
||||
}
|
||||
|
||||
$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',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschau der geplanten Übernahme: verfügbare Texte, Varianten und Medienhinweise, bei einer neuen Quellfassung die
|
||||
* fachlich relevanten Änderungen zur zuletzt übernommenen Fassung und offene Zuordnungen lokaler Ergänzungen.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function preview(ExerciseSource $source): array
|
||||
{
|
||||
$snapshot = $source->latestSnapshot();
|
||||
$state = $this->state($source);
|
||||
$document = $snapshot?->payload ?? [];
|
||||
$previous = $this->lastAdopted($source);
|
||||
$sections = [];
|
||||
|
||||
foreach (self::SECTIONS as $field => $label) {
|
||||
if (trim((string) ($document[$field] ?? '')) !== '') {
|
||||
$sections[] = ['label' => $label, 'text' => mb_strimwidth(trim((string) $document[$field]), 0, 280, '…')];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'source' => $source->id,
|
||||
'snapshot' => $snapshot?->id,
|
||||
'hash' => $snapshot?->content_hash,
|
||||
'state' => $state,
|
||||
'title' => (string) ($document['title'] ?? $source->title),
|
||||
'summary' => (string) ($document['summary'] ?? ''),
|
||||
'goal' => (string) ($document['goal'] ?? ''),
|
||||
'duration' => $this->duration($document),
|
||||
'equipment' => (string) ($document['equipment'] ?? ''),
|
||||
'sections' => $sections,
|
||||
'variants' => array_map(fn (array $variant): array => [
|
||||
'key' => (string) ($variant['id'] ?? ''),
|
||||
'name' => (string) ($variant['name'] ?? ''),
|
||||
'description' => (string) ($variant['description'] ?? ''),
|
||||
'changes' => trim((string) ($variant['execution_changes'] ?? '')) !== '',
|
||||
], array_values(array_filter((array) ($document['variants'] ?? []), 'is_array'))),
|
||||
'media' => array_map(fn (array $media): string => ($media['title'] ?? 'Medium').' ('.($media['media_type'] ?? '').')', array_values(array_filter((array) ($document['media'] ?? []), 'is_array'))),
|
||||
'changes' => $previous === null ? [] : $this->changes($previous->payload, $document, $source),
|
||||
'conflicts' => $snapshot === null ? [] : $this->conflicts($source, $document),
|
||||
'text_conflicts' => $snapshot === null ? [] : $this->textDecisions($source, $document, 'conflict'),
|
||||
'kept_local' => $snapshot === null ? [] : array_column($this->textDecisions($source, $document, 'keep_local'), 'label'),
|
||||
'identical' => $snapshot !== null && $snapshot->adopted_version_id !== null,
|
||||
'excluded' => $source->availability === ExerciseSource::WITHDRAWN,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fachlich relevante Änderungen einer neuen Quellfassung zur zuletzt übernommenen.
|
||||
*
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
* @return list<string>
|
||||
*/
|
||||
public function changes(array $before, array $after, ?ExerciseSource $source = null): array
|
||||
{
|
||||
$lines = [];
|
||||
$labels = [
|
||||
'title' => 'Titel', 'summary' => 'Kurzbeschreibung', 'goal' => 'Lernziel', 'equipment' => 'Ausstattung',
|
||||
'duration_min' => 'Dauer (von)', 'duration_max' => 'Dauer (bis)',
|
||||
] + self::SECTIONS;
|
||||
|
||||
foreach ($labels as $field => $label) {
|
||||
if (trim((string) ($before[$field] ?? '')) !== trim((string) ($after[$field] ?? ''))) {
|
||||
$lines[] = $label.' geändert';
|
||||
}
|
||||
}
|
||||
|
||||
$old = collect((array) ($before['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
|
||||
$new = collect((array) ($after['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
|
||||
|
||||
foreach ($new->diffKeys($old) as $variant) {
|
||||
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ neu';
|
||||
}
|
||||
|
||||
foreach ($old->diffKeys($new) as $variant) {
|
||||
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ entfällt';
|
||||
}
|
||||
|
||||
foreach ($new->intersectByKeys($old) as $key => $variant) {
|
||||
if (($variant['name'] ?? '') !== ($old[$key]['name'] ?? '')) {
|
||||
$lines[] = 'Variante „'.($old[$key]['name'] ?? '').'“ heißt jetzt „'.($variant['name'] ?? '').'“';
|
||||
}
|
||||
|
||||
if (trim((string) ($variant['description'] ?? '')) !== trim((string) ($old[$key]['description'] ?? ''))
|
||||
|| trim((string) ($variant['execution_changes'] ?? '')) !== trim((string) ($old[$key]['execution_changes'] ?? ''))) {
|
||||
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ geändert';
|
||||
}
|
||||
}
|
||||
|
||||
$common = $old->keys()->intersect($new->keys())->values()->all();
|
||||
|
||||
if ($common !== [] && $common !== $new->keys()->intersect($old->keys())->values()->all()) {
|
||||
$lines[] = 'Reihenfolge der Varianten geändert';
|
||||
}
|
||||
|
||||
if ($source?->composition !== null) {
|
||||
if (($before['title'] ?? '') !== ($after['title'] ?? '') && $source->composition->designation !== ($before['title'] ?? '')) {
|
||||
$lines[] = 'Der Titel wurde lokal geändert und bleibt unverändert';
|
||||
}
|
||||
|
||||
if (($before['summary'] ?? '') !== ($after['summary'] ?? '') && filled($source->composition->summary) && $source->composition->summary !== ($before['summary'] ?? '')) {
|
||||
$lines[] = 'Die Kurzbeschreibung wurde lokal geändert und bleibt unverändert';
|
||||
}
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lokal ergänzte Bestandteile, die einer Quellvariante zugeordnet sind, die die neue Quellfassung nicht mehr kennt.
|
||||
* Die Redaktion legt deren neue Zuordnung fest.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @return list<array{key: string, name: string, members: list<string>}>
|
||||
*/
|
||||
public function conflicts(ExerciseSource $source, array $document): array
|
||||
{
|
||||
$latest = $source->composition?->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
||||
|
||||
if ($latest === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$keep = array_merge(
|
||||
array_map(fn (array $variant): string => (string) ($variant['id'] ?? ''), array_filter((array) ($document['variants'] ?? []), 'is_array')),
|
||||
$latest->variants->where('origin', 'lokal')->pluck('key')->all(),
|
||||
);
|
||||
$open = [];
|
||||
|
||||
foreach ($latest->members->where('origin', 'lokal') as $member) {
|
||||
$key = $member->variant?->key;
|
||||
|
||||
if ($key !== null && ! in_array($key, $keep, true)) {
|
||||
$open[$key]['key'] = $key;
|
||||
$open[$key]['name'] = $member->variant->name;
|
||||
$open[$key]['members'][] = $member->role;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($open);
|
||||
}
|
||||
|
||||
/**
|
||||
* Texte und Felder, die lokal bearbeitet wurden: `keep_local` bleiben erhalten, bei `conflict` hat auch die Quelle
|
||||
* geändert und die Redaktion entscheidet.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @return list<array{key: string, label: string}>
|
||||
*/
|
||||
public function textDecisions(ExerciseSource $source, array $document, string $wanted): array
|
||||
{
|
||||
$previousSnapshot = $this->lastAdopted($source);
|
||||
|
||||
if ($previousSnapshot === null || $source->composition === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$previousSource = $previousSnapshot->payload;
|
||||
$result = [];
|
||||
|
||||
foreach ($this->plan($source, $document, $previousSource) as $item) {
|
||||
if ($item['kind'] === 'text' && $item['decision'] === $wanted) {
|
||||
$result[] = ['key' => $item['key'], 'label' => $item['label']];
|
||||
}
|
||||
}
|
||||
|
||||
$latest = $source->composition->versions()->orderByDesc('number')->first();
|
||||
|
||||
foreach (self::FIELDS as $field => [$column, $label]) {
|
||||
if ($latest !== null && $this->classifyField($latest->{$column}, $previousSource[$field] ?? null, $document[$field] ?? null) === $wanted) {
|
||||
$result[] = ['key' => $field, 'label' => $label];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Übernimmt genau den Stand, den die Redaktion in der Vorschau gesehen hat. Hat sich der Stand seither geändert oder
|
||||
* wurde die Quelle ausgeblendet, wird nichts übernommen. Identische bereits übernommene Stände ergeben keine Fassung.
|
||||
*
|
||||
* @param array<string, string> $reassign neue Zuordnung entfallener Quellvarianten: alter Schlüssel => neuer Schlüssel oder ''
|
||||
* @param array<string, string> $choices bei lokal und in der Quelle geänderten Angaben: Schlüssel => `lokal` oder `quelle`
|
||||
* @return array{status: string, message: string, version?: CompositionVersion}
|
||||
*/
|
||||
public function adoptPreviewed(ExerciseSource $source, int $previewedSnapshot, array $reassign = [], ?User $actor = null, array $choices = []): array
|
||||
{
|
||||
$source->refresh();
|
||||
$latest = $source->latestSnapshot();
|
||||
|
||||
if ($source->availability === ExerciseSource::WITHDRAWN) {
|
||||
return ['status' => 'ausgeschlossen', 'message' => 'Die Quelle stellt diese Übung nicht mehr bereit. Sie wird nicht übernommen.'];
|
||||
}
|
||||
|
||||
if ($latest === null || $latest->id !== $previewedSnapshot) {
|
||||
return ['status' => 'geaendert', 'message' => 'Der Quellstand hat sich seit der Vorschau geändert. Prüfe die aktualisierte Vorschau und bestätige den neuen Stand.'];
|
||||
}
|
||||
|
||||
if ($latest->adopted_version_id !== null) {
|
||||
return ['status' => 'unveraendert', 'message' => 'Dieser Stand ist bereits übernommen. Es entsteht keine weitere Fassung.', 'version' => $latest->adoptedVersion];
|
||||
}
|
||||
|
||||
try {
|
||||
$version = $this->adopt($latest, $actor, $reassign, $choices);
|
||||
} catch (DomainRuleException $exception) {
|
||||
return ['status' => 'fehler', 'message' => $exception->getMessage()];
|
||||
}
|
||||
|
||||
return ['status' => 'uebernommen', 'message' => 'Fassung '.$version->number.' ist lokal angelegt und unveränderlich.', 'version' => $version];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die bewusste Übernahme: aus dem Inhaltsstand wird eine neue, unveränderliche lokale Fassung. Wiederholt man sie,
|
||||
* entsteht keine zweite Fassung.
|
||||
*
|
||||
* Eine importierte Übung ist eine Übung wie jede andere und lässt sich bearbeiten. Lokal bearbeitete Texte und Felder
|
||||
* bleiben deshalb erhalten, solange die Quelle sie nicht ebenfalls geändert hat. Haben beide Seiten geändert, legt die
|
||||
* Redaktion fest, welcher Stand gilt (`$choices`). Lokale Ergänzungen bleiben erhalten; entfällt ihre Quellvariante,
|
||||
* legt die Redaktion die neue Zuordnung fest (`$reassign`).
|
||||
*
|
||||
* @param array<string, string> $reassign
|
||||
* @param array<string, string> $choices Schlüssel => `lokal` oder `quelle`
|
||||
*/
|
||||
public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null, array $reassign = [], array $choices = []): CompositionVersion
|
||||
{
|
||||
$snapshot->refresh();
|
||||
|
||||
if ($snapshot->adopted_version_id !== null) {
|
||||
return $snapshot->adoptedVersion;
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($snapshot, $actor, $reassign, $choices): CompositionVersion {
|
||||
$source = $snapshot->source;
|
||||
$document = $snapshot->payload;
|
||||
$content = app(ContentService::class);
|
||||
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
|
||||
$previousSnapshot = $this->lastAdopted($source);
|
||||
$previousSource = $previousSnapshot?->payload ?? [];
|
||||
$composition = $source->composition ?? $this->createComposition($title, (string) ($document['summary'] ?? ''));
|
||||
|
||||
if ($source->composition !== null && $previousSnapshot !== null) {
|
||||
$this->carryOverTexts($composition, $previousSource, $document);
|
||||
}
|
||||
|
||||
$previous = $composition->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
||||
$variants = [];
|
||||
$members = [];
|
||||
|
||||
foreach ($this->plan($source, $document, $previousSource) as $item) {
|
||||
if ($item['kind'] === 'variant') {
|
||||
$variants[] = $item['variant'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$latest = $item['latest'];
|
||||
$decision = $item['decision'];
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
$decision = ($choices[$item['key']] ?? null) === 'lokal' ? 'keep_local'
|
||||
: (($choices[$item['key']] ?? null) === 'quelle' ? 'source' : 'conflict');
|
||||
}
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
throw new DomainRuleException('„'.$item['label'].'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.');
|
||||
}
|
||||
|
||||
$keepLocal = $decision === 'keep_local' && $latest !== null;
|
||||
$target = $keepLocal ? $latest : $this->sectionVersion($source, $item['field'], $item['title'], $item['text'], $latest);
|
||||
$members[] = array_filter([
|
||||
'role' => $item['role'],
|
||||
'target' => $target,
|
||||
'variant' => $item['variant_key'],
|
||||
'origin' => $keepLocal || ($latest !== null && $latest->id === $target->id && $latest->change_note !== self::IMPORT_NOTE) ? 'lokal' : 'quelle',
|
||||
], fn ($value): bool => $value !== null);
|
||||
}
|
||||
|
||||
// Fassungsfelder: lokal geändert bleibt erhalten, solange die Quelle den Wert nicht ebenfalls geändert hat.
|
||||
$fields = [];
|
||||
|
||||
foreach (self::FIELDS as $field => [$column, $label]) {
|
||||
$value = $document[$field] ?? null;
|
||||
|
||||
if ($previous !== null && $previousSnapshot !== null) {
|
||||
$decision = $this->classifyField($previous->{$column}, $previousSource[$field] ?? null, $value);
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
$decision = ($choices[$field] ?? null) === 'lokal' ? 'keep_local' : (($choices[$field] ?? null) === 'quelle' ? 'source' : 'conflict');
|
||||
}
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
throw new DomainRuleException('„'.$label.'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.');
|
||||
}
|
||||
|
||||
$value = $decision === 'keep_local' ? $previous->{$column} : $value;
|
||||
}
|
||||
|
||||
$fields[$column] = $value;
|
||||
}
|
||||
|
||||
[$localMembers, $localVariants] = $this->localAdditions($previous, array_column($variants, 'key'), $reassign);
|
||||
$version = $content->publishComposition(
|
||||
$composition,
|
||||
[...$members, ...$localMembers],
|
||||
$actor,
|
||||
self::IMPORT_NOTE,
|
||||
[
|
||||
'learning_goal' => $fields['learning_goal'],
|
||||
'duration_minutes' => $fields['duration_minutes'],
|
||||
'duration_max' => $fields['duration_max'],
|
||||
'material_note' => $fields['material_note'],
|
||||
'source_snapshot_id' => $snapshot->id,
|
||||
],
|
||||
[...$variants, ...$localVariants],
|
||||
);
|
||||
|
||||
$snapshot->update(['adopted_version_id' => $version->id]);
|
||||
$source->update(['composition_id' => $composition->id]);
|
||||
|
||||
return $version;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Was die Übernahme aus dem Quellstand anlegen würde, mit der Entscheidung je Text: `source` (Quelltext gilt),
|
||||
* `keep_local` (lokal bearbeitet, die Quelle hat sich nicht geändert) oder `conflict` (beide haben geändert).
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @param array<string, mixed> $previousSource
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function plan(ExerciseSource $source, array $document, array $previousSource): array
|
||||
{
|
||||
$plan = [];
|
||||
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
|
||||
|
||||
foreach (self::SECTIONS as $field => $label) {
|
||||
$text = trim((string) ($document[$field] ?? ''));
|
||||
|
||||
if ($text !== '') {
|
||||
$plan[] = $this->textItem($source, $field, $label, $title.' · '.$label, $label, $text, null, $previousSource[$field] ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ((array) ($document['variants'] ?? []) as $variant) {
|
||||
$key = (string) ($variant['id'] ?? '');
|
||||
|
||||
if ($key === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = (string) ($variant['name'] ?? '') ?: 'Variante';
|
||||
$plan[] = [
|
||||
'kind' => 'variant',
|
||||
'variant' => ['key' => $key, 'name' => $name, 'description' => (string) ($variant['description'] ?? ''), 'origin' => 'quelle'],
|
||||
];
|
||||
$changes = trim((string) ($variant['execution_changes'] ?? ''));
|
||||
|
||||
if ($changes !== '') {
|
||||
$before = collect((array) ($previousSource['variants'] ?? []))->firstWhere('id', $key);
|
||||
$plan[] = $this->textItem(
|
||||
$source,
|
||||
'variant:'.$key,
|
||||
'Abweichung der Durchführung ('.$name.')',
|
||||
$title.' · '.$name.' · Abweichung',
|
||||
'Abweichung der Durchführung',
|
||||
$changes,
|
||||
$key,
|
||||
is_array($before) ? ($before['execution_changes'] ?? null) : null,
|
||||
'variant_'.$key,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $plan;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function textItem(ExerciseSource $source, string $field, string $label, string $title, string $role, string $text, ?string $variantKey, ?string $previousText, ?string $key = null): array
|
||||
{
|
||||
$element = ContentElement::query()->where('source_ref', 'shinkan:'.$source->source_id.':'.$field)->first();
|
||||
$latest = $element?->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
|
||||
|
||||
return [
|
||||
'kind' => 'text',
|
||||
'key' => $key ?? $field,
|
||||
'field' => $field,
|
||||
'label' => $label,
|
||||
'title' => $title,
|
||||
'role' => $role,
|
||||
'text' => $text,
|
||||
'variant_key' => $variantKey,
|
||||
'latest' => $latest,
|
||||
'decision' => $this->classifyText($latest, $text, $previousText),
|
||||
];
|
||||
}
|
||||
|
||||
private function classifyText(?ContentElementVersion $latest, string $text, ?string $previousText): string
|
||||
{
|
||||
if ($latest === null || trim((string) $latest->body) === $text || $latest->change_note === self::IMPORT_NOTE) {
|
||||
return 'source';
|
||||
}
|
||||
|
||||
return $previousText === null || trim($previousText) !== $text ? 'conflict' : 'keep_local';
|
||||
}
|
||||
|
||||
private function classifyField(mixed $local, mixed $previousSource, mixed $new): string
|
||||
{
|
||||
$plain = fn (mixed $value): string => $value === null ? '' : trim((string) $value);
|
||||
|
||||
if ($plain($local) === $plain($new) || $plain($local) === $plain($previousSource)) {
|
||||
return 'source';
|
||||
}
|
||||
|
||||
return $plain($previousSource) !== $plain($new) ? 'conflict' : 'keep_local';
|
||||
}
|
||||
|
||||
/**
|
||||
* Titel und Kurzbeschreibung gehören zur Übung und nicht zur Fassung. Sie folgen der Quelle, solange die Redaktion sie
|
||||
* nicht lokal geändert hat; ein lokal geänderter Wert bleibt.
|
||||
*
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
*/
|
||||
private function carryOverTexts(Composition $composition, array $before, array $after): void
|
||||
{
|
||||
if (trim((string) ($after['title'] ?? '')) !== '' && $composition->designation === ($before['title'] ?? null)) {
|
||||
$composition->designation = trim((string) $after['title']);
|
||||
}
|
||||
|
||||
if (array_key_exists('summary', $after) && ((string) $composition->summary === '' || $composition->summary === ($before['summary'] ?? null))) {
|
||||
$composition->summary = trim((string) $after['summary']) ?: null;
|
||||
}
|
||||
|
||||
$composition->save();
|
||||
}
|
||||
|
||||
private function lastAdopted(ExerciseSource $source): ?ExerciseSourceSnapshot
|
||||
{
|
||||
return $source->snapshots()->reorder()->whereNotNull('adopted_version_id')->orderByDesc('id')->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Was die Redaktion lokal ergänzt hat, bleibt bei einer neuen Quellfassung erhalten. Eine lokale Zuordnung zu einer
|
||||
* Quellvariante, die es nicht mehr gibt, braucht eine ausdrücklich festgelegte neue Zuordnung.
|
||||
*
|
||||
* @param list<string> $sourceVariantKeys
|
||||
* @param array<string, string> $reassign
|
||||
* @return array{0: list<array<string, mixed>>, 1: list<array<string, mixed>>}
|
||||
*/
|
||||
private function localAdditions(?CompositionVersion $previous, array $sourceVariantKeys, array $reassign): 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;
|
||||
|
||||
if ($variant !== null && ! in_array($variant, $known, true)) {
|
||||
if (! array_key_exists($variant, $reassign)) {
|
||||
throw new DomainRuleException('Die lokale Ergänzung „'.$member->role.'“ gehört zur Quellvariante „'.$member->variant->name.'“, die es nicht mehr gibt. Lege ihre neue Zuordnung fest.');
|
||||
}
|
||||
|
||||
$target = (string) $reassign[$variant];
|
||||
|
||||
if ($target !== '' && ! in_array($target, $known, true)) {
|
||||
throw new DomainRuleException('Die gewählte neue Zuordnung gibt es in der neuen Fassung nicht.');
|
||||
}
|
||||
|
||||
$variant = $target === '' ? null : $target;
|
||||
}
|
||||
|
||||
$members[] = [
|
||||
'role' => $member->role,
|
||||
'note' => $member->placement_note,
|
||||
'target' => $member->content_element_version_id !== null ? $member->contentElementVersion : $member->nestedCompositionVersion,
|
||||
'variant' => $variant,
|
||||
'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 sectionVersion(ExerciseSource $source, string $field, string $title, string $text, ?ContentElementVersion $latest): 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();
|
||||
}
|
||||
|
||||
return $latest !== null && trim((string) $latest->body) === $text
|
||||
? $latest
|
||||
: $content->publishElementVersion($element, $text, [], self::IMPORT_NOTE);
|
||||
}
|
||||
|
||||
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> $document
|
||||
*/
|
||||
private function duration(array $document): string
|
||||
{
|
||||
$min = $document['duration_min'] ?? null;
|
||||
$max = $document['duration_max'] ?? null;
|
||||
|
||||
return match (true) {
|
||||
$min !== null && $max !== null && $min !== $max => $min.' bis '.$max.' Minuten',
|
||||
$min !== null => $min.' Minuten',
|
||||
$max !== null => $max.' Minuten',
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $query
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function get(string $path, array $query = [], ?string $key = null): array
|
||||
{
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$response = Http::withToken((string) ($key ?? $connection->apiKey()))
|
||||
->acceptJson()
|
||||
->timeout(20)
|
||||
->get((string) $connection->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 match ($exception->response->status()) {
|
||||
401, 403 => 'Shinkan akzeptiert den Zugangsschlüssel nicht (Status '.$exception->response->status().').',
|
||||
404 => 'Der Katalog ist unter dieser Adresse nicht erreichbar oder die Distribution ist in Shinkan nicht aktiv (Status 404).',
|
||||
default => 'Die Quelle antwortete mit Status '.$exception->response->status().'.',
|
||||
};
|
||||
}
|
||||
|
||||
if ($exception instanceof DomainRuleException) {
|
||||
return $exception->getMessage();
|
||||
}
|
||||
|
||||
return $this->networkCause($exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* Benennt die Ursache eines Netzwerkfehlers, ohne Adresse, Pfad oder Schlüssel auszugeben. Genannt wird nur der
|
||||
* Servername, damit die Redaktion erkennt, ob die richtige Quelle gemeint ist.
|
||||
*/
|
||||
private function networkCause(Throwable $exception): string
|
||||
{
|
||||
$host = app(ShinkanConnection::class)->url();
|
||||
$host = $host === null ? 'der Quelle' : (string) (parse_url($host, PHP_URL_HOST) ?: 'der Quelle');
|
||||
preg_match('/cURL error (\d+)/', $exception->getMessage(), $match);
|
||||
$code = isset($match[1]) ? (int) $match[1] : null;
|
||||
|
||||
$cause = match (true) {
|
||||
$code === 6 => 'Der Servername konnte von diesem Server aus nicht aufgelöst werden (Namensauflösung, DNS).',
|
||||
$code === 7 => 'Der Server nimmt die Verbindung nicht an (abgelehnt, falscher Port oder Firewall).',
|
||||
$code === 28 => 'Die Verbindung hat die Zeit überschritten (ausgehende Verbindungen sind möglicherweise blockiert).',
|
||||
in_array($code, [35, 51, 58, 60, 77, 83], true) => 'Das Zertifikat oder die verschlüsselte Verbindung wird nicht akzeptiert.',
|
||||
$code === 56 || $code === 52 => 'Die Verbindung wurde unterbrochen.',
|
||||
$code !== null => 'Netzwerkfehler (cURL '.$code.').',
|
||||
default => 'Netzwerkfehler.',
|
||||
};
|
||||
|
||||
return 'Die Quelle '.$host.' ist von diesem Server aus nicht erreichbar. '.$cause;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Scope;
|
||||
|
||||
/**
|
||||
* Rückfallschutz: Dieser Code kennt nur die Kompositionsarten aus {@see CompositionKind}. Eine Komposition mit einem
|
||||
* Wert, den erst eine neuere Programmversion einführt, gilt hier als nicht vorhanden. Sie wird weder geladen (der
|
||||
* Enum-Zugriff würde sonst abstürzen) noch angezeigt, bearbeitet oder veröffentlicht. Eine neuere Programmversion
|
||||
* kennt den Wert und sieht die Zeile wieder.
|
||||
*/
|
||||
class SupportedKindScope implements Scope
|
||||
{
|
||||
public function apply(Builder $builder, Model $model): void
|
||||
{
|
||||
$builder->whereIn($model->qualifyColumn('kind'), CompositionKind::values());
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@
|
||||
* Redaktionsvorschau (Route editorial.card, nur für angemeldete Redaktion); öffentlich nie ausgegeben, weil es
|
||||
* keine Freigabe für die Website hat.
|
||||
* - missing: was für eine vollständige Karte fehlt, als Hinweis nur in der Redaktionsvorschau.
|
||||
* - tag: Schlüssel eines Material-Tags (App\Domain\Catalog\MaterialTag), nur wenn die Art eindeutig zuzuordnen ist;
|
||||
* sonst null, und die Karte zeigt die Art als Text wie bisher.
|
||||
* - texts: die zentralen Texte des Fachobjekts, aus denen die Karte einen wählen kann (teaser, summary, description).
|
||||
* summary bleibt der Text der Vorgabe („Automatisch“); texts wird nur gelesen, wenn die Redaktion einen wählt.
|
||||
*/
|
||||
@@ -39,6 +41,7 @@ public function __construct(
|
||||
public array $missing = [],
|
||||
public ?string $style = null,
|
||||
public array $texts = [],
|
||||
public ?string $tag = null,
|
||||
) {}
|
||||
|
||||
public function withText(?string $title, ?string $summary): self
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\MaterialTag;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
@@ -235,6 +236,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
missing: $missing,
|
||||
style: $film ? 'media' : 'material',
|
||||
texts: $texts,
|
||||
tag: MaterialTag::fromContent((string) $shown->output_class, $element->editorialContentKind?->slug)?->value,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Support;
|
||||
|
||||
/**
|
||||
* Zulässige Kleingrafiken des Brand-Kits als Auswahl im CMS (ADR-30: nur feste Werte, nie freie Dateinamen).
|
||||
*
|
||||
* Die Schlüssel sind Dateinamen aus resources/svg/brand/symbole/. Nicht angeboten werden die gelbe Unterstreichung
|
||||
* (eigene Einstellung „Pinselstrich“) und die Signalstrahlen (Markenakzent des Einstiegs). Eine Prüfung im Test stellt
|
||||
* sicher, dass jeder Schlüssel eine vorhandene Datei hat.
|
||||
*/
|
||||
final class HeadingAccent
|
||||
{
|
||||
/** @var array<string, string> */
|
||||
public const SYMBOLS = [
|
||||
'bildung' => 'Bildung',
|
||||
'buch' => 'Buch',
|
||||
'download' => 'Download',
|
||||
'filmklappe' => 'Filmklappe',
|
||||
'filmstreifen' => 'Filmstreifen',
|
||||
'gruppe' => 'Gruppe',
|
||||
'merkblatt' => 'Merkblatt',
|
||||
'muskelarm' => 'Starker Arm',
|
||||
'paket' => 'Paket',
|
||||
'pause-hand' => 'Pause (Hand)',
|
||||
'play' => 'Abspielen',
|
||||
'schutzschild' => 'Schutzschild',
|
||||
'sprechblase-fragezeichen' => 'Frage (Sprechblase)',
|
||||
'uebungsblatt' => 'Übungsblatt',
|
||||
];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const BRUSH = ['brush' => 'Gelber Pinselstrich unter der Überschrift'];
|
||||
|
||||
public const SYMBOL_LABEL = ['Symbol vor der Überschrift', 'Kleine Grafik aus dem Brand-Kit vor dem Text. Sie ist reine Zierde und wird von Hilfstechnik nicht vorgelesen. Vorgabe: kein Symbol.'];
|
||||
|
||||
public const BRUSH_LABEL = ['Pinselstrich', 'Gelbe Unterstreichung unter der Überschrift (freigegebenes Motiv aus dem Brand-Kit). Vorgabe: ohne.'];
|
||||
|
||||
/**
|
||||
* Gültiger Symbolname aus den Einstellungen eines Widgets oder null.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
public static function symbol(array $settings): ?string
|
||||
{
|
||||
$name = $settings['symbol'] ?? null;
|
||||
|
||||
return is_string($name) && array_key_exists($name, self::SYMBOLS) ? $name : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
public static function hasBrush(array $settings): bool
|
||||
{
|
||||
return ($settings['accent'] ?? null) === 'brush';
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\SafeUrl;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
@@ -90,6 +91,21 @@ public function dataFields(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return ['symbol' => HeadingAccent::SYMBOLS];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Aussehen' => ['symbol']];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return ['symbol' => HeadingAccent::SYMBOL_LABEL];
|
||||
}
|
||||
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
if (! SafeUrl::isSafe($data['url'] ?? null)) {
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* Merkmalszeile nach den Entwürfen des Brand-Kits (04_visuelle_entwuerfe): zwei bis vier Merkmale nebeneinander,
|
||||
* je mit Symbol, Kurztitel und einem Satz. Die Anzahl der Einträge bestimmt die Spaltenzahl; es gibt keine
|
||||
* zweite Einstellung dafür. Das Symbol stammt aus der festen Auswahl (HeadingAccent::SYMBOLS), nie aus einem
|
||||
* freien Dateinamen.
|
||||
*/
|
||||
class FeaturesWidget extends WidgetType
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'features';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Merkmalszeile';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Zwei bis vier Merkmale nebeneinander, je mit Symbol, Kurztitel und einem Satz.';
|
||||
}
|
||||
|
||||
public function supportedUnits(): array
|
||||
{
|
||||
return [2, 3, 4];
|
||||
}
|
||||
|
||||
public function narrowBehavior(): string
|
||||
{
|
||||
return 'Die Merkmale stehen nebeneinander, solange jedes mindestens 12 rem breit bleibt; darunter stehen sie untereinander.';
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'narrow' => 'ein Merkmal je Zeile',
|
||||
'wide' => 'so viele Merkmale nebeneinander, wie bei mindestens 12rem Breite passen',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-sparkles';
|
||||
}
|
||||
|
||||
public function schematic(): array
|
||||
{
|
||||
return [[3, 6, 14, 14, 'accent'], [23, 6, 14, 14, 'accent'], [43, 6, 14, 14, 'accent'], [3, 24, 14, 3, 'ink'], [23, 24, 14, 3, 'ink'], [43, 24, 14, 3, 'ink'], [3, 29, 14, 2, 'line'], [23, 29, 14, 2, 'line'], [43, 29, 14, 2, 'line']];
|
||||
}
|
||||
|
||||
public function dataRules(): array
|
||||
{
|
||||
return [
|
||||
'items' => ['required', 'array', 'min:2', 'max:4'],
|
||||
'items.*.symbol' => ['required', 'string', Rule::in(array_keys(HeadingAccent::SYMBOLS))],
|
||||
'items.*.title' => ['required', 'string', 'max:60'],
|
||||
'items.*.text' => ['nullable', 'string', 'max:200'],
|
||||
];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
{
|
||||
return [
|
||||
Repeater::make('items')
|
||||
->label('Merkmale')
|
||||
->schema([
|
||||
Select::make('symbol')->label('Symbol')->options(HeadingAccent::SYMBOLS)->required(),
|
||||
TextInput::make('title')->label('Kurztitel')->required()->maxLength(60),
|
||||
Textarea::make('text')->label('Satz')->rows(2)->maxLength(200),
|
||||
])
|
||||
->minItems(2)
|
||||
->maxItems(4)
|
||||
->reorderableWithButtons()
|
||||
->collapsible()
|
||||
->itemLabel(fn (array $state): ?string => $state['title'] ?? null)
|
||||
->addActionLabel('Merkmal hinzufügen')
|
||||
->helperText('Die Anzahl der Merkmale bestimmt die Spalten: zwei, drei oder vier.'),
|
||||
];
|
||||
}
|
||||
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
foreach ($data['items'] as $index => $item) {
|
||||
$data['items'][$index] = [
|
||||
'symbol' => $item['symbol'],
|
||||
'title' => $item['title'],
|
||||
'text' => filled($item['text'] ?? null) ? $item['text'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
return [$data, $refs];
|
||||
}
|
||||
|
||||
public function resolve(array $widget, RenderContext $context): array
|
||||
{
|
||||
$items = [];
|
||||
|
||||
foreach ($widget['data']['items'] ?? [] as $item) {
|
||||
if (! is_array($item) || ! filled($item['title'] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$items[] = [
|
||||
'symbol' => HeadingAccent::symbol(['symbol' => $item['symbol'] ?? null]),
|
||||
'title' => $item['title'],
|
||||
'text' => $item['text'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
return ['items' => $items];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
$titles = array_filter(array_map(fn ($item) => is_array($item) ? ($item['title'] ?? null) : null, $widget['data']['items'] ?? []));
|
||||
|
||||
return count($titles).' Merkmale: '.implode(', ', $titles);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
@@ -71,6 +72,27 @@ public function dataFields(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => HeadingAccent::SYMBOLS,
|
||||
'accent' => HeadingAccent::BRUSH,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Aussehen' => ['symbol', 'accent']];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => HeadingAccent::SYMBOL_LABEL,
|
||||
'accent' => HeadingAccent::BRUSH_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
return (string) ($widget['data']['heading'] ?? '');
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\HeroVideo;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
@@ -112,13 +113,14 @@ public function settings(): array
|
||||
return [
|
||||
'heading_level' => PremiumFields::HEADING_LEVELS,
|
||||
'accent' => ['underline' => 'Gelbe Unterstreichung', 'rays' => 'Unterstreichung und Signalstrahlen', 'none' => 'Ohne Akzent'],
|
||||
'symbol' => HeadingAccent::SYMBOLS,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['accent'],
|
||||
'Aussehen' => ['accent', 'symbol'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
@@ -128,6 +130,7 @@ public function settingLabels(): array
|
||||
return [
|
||||
'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.'],
|
||||
'symbol' => HeadingAccent::SYMBOL_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
@@ -114,13 +115,14 @@ public function settings(): array
|
||||
return [
|
||||
'surface' => ['cream' => 'Creme (Markenfläche)', 'clear' => 'Ohne eigene Fläche', 'navy' => 'Navy (dunkel)'],
|
||||
'heading_level' => PremiumFields::HEADING_LEVELS,
|
||||
'symbol' => HeadingAccent::SYMBOLS,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['surface'],
|
||||
'Aussehen' => ['surface', 'symbol'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
@@ -129,6 +131,7 @@ public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'],
|
||||
'symbol' => HeadingAccent::SYMBOL_LABEL,
|
||||
'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.'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Mail\OrderConfirmed;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
@@ -26,6 +27,7 @@ public function __construct(
|
||||
private readonly GrantIssuer $grants,
|
||||
private readonly OfferService $offers,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly PaymentJournal $journal,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -187,14 +189,16 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
$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
|
||||
* 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') - $order->lines()->sum('discount_cents'));
|
||||
|
||||
@@ -202,15 +206,17 @@ public function confirmProviderPayment(Order $order, string $provider, string $r
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* (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): Order
|
||||
public function confirmInvoicePayment(Order $order, string $reference, User $actor, string|CarbonInterface|null $receivedOn = null): Order
|
||||
{
|
||||
$order->refresh();
|
||||
|
||||
@@ -218,10 +224,12 @@ public function confirmInvoicePayment(Order $order, string $reference, User $act
|
||||
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
|
||||
}
|
||||
|
||||
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor);
|
||||
$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 = null): Order
|
||||
private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy, CarbonInterface $occurredAt, bool $live, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$reference = trim($reference);
|
||||
|
||||
@@ -230,7 +238,7 @@ private function settle(Order $order, string $provider, string $reference, ?User
|
||||
}
|
||||
|
||||
$paidNow = false;
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, &$paidNow): Order {
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, $occurredAt, $live, $paymentIntent, &$paidNow): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status === 'bezahlt') {
|
||||
@@ -242,10 +250,14 @@ private function settle(Order $order, string $provider, string $reference, ?User
|
||||
}
|
||||
|
||||
// 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' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id],
|
||||
array_filter(
|
||||
['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id, 'provider_payment_ref' => $paymentIntent],
|
||||
fn (mixed $value): bool => $value !== null,
|
||||
),
|
||||
);
|
||||
$this->journal->recordPayment($order, $payment, $occurredAt, $confirmedBy, $live);
|
||||
$order->status = 'bezahlt';
|
||||
$order->save();
|
||||
$paidNow = true;
|
||||
@@ -295,8 +307,11 @@ public function failTestPayment(Order $order, string $reference): Order
|
||||
* (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Bundles sind Rückgabeeinheiten; freiwillige
|
||||
* Teilerstattungen gibt es zum Start nicht. Bei einer Zahlung über Stripe wird die Rückzahlung zuerst bei Stripe
|
||||
* veranlasst; erst wenn Stripe sie annimmt, werden Rechte entzogen. Wirkt sie dort nicht, bleibt alles unverändert.
|
||||
* Jede Erstattung wird im Zahlungsjournal gegengebucht, in derselben Transaktion: Bei Stripe mit Rückzahlungs-ID
|
||||
* und Zeitpunkt von Stripe, sonst (Überweisung, Testzahlung) mit `$refundedOn` (Tag der Rückzahlung, ohne Angabe
|
||||
* jetzt) und `$reference` (Überweisungsreferenz o. ä., sonst eine feste Kennung der Bestellung).
|
||||
*/
|
||||
public function refund(Order $order, string $reason, ?StripeGateway $stripe = null): 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);
|
||||
|
||||
@@ -306,12 +321,15 @@ public function refund(Order $order, string $reason, ?StripeGateway $stripe = nu
|
||||
|
||||
$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) {
|
||||
($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
|
||||
$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): Order {
|
||||
return DB::transaction(function () use ($order, $reason, $actor, $manualAt, $reference, $booking): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status !== 'bezahlt') {
|
||||
@@ -334,6 +352,16 @@ public function refund(Order $order, string $reason, ?StripeGateway $stripe = nu
|
||||
}
|
||||
}
|
||||
|
||||
$payment = $order->payments()->where('status', 'bestaetigt')->latest('id')->first();
|
||||
$this->journal->recordRefund(
|
||||
$order,
|
||||
$payment,
|
||||
$booking['at'] ?? $manualAt,
|
||||
$actor,
|
||||
$reason,
|
||||
$booking['reference'] ?? (filled($reference) ? 'erstattung-'.trim((string) $reference) : 'erstattung-bestellung-'.$order->id),
|
||||
$booking['status'] ?? null,
|
||||
);
|
||||
$order->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']);
|
||||
$order->status = 'erstattet';
|
||||
$order->save();
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use LogicException;
|
||||
|
||||
/**
|
||||
* Eine Geldbewegung im Zahlungsjournal (Zahlungseingang oder Erstattung). Unveränderlich: Eine Zeile wird nur
|
||||
* angelegt, nie geändert oder gelöscht. Eine Korrektur ist eine neue Gegenbuchung. Beträge sind vorzeichenbehaftet
|
||||
* (Eingang positiv, Erstattung negativ), sodass die Summe den Saldo ergibt.
|
||||
*/
|
||||
class LedgerEntry extends Model
|
||||
{
|
||||
public const KIND_PAYMENT = 'eingang';
|
||||
|
||||
public const KIND_REFUND = 'erstattung';
|
||||
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
protected $table = 'payment_ledger';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'occurred_at' => 'datetime',
|
||||
'amount_cents' => 'integer',
|
||||
'live' => 'boolean',
|
||||
'derived' => 'boolean',
|
||||
'payer' => 'array',
|
||||
'order_snapshot' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::updating(function (): never {
|
||||
throw new LogicException('Das Zahlungsjournal ist unveränderlich. Korrekturen sind neue Gegenbuchungen.');
|
||||
});
|
||||
static::deleting(function (): never {
|
||||
throw new LogicException('Das Zahlungsjournal ist unveränderlich. Einträge werden nie gelöscht.');
|
||||
});
|
||||
}
|
||||
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
|
||||
public function isRefund(): bool
|
||||
{
|
||||
return $this->kind === self::KIND_REFUND;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Zahlungsjournal: schreibt und liest die unveränderlichen Geldbewegungen (LedgerEntry). Geschrieben wird nur aus
|
||||
* derselben Transaktion, die die Bestellung auf „bezahlt“ oder „erstattet“ setzt, sodass beides nie auseinanderläuft.
|
||||
* Zeiträume und Datumsangaben gelten in deutscher Zeit (Geschäftsjahr, Monats- und Quartalsgrenzen); gespeichert wird
|
||||
* in UTC. Der Nachweis ist an die Grundsätze der ordnungsmäßigen Buchführung angelehnt (unveränderbar, nachvollziehbar);
|
||||
* ob er den Anforderungen der Steuerberatung genügt, ist dort zu bestätigen.
|
||||
*/
|
||||
final class PaymentJournal
|
||||
{
|
||||
public const TIMEZONE = 'Europe/Berlin';
|
||||
|
||||
/** Höchstzahl der in der Verwaltung gezeigten Zeilen; der Export enthält immer alle des Zeitraums. */
|
||||
public const DISPLAY_LIMIT = 500;
|
||||
|
||||
/**
|
||||
* Zahlungseingang. Wiederholte Meldung derselben Zahlung legt keine zweite Zeile an (Schlüssel: Art, Anbieter,
|
||||
* Referenz).
|
||||
*/
|
||||
public function recordPayment(Order $order, Payment $payment, CarbonInterface $occurredAt, ?User $actor, bool $live): LedgerEntry
|
||||
{
|
||||
return LedgerEntry::query()->firstOrCreate(
|
||||
['kind' => LedgerEntry::KIND_PAYMENT, 'provider' => $payment->provider, 'provider_reference' => $payment->provider_reference],
|
||||
[
|
||||
'order_id' => $order->id,
|
||||
'payment_id' => $payment->id,
|
||||
'occurred_at' => $this->utc($occurredAt),
|
||||
'amount_cents' => $order->payable(),
|
||||
'currency' => (string) ($order->currency ?? 'EUR'),
|
||||
'provider_payment_ref' => $payment->provider_payment_ref,
|
||||
'live' => $live,
|
||||
'actor_id' => $actor?->id,
|
||||
'actor_name' => $actor?->name,
|
||||
'payer' => $this->payer($order),
|
||||
'order_snapshot' => $this->orderSnapshot($order),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstattung: eine Gegenbuchung in Höhe des Zahlbetrags. Das Echt-Kennzeichen folgt dem Zahlungseingang der
|
||||
* Bestellung. `$reference` ist bei Stripe die Rückzahlungs-ID (re_...), sonst eine Referenz der Rückzahlung.
|
||||
*/
|
||||
public function recordRefund(Order $order, ?Payment $payment, CarbonInterface $occurredAt, ?User $actor, string $reason, string $reference, ?string $providerStatus = null): LedgerEntry
|
||||
{
|
||||
$original = LedgerEntry::query()->where('order_id', $order->id)->where('kind', LedgerEntry::KIND_PAYMENT)->orderBy('id')->first();
|
||||
|
||||
return LedgerEntry::query()->firstOrCreate(
|
||||
['kind' => LedgerEntry::KIND_REFUND, 'provider' => $payment?->provider ?? $original?->provider ?? 'unbekannt', 'provider_reference' => $reference],
|
||||
[
|
||||
'order_id' => $order->id,
|
||||
'payment_id' => $payment?->id,
|
||||
'occurred_at' => $this->utc($occurredAt),
|
||||
'amount_cents' => -$order->payable(),
|
||||
'currency' => (string) ($order->currency ?? 'EUR'),
|
||||
'provider_payment_ref' => $payment?->provider_payment_ref,
|
||||
'provider_status' => $providerStatus,
|
||||
'live' => $original?->live ?? false,
|
||||
'actor_id' => $actor?->id,
|
||||
'actor_name' => $actor?->name,
|
||||
'reason' => $reason,
|
||||
'payer' => $original?->payer ?? $this->payer($order),
|
||||
'order_snapshot' => $original?->order_snapshot ?? $this->orderSnapshot($order),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Datum ohne Uhrzeit (Zahlungseingang auf dem Konto): Beginn dieses Tages in deutscher Zeit. Nicht in der
|
||||
* Zukunft; `$notBefore` ist der früheste zulässige Tag (Bestelldatum).
|
||||
*/
|
||||
public static function dayOf(string|CarbonInterface $date, ?CarbonInterface $notBefore = null): CarbonImmutable
|
||||
{
|
||||
$day = CarbonImmutable::parse($date instanceof CarbonInterface ? $date->format('Y-m-d') : $date, self::TIMEZONE)->startOfDay();
|
||||
|
||||
if ($day->greaterThan(CarbonImmutable::now(self::TIMEZONE)->endOfDay())) {
|
||||
throw new DomainRuleException('Das Datum darf nicht in der Zukunft liegen.');
|
||||
}
|
||||
|
||||
if ($notBefore !== null && $day->lessThan(CarbonImmutable::instance($notBefore)->setTimezone(self::TIMEZONE)->startOfDay())) {
|
||||
throw new DomainRuleException('Das Datum liegt vor dem Bestelldatum.');
|
||||
}
|
||||
|
||||
return $day;
|
||||
}
|
||||
|
||||
/**
|
||||
* Von und bis (einschließlich) eines Zeitraums in UTC.
|
||||
*
|
||||
* @param 'monat'|'quartal'|'jahr' $mode
|
||||
* @return array{0: CarbonImmutable, 1: CarbonImmutable}
|
||||
*/
|
||||
public static function range(string $mode, int $year, int $index): array
|
||||
{
|
||||
$from = CarbonImmutable::create($year, 1, 1, 0, 0, 0, self::TIMEZONE);
|
||||
|
||||
$from = match ($mode) {
|
||||
'monat' => $from->setMonth(max(1, min(12, $index)))->startOfMonth(),
|
||||
'quartal' => $from->setMonth((max(1, min(4, $index)) - 1) * 3 + 1)->startOfMonth(),
|
||||
default => $from->startOfYear(),
|
||||
};
|
||||
$to = match ($mode) {
|
||||
'monat' => $from->endOfMonth(),
|
||||
'quartal' => $from->addMonths(2)->endOfMonth(),
|
||||
default => $from->endOfYear(),
|
||||
};
|
||||
|
||||
return [$from->setTimezone('UTC'), $to->setTimezone('UTC')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param 'alle'|'eingang'|'erstattung' $kind
|
||||
* @param 'alle'|'stripe'|'ueberweisung'|'test' $provider
|
||||
* @param 'echt'|'test'|'alle' $operation
|
||||
* @return Collection<int, LedgerEntry>
|
||||
*/
|
||||
public function entries(CarbonInterface $from, CarbonInterface $to, string $kind = 'alle', string $provider = 'alle', string $operation = 'echt', ?int $offerId = null): Collection
|
||||
{
|
||||
return LedgerEntry::query()
|
||||
->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])
|
||||
->when($offerId !== null, fn ($query) => $query->whereHas('order.lines.offerVersion', fn ($versions) => $versions->where('offer_id', $offerId)))
|
||||
->when($kind !== 'alle', fn ($query) => $query->where('kind', $kind))
|
||||
->when($provider !== 'alle', fn ($query) => $query->where('provider', $provider))
|
||||
->when($operation === 'echt', fn ($query) => $query->where('live', true))
|
||||
->when($operation === 'test', fn ($query) => $query->where('live', false))
|
||||
->orderBy('occurred_at')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Anteil eines Angebots an jeder Bewegung: die Positionen dieses Angebots in der Bestellung (Preis nach Rabatt,
|
||||
* wie bei der Bestellung festgehalten), bei einer Erstattung negativ. Eine Buchung trägt den Betrag der ganzen
|
||||
* Bestellung; ohne diese Aufteilung würde eine Bestellung mit mehreren Angeboten den Umsatz des einzelnen
|
||||
* Angebots überzeichnen. Es gibt nur Vollerstattungen, deshalb ist der Anteil der Erstattung der gespiegelte.
|
||||
*
|
||||
* @param Collection<int, LedgerEntry> $entries
|
||||
* @return array<int, int> Buchungsnummer => Anteil in Cent (mit Vorzeichen der Buchung)
|
||||
*/
|
||||
public function shares(Collection $entries, int $offerId): array
|
||||
{
|
||||
$perOrder = OrderLine::query()
|
||||
->whereIn('order_id', $entries->pluck('order_id')->unique()->all())
|
||||
->whereHas('offerVersion', fn ($versions) => $versions->where('offer_id', $offerId))
|
||||
->get()
|
||||
->groupBy('order_id')
|
||||
->map(fn (Collection $lines): int => (int) $lines->sum(fn (OrderLine $line): int => $line->payable()));
|
||||
$shares = [];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$share = (int) ($perOrder[$entry->order_id] ?? 0);
|
||||
$shares[$entry->id] = $entry->isRefund() ? -$share : $share;
|
||||
}
|
||||
|
||||
return $shares;
|
||||
}
|
||||
|
||||
/**
|
||||
* Anzahl der Bewegungen außerhalb des Betriebsfilters, damit ein leerer Echtbetrieb nicht wie „keine Daten“ wirkt.
|
||||
*/
|
||||
public function countByOperation(CarbonInterface $from, CarbonInterface $to): array
|
||||
{
|
||||
$rows = LedgerEntry::query()->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])->get(['live']);
|
||||
|
||||
return ['echt' => $rows->where('live', true)->count(), 'test' => $rows->where('live', false)->count()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, LedgerEntry> $entries
|
||||
* @param array<int, int>|null $shares Anteile eines Angebots (shares), sonst die ganzen Buchungen
|
||||
* @return array{eingang: int, erstattung: int, saldo: int, anzahl_eingang: int, anzahl_erstattung: int}
|
||||
*/
|
||||
public static function totals(Collection $entries, ?array $shares = null): array
|
||||
{
|
||||
$in = $entries->where('kind', LedgerEntry::KIND_PAYMENT);
|
||||
$out = $entries->where('kind', LedgerEntry::KIND_REFUND);
|
||||
$amount = fn (LedgerEntry $entry): int => $shares === null ? $entry->amount_cents : (int) ($shares[$entry->id] ?? 0);
|
||||
|
||||
return [
|
||||
'eingang' => (int) $in->sum($amount),
|
||||
'erstattung' => (int) abs($out->sum($amount)),
|
||||
'saldo' => (int) $entries->sum($amount),
|
||||
'anzahl_eingang' => $in->count(),
|
||||
'anzahl_erstattung' => $out->count(),
|
||||
];
|
||||
}
|
||||
|
||||
public static function providerLabel(string $provider): string
|
||||
{
|
||||
return match ($provider) {
|
||||
'stripe' => 'Stripe',
|
||||
'ueberweisung' => 'Überweisung',
|
||||
'test' => 'Testzahlung',
|
||||
default => $provider,
|
||||
};
|
||||
}
|
||||
|
||||
public static function local(CarbonInterface $moment): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::instance($moment)->setTimezone(self::TIMEZONE);
|
||||
}
|
||||
|
||||
/** Hat die Bewegung eine belegte Uhrzeit? Datumsbuchungen (Überweisung) beginnen um 00:00 deutscher Zeit. */
|
||||
public static function hasTime(LedgerEntry $entry): bool
|
||||
{
|
||||
return self::local($entry->occurred_at)->format('H:i:s') !== '00:00:00';
|
||||
}
|
||||
|
||||
/**
|
||||
* Semikolon-getrennt, Dezimalkomma, UTF-8 mit BOM: öffnet in Excel und bei der Steuerberatung ohne Umweg.
|
||||
*
|
||||
* @param Collection<int, LedgerEntry> $entries
|
||||
* @param array<int, int>|null $shares Mit Angebotsfilter eine zusätzliche Spalte „Anteil des Angebots“
|
||||
*/
|
||||
public static function csv(Collection $entries, ?array $shares = null): string
|
||||
{
|
||||
$header = [
|
||||
'Buchungsnummer', 'Datum', 'Uhrzeit', 'Art', 'Betrag EUR', 'Währung', 'Bestellung', 'Zahlungsweg', 'Betrieb', 'Herkunft',
|
||||
'Referenz', 'Zahlungsvorgang', 'Status beim Anbieter', 'Lizenzinhaber', 'Rechnungsempfänger', 'Zusatz', 'Straße', 'PLZ', 'Ort', 'Land',
|
||||
'Besteller', 'Zwischensumme EUR', 'Rabatt EUR', 'Rabattcode', 'Positionen', 'Begründung', 'Gebucht von', 'Gebucht am',
|
||||
...($shares === null ? [] : ['Anteil des Angebots EUR']),
|
||||
];
|
||||
$rows = [$header];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$local = self::local($entry->occurred_at);
|
||||
$payer = (array) $entry->payer;
|
||||
$billing = (array) ($payer['billing'] ?? []);
|
||||
$snapshot = (array) $entry->order_snapshot;
|
||||
$lines = collect($snapshot['lines'] ?? [])->map(fn (array $line): string => ($line['name'] ?? '').' '.self::decimal((int) ($line['price_cents'] ?? 0) - (int) ($line['discount_cents'] ?? 0)))->implode(' | ');
|
||||
|
||||
$rows[] = [
|
||||
$entry->id,
|
||||
$local->format('d.m.Y'),
|
||||
self::hasTime($entry) ? $local->format('H:i:s') : '',
|
||||
$entry->isRefund() ? 'Erstattung' : 'Zahlungseingang',
|
||||
self::decimal($entry->amount_cents),
|
||||
$entry->currency,
|
||||
$entry->order_id,
|
||||
self::providerLabel($entry->provider),
|
||||
$entry->live ? 'echt' : 'Test',
|
||||
$entry->derived ? 'nachgetragen (Datum abgeleitet)' : 'belegt',
|
||||
$entry->provider_reference,
|
||||
$entry->provider_payment_ref,
|
||||
$entry->provider_status,
|
||||
$payer['holder'] ?? null,
|
||||
$billing['recipient'] ?? null,
|
||||
$billing['line2'] ?? null,
|
||||
$billing['street'] ?? null,
|
||||
$billing['postal_code'] ?? null,
|
||||
$billing['city'] ?? null,
|
||||
$billing['country'] ?? null,
|
||||
$payer['buyer'] ?? null,
|
||||
self::decimal((int) ($snapshot['subtotal_cents'] ?? 0)),
|
||||
self::decimal((int) ($snapshot['discount_cents'] ?? 0)),
|
||||
$snapshot['discount_code'] ?? null,
|
||||
$lines,
|
||||
$entry->reason,
|
||||
$entry->actor_name,
|
||||
self::local($entry->created_at)->format('d.m.Y H:i:s'),
|
||||
...($shares === null ? [] : [self::decimal((int) ($shares[$entry->id] ?? 0))]),
|
||||
];
|
||||
}
|
||||
|
||||
$handle = fopen('php://temp', 'r+');
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($handle, array_map(self::cell(...), $row), ';', '"', '\\', "\r\n");
|
||||
}
|
||||
|
||||
rewind($handle);
|
||||
$csv = (string) stream_get_contents($handle);
|
||||
fclose($handle);
|
||||
|
||||
return "\xEF\xBB\xBF".$csv;
|
||||
}
|
||||
|
||||
public static function decimal(int $cents): string
|
||||
{
|
||||
return number_format($cents / 100, 2, ',', '');
|
||||
}
|
||||
|
||||
/** Verhindert, dass ein Zellinhalt in der Tabellenkalkulation als Formel ausgeführt wird. */
|
||||
private static function cell(mixed $value): string
|
||||
{
|
||||
$text = (string) $value;
|
||||
|
||||
if ($text !== '' && preg_match('/^[=+\-@\t\r]/', $text) === 1 && preg_match('/^-?\d+(,\d+)?$/', $text) !== 1) {
|
||||
return "'".$text;
|
||||
}
|
||||
|
||||
return $text;
|
||||
}
|
||||
|
||||
private function utc(CarbonInterface $moment): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::instance($moment)->setTimezone('UTC');
|
||||
}
|
||||
|
||||
/**
|
||||
* Zahler zum Zeitpunkt der Bewegung. Spätere Änderungen an Profil oder Rechnungsadresse ändern sie nicht.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function payer(Order $order): array
|
||||
{
|
||||
$order->loadMissing('user', 'party.billingAddress');
|
||||
$address = $order->party?->billingAddress;
|
||||
|
||||
return [
|
||||
'holder' => $order->party?->display_name,
|
||||
'holder_kind' => $order->holder_kind,
|
||||
'buyer' => $order->user?->name,
|
||||
'buyer_email' => $order->user?->email,
|
||||
'billing' => $address === null ? null : [
|
||||
'recipient' => $address->recipient,
|
||||
'line2' => $address->line2,
|
||||
'street' => $address->street,
|
||||
'postal_code' => $address->postal_code,
|
||||
'city' => $address->city,
|
||||
'country' => $address->country,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function orderSnapshot(Order $order): array
|
||||
{
|
||||
$order->loadMissing('lines');
|
||||
|
||||
return [
|
||||
'subtotal_cents' => $order->subtotal(),
|
||||
'discount_cents' => (int) $order->discount_cents,
|
||||
'discount_code' => $order->discount_snapshot['code'] ?? null,
|
||||
'lines' => $order->lines->map(fn (OrderLine $line): array => [
|
||||
'name' => $line->offer_name,
|
||||
'price_cents' => (int) $line->price_cents,
|
||||
'discount_cents' => (int) $line->discount_cents,
|
||||
])->values()->all(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
@@ -121,9 +122,12 @@ public function assertAllowed(): void
|
||||
/**
|
||||
* 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).
|
||||
* 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): void
|
||||
public function refund(Order $order, Payment $payment, string $reason): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$intent = (string) $payment->provider_payment_ref;
|
||||
@@ -148,8 +152,25 @@ public function refund(Order $order, Payment $payment, string $reason): void
|
||||
]);
|
||||
|
||||
$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,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,6 +16,7 @@ class MediaDelivery extends Model
|
||||
'copy_id',
|
||||
'checksum',
|
||||
'marking',
|
||||
'composition_version_id',
|
||||
'delivered_at',
|
||||
];
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ public function write(
|
||||
string $format,
|
||||
?string $checksum,
|
||||
string $marking,
|
||||
?string $copyId = null,
|
||||
?int $compositionVersionId = null,
|
||||
): MediaDelivery {
|
||||
return MediaDelivery::query()->create([
|
||||
'grant_id' => $grant->id,
|
||||
@@ -27,10 +29,16 @@ public function write(
|
||||
'content_element_version_id' => $version->id,
|
||||
'action' => $action,
|
||||
'format' => $format,
|
||||
'copy_id' => 'LK-'.strtoupper(bin2hex(random_bytes(6))),
|
||||
'copy_id' => $copyId ?? self::newCopyId(),
|
||||
'composition_version_id' => $compositionVersionId,
|
||||
'checksum' => $checksum,
|
||||
'marking' => $marking,
|
||||
'delivered_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function newCopyId(): string
|
||||
{
|
||||
return 'LK-'.strtoupper(bin2hex(random_bytes(6)));
|
||||
}
|
||||
}
|
||||
@@ -52,11 +52,11 @@ class RedaktionelleStammdaten extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Stammdaten';
|
||||
|
||||
protected static ?string $navigationLabel = 'Redaktionelle Stammdaten';
|
||||
|
||||
protected static ?int $navigationSort = 6;
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
protected static ?string $slug = 'stammdaten';
|
||||
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\ExerciseImportRun;
|
||||
use App\Domain\Catalog\ExerciseSource;
|
||||
use App\Domain\Catalog\ShinkanConnection;
|
||||
use App\Domain\Catalog\ShinkanImport;
|
||||
use App\Domain\Identity\StaffRole;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Übungen aus Shinkan übernehmen: abrufen, suchen und nach Zustand filtern, markieren, vor der Übernahme prüfen und
|
||||
* ausdrücklich bestätigen. Abrufen verändert nur den Quellenstand; erst die Bestätigung legt lokale Fassungen an, und
|
||||
* erst eine Produktveröffentlichung setzt sie ein.
|
||||
*
|
||||
* Den Zugangsschlüssel hinterlegen und ersetzen nur Katalog- und Systemverwalter. Die Redaktion sieht den Zustand der
|
||||
* Anbindung und arbeitet mit ihr; der Schlüssel wird nie an den Browser zurückgegeben.
|
||||
*/
|
||||
class Uebernahme extends Page
|
||||
{
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
|
||||
protected static ?string $navigationLabel = 'Übungen aus Shinkan';
|
||||
|
||||
protected static ?int $navigationSort = 6;
|
||||
|
||||
protected static ?string $slug = 'uebernahme';
|
||||
|
||||
protected static ?string $title = 'Übungen aus Shinkan übernehmen';
|
||||
|
||||
protected string $view = 'filament.pages.uebernahme';
|
||||
|
||||
public string $apiKey = '';
|
||||
|
||||
public string $search = '';
|
||||
|
||||
public string $statusFilter = 'alle';
|
||||
|
||||
/** @var list<int|string> Markierte Quellübungen (Kennung in der Datenbank) */
|
||||
public array $selected = [];
|
||||
|
||||
/** auswahl | vorschau | ergebnis */
|
||||
public string $step = 'auswahl';
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
public array $preview = [];
|
||||
|
||||
/** @var array<int|string, array<string, string>> Quellübung => (entfallene Quellvariante => neue Zuordnung) */
|
||||
public array $reassign = [];
|
||||
|
||||
/** @var array<int|string, array<string, string>> Quellübung => (Text oder Feld => `lokal` oder `quelle`) */
|
||||
public array $textChoice = [];
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
public array $results = [];
|
||||
|
||||
public string $feedback = '';
|
||||
|
||||
public bool $feedbackError = false;
|
||||
|
||||
/**
|
||||
* Die Übernahme ist ein Weg im Übungsbestand („Aus Shinkan übernehmen“) und kein eigener Einstieg. Nur wer die
|
||||
* Anbindung pflegen darf, aber den Übungsbestand nicht sieht, bekommt den Eintrag in der Navigation.
|
||||
*/
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
return static::canConfigure() && ! ContentElementResource::editor();
|
||||
}
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return ContentElementResource::editor() || static::canConfigure();
|
||||
}
|
||||
|
||||
/** Den Schlüssel ändern dürfen nur Katalogverwalter und Systemverwalter. */
|
||||
public static function canConfigure(): bool
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
return $user instanceof User
|
||||
&& ($user->hasStaffRole(StaffRole::Katalogverwalter) || $user->hasStaffRole(StaffRole::Systemverwalter));
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
public function saveKey(): void
|
||||
{
|
||||
abort_unless(static::canConfigure(), 403);
|
||||
|
||||
try {
|
||||
app(ShinkanConnection::class)->saveKey($this->apiKey, $this->actor());
|
||||
$this->say('Der Zugangsschlüssel ist gespeichert. Prüfe jetzt die Verbindung. Der Schlüssel wird nie wieder angezeigt.');
|
||||
} catch (DomainRuleException $exception) {
|
||||
$this->say($exception->getMessage(), true);
|
||||
}
|
||||
|
||||
$this->apiKey = '';
|
||||
}
|
||||
|
||||
public function removeKey(): void
|
||||
{
|
||||
abort_unless(static::canConfigure(), 403);
|
||||
|
||||
app(ShinkanConnection::class)->forgetKey($this->actor());
|
||||
$this->say('Der in der Verwaltung hinterlegte Zugangsschlüssel ist entfernt. Ein Schlüssel aus der Umgebung des Servers bleibt davon unberührt.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die Verbindung. Ein eingetragener, noch nicht gespeicherter Schlüssel wird mitgeprüft (nur Verwalter).
|
||||
*/
|
||||
public function check(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$candidate = static::canConfigure() ? $this->apiKey : '';
|
||||
$result = app(ShinkanImport::class)->check($candidate);
|
||||
$this->apiKey = '';
|
||||
$this->say($result['message'], ! $result['ok']);
|
||||
}
|
||||
|
||||
public function fetch(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$run = app(ShinkanImport::class)->fetch();
|
||||
$this->say(
|
||||
$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,
|
||||
$run->status !== 'ok',
|
||||
);
|
||||
}
|
||||
|
||||
public function review(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$ids = array_values(array_unique(array_map('intval', $this->selected)));
|
||||
|
||||
if ($ids === []) {
|
||||
$this->say('Markiere mindestens eine Übung.', true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->buildPreview($ids);
|
||||
$this->step = 'vorschau';
|
||||
$this->say('');
|
||||
}
|
||||
|
||||
public function backToSelection(): void
|
||||
{
|
||||
$this->step = 'auswahl';
|
||||
$this->preview = [];
|
||||
$this->say('');
|
||||
}
|
||||
|
||||
public function confirm(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$import = app(ShinkanImport::class);
|
||||
$changed = [];
|
||||
$open = [];
|
||||
|
||||
foreach ($this->preview as $entry) {
|
||||
$source = ExerciseSource::query()->find($entry['source']);
|
||||
|
||||
if ($source === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$latest = $source->latestSnapshot();
|
||||
|
||||
if (($source->availability === ExerciseSource::WITHDRAWN) !== (bool) $entry['excluded'] || $latest?->id !== $entry['snapshot']) {
|
||||
$changed[] = $entry['title'];
|
||||
}
|
||||
|
||||
foreach ($entry['text_conflicts'] as $conflict) {
|
||||
if (! in_array($this->textChoice[$entry['source']][$conflict['key']] ?? 'offen', ['lokal', 'quelle'], true)) {
|
||||
$open[] = $entry['title'].': '.$conflict['label'];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($entry['conflicts'] as $conflict) {
|
||||
if (! isset($this->reassign[$entry['source']][$conflict['key']]) || $this->reassign[$entry['source']][$conflict['key']] === 'offen') {
|
||||
$open[] = $entry['title'].': '.implode(', ', $conflict['members']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($changed !== []) {
|
||||
$this->buildPreview(array_map(fn (array $entry): int => (int) $entry['source'], $this->preview));
|
||||
$this->say('Der Quellstand hat sich seit der Vorschau geändert ('.implode(', ', $changed).'). Die Vorschau ist aktualisiert. Prüfe sie und bestätige den neuen Stand bewusst. Es wurde nichts übernommen.', true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($open !== []) {
|
||||
$this->say('Lege zuerst fest, was gilt: '.implode('; ', $open).'.', true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->results = [];
|
||||
|
||||
foreach ($this->preview as $entry) {
|
||||
$source = ExerciseSource::query()->findOrFail($entry['source']);
|
||||
$reassign = array_map(fn (string $value): string => $value === 'gemeinsam' ? '' : $value, $this->reassign[$entry['source']] ?? []);
|
||||
$result = $import->adoptPreviewed($source, (int) $entry['snapshot'], $reassign, $this->actor(), $this->textChoice[$entry['source']] ?? []);
|
||||
$source->refresh();
|
||||
$this->results[] = [
|
||||
'title' => $entry['title'],
|
||||
'status' => $result['status'],
|
||||
'message' => $result['message'],
|
||||
'url' => $source->composition === null ? null : PracticeResource::getUrl('edit', ['record' => $source->composition]),
|
||||
];
|
||||
}
|
||||
|
||||
$this->selected = [];
|
||||
$this->preview = [];
|
||||
$this->step = 'ergebnis';
|
||||
$this->say('');
|
||||
}
|
||||
|
||||
public function done(): void
|
||||
{
|
||||
$this->step = 'auswahl';
|
||||
$this->results = [];
|
||||
$this->say('');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function daten(): array
|
||||
{
|
||||
$import = app(ShinkanImport::class);
|
||||
$labels = [
|
||||
'neu' => ['Neu', 'is-neu'],
|
||||
'geaendert' => ['Geänderter Quellstand', 'is-geaendert'],
|
||||
'uebernommen' => ['Übernommen', 'is-eigen'],
|
||||
'nicht_mehr_bereitgestellt' => ['Nicht mehr bereitgestellt', ''],
|
||||
];
|
||||
$needle = mb_strtolower(trim($this->search));
|
||||
$rows = [];
|
||||
$total = 0;
|
||||
|
||||
foreach (ExerciseSource::query()->with('composition')->orderBy('title')->get() as $source) {
|
||||
$total++;
|
||||
$state = $import->state($source);
|
||||
|
||||
if (($this->statusFilter !== 'alle' && $this->statusFilter !== $state)
|
||||
|| ($needle !== '' && ! str_contains(mb_strtolower(($source->title ?? '').' '.$source->source_id), $needle))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'id' => $source->id,
|
||||
'titel' => $source->title ?: $source->source_id,
|
||||
'zustand' => $labels[$state][0],
|
||||
'ton' => $labels[$state][1],
|
||||
'state' => $state,
|
||||
'markierbar' => $state !== 'nicht_mehr_bereitgestellt',
|
||||
'lokal' => $source->composition === null ? null : PracticeResource::getUrl('edit', ['record' => $source->composition]),
|
||||
'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,
|
||||
'gesamt' => $total,
|
||||
'optionen' => ['alle' => 'Alle Zustände', 'neu' => 'Neu', 'geaendert' => 'Geänderter Quellstand', 'uebernommen' => 'Übernommen', 'nicht_mehr_bereitgestellt' => 'Nicht mehr bereitgestellt'],
|
||||
'eingerichtet' => $import->configured(),
|
||||
'anbindung' => $import->status(),
|
||||
'darfAendern' => static::canConfigure(),
|
||||
'letzterLauf' => ExerciseImportRun::query()->orderByDesc('id')->first(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $ids
|
||||
*/
|
||||
private function buildPreview(array $ids): void
|
||||
{
|
||||
$import = app(ShinkanImport::class);
|
||||
$this->preview = [];
|
||||
|
||||
foreach (ExerciseSource::query()->whereIn('id', $ids)->orderBy('title')->get() as $source) {
|
||||
$this->preview[] = $import->preview($source);
|
||||
}
|
||||
}
|
||||
|
||||
private function actor(): ?User
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
return $user instanceof User ? $user : null;
|
||||
}
|
||||
|
||||
private function say(string $message, bool $error = false): void
|
||||
{
|
||||
$this->feedback = $message;
|
||||
$this->feedbackError = $error;
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,11 @@ public function daten(): array
|
||||
['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' => 'Kauf auf Rechnung für Vereine: '.(Shop::invoice() ? 'angeboten' : 'aus'), 'neben' => 'Die Rechnung erstellt der Betreiber manuell; den Zahlungseingang bestätigst du in der Bestellverwaltung.', 'zustand' => ['label' => Shop::invoice() ? 'Bereit' : 'Aus', 'ton' => 'neutral']],
|
||||
['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 = [
|
||||
|
||||
@@ -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']);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ class CombinationResource extends CompositionKindResource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Fachliche Kombinationen';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
public static function kind(): CompositionKind
|
||||
{
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\EditorialWorkingDraft;
|
||||
use App\Domain\Catalog\ForeignCompositions;
|
||||
use App\Domain\Catalog\IdentityDimension;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
use App\Domain\Catalog\IdentityProfile;
|
||||
@@ -39,6 +40,7 @@
|
||||
use Filament\Support\Exceptions\Halt;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Str;
|
||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||
use Livewire\WithFileUploads;
|
||||
|
||||
@@ -68,6 +70,15 @@ abstract class EditComposition extends EditRecord
|
||||
|
||||
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 $search = '';
|
||||
@@ -489,8 +500,173 @@ public function cancelText(): void
|
||||
$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
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->feedback = $reason;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
$minutes = $this->minutes($this->durationMinutes);
|
||||
|
||||
@@ -508,6 +684,13 @@ public function saveDraft(): void
|
||||
|
||||
public function armRelease(): void
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->releaseArmed = false;
|
||||
$this->feedback = $reason;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
|
||||
if ($this->members === []) {
|
||||
@@ -585,6 +768,12 @@ protected function selectFirstPart(): void
|
||||
|
||||
public function discardDraft(): void
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->feedback = $reason;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var Composition $record */
|
||||
$record = $this->getRecord();
|
||||
app(EditorialWorkingDraft::class)->clear($record);
|
||||
@@ -924,7 +1113,7 @@ private function includePart(string $target, bool $allowDraft): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($this->members as $index => $member) {
|
||||
foreach ($this->isExercise() ? [] : $this->members as $index => $member) {
|
||||
if (($member['target'] ?? '') === $target) {
|
||||
$this->selected = $index;
|
||||
$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['note'] = '';
|
||||
$row = [...$row, ...$this->memberExtras([])];
|
||||
$this->members[] = $row;
|
||||
$this->members = array_values($this->members);
|
||||
$this->selected = array_key_last($this->members);
|
||||
@@ -1034,6 +1224,7 @@ public function useVersion(int $index, string $target): void
|
||||
$this->commitRoleDraft();
|
||||
$row['role'] = $this->members[$index]['role'] ?? $row['kind'];
|
||||
$row['note'] = $this->members[$index]['note'] ?? '';
|
||||
$row = [...$row, ...$this->memberExtras($this->members[$index])];
|
||||
$this->members[$index] = $row;
|
||||
$this->syncRoleDraft();
|
||||
$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
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->feedback = $reason;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
|
||||
if ($this->members === []) {
|
||||
@@ -1560,9 +1757,12 @@ public function publishRevision(): bool
|
||||
[
|
||||
'learning_goal' => $this->blank($this->learningGoal),
|
||||
'duration_minutes' => $minutes,
|
||||
'duration_max' => $this->blank($this->durationMax),
|
||||
'material_note' => $this->blank($this->materialNote),
|
||||
'prerequisites' => $this->blank($this->prerequisites),
|
||||
],
|
||||
$this->releaseConsent,
|
||||
$this->normalizeVariants($this->variants),
|
||||
);
|
||||
} catch (DomainRuleException $exception) {
|
||||
$this->feedback = $exception->getMessage();
|
||||
@@ -1679,7 +1879,8 @@ protected function loadAufbau(): void
|
||||
$this->imageCaptionText = $this->captionFor($composition->thumbnail_source);
|
||||
$this->catalogScope = match ($this->hostKind()) {
|
||||
CompositionKind::Kurs => 'module',
|
||||
CompositionKind::Uebung => 'medien',
|
||||
CompositionKind::Uebung => 'uebungen',
|
||||
CompositionKind::Exercise => 'medien',
|
||||
default => 'alles',
|
||||
};
|
||||
|
||||
@@ -1693,6 +1894,9 @@ protected function loadAufbau(): void
|
||||
|
||||
if ($version === null) {
|
||||
$this->members = [];
|
||||
$this->variants = [];
|
||||
$this->durationMax = '';
|
||||
$this->prerequisites = '';
|
||||
$this->learningGoal = '';
|
||||
$this->durationMinutes = '';
|
||||
$this->materialNote = '';
|
||||
@@ -1726,10 +1930,14 @@ protected function applyDraft(array $draft): void
|
||||
|
||||
$row['role'] = (string) ($member['role'] ?? $row['kind']);
|
||||
$row['note'] = trim((string) ($member['note'] ?? ''));
|
||||
$row = [...$row, ...$this->memberExtras($member)];
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
$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->durationMinutes = ($draft['duration_minutes'] ?? null) === null ? '' : (string) $draft['duration_minutes'];
|
||||
$this->materialNote = (string) ($draft['material_note'] ?? '');
|
||||
@@ -1747,6 +1955,11 @@ protected function applyDraft(array $draft): void
|
||||
protected function applyVersion(CompositionVersion $version): void
|
||||
{
|
||||
$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, 'origin' => $variant->origin,
|
||||
])->all());
|
||||
$this->durationMax = $version->duration_max === null ? '' : (string) $version->duration_max;
|
||||
$this->prerequisites = (string) ($version->prerequisites ?? '');
|
||||
$this->learningGoal = (string) ($version->learning_goal ?? '');
|
||||
$this->durationMinutes = $version->duration_minutes === null ? '' : (string) $version->duration_minutes;
|
||||
$this->materialNote = (string) ($version->material_note ?? '');
|
||||
@@ -1833,18 +2046,21 @@ protected function needsRevision(): bool
|
||||
|
||||
protected function sameMembers(CompositionVersion $version): bool
|
||||
{
|
||||
$version->loadMissing('members');
|
||||
$version->loadMissing('members.variant');
|
||||
$current = $version->members->map(function ($member): string {
|
||||
$target = $member->content_element_version_id
|
||||
? 'element:'.$member->content_element_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();
|
||||
$next = array_values(array_map(
|
||||
fn (array $member): string => trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? '').'|'.trim((string) ($member['note'] ?? '')),
|
||||
$this->members,
|
||||
));
|
||||
$next = array_values(array_map(function (array $member): string {
|
||||
$extras = $this->memberExtras($member);
|
||||
|
||||
return trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? '').'|'.trim((string) ($member['note'] ?? ''))
|
||||
.'|'.($extras['variant'] ?? '').'|'.$extras['requirement'].'|'.json_encode($extras['selection']);
|
||||
}, $this->members));
|
||||
|
||||
return $current === $next;
|
||||
}
|
||||
@@ -1859,8 +2075,15 @@ protected function didacticChanged(CompositionVersion $version): bool
|
||||
|
||||
$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, 'origin' => $variant->origin,
|
||||
])->all());
|
||||
|
||||
return $version->learning_goal !== $this->blank($this->learningGoal)
|
||||
|| $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;
|
||||
}
|
||||
|
||||
@@ -1929,6 +2152,12 @@ protected function persistRedaktion(): bool
|
||||
|
||||
protected function persistDraft(): bool
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->feedback = $reason;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->minutes($this->durationMinutes) === false) {
|
||||
$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),
|
||||
'duration_minutes' => $minutes === false ? $this->durationMinutes : $minutes,
|
||||
'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),
|
||||
'members' => array_values(array_map(
|
||||
fn (array $member): array => [
|
||||
'role' => trim((string) ($member['role'] ?? '')),
|
||||
'target' => (string) ($member['target'] ?? ''),
|
||||
'note' => trim((string) ($member['note'] ?? '')),
|
||||
...$this->memberExtras($member),
|
||||
],
|
||||
$members,
|
||||
)),
|
||||
@@ -2105,6 +2338,9 @@ protected function readyPayload(): array
|
||||
'learning_goal' => null,
|
||||
'duration_minutes' => null,
|
||||
'material_note' => null,
|
||||
'duration_max' => null,
|
||||
'prerequisites' => null,
|
||||
'variants' => [],
|
||||
'revision_note' => null,
|
||||
'members' => [],
|
||||
];
|
||||
@@ -2116,12 +2352,18 @@ protected function readyPayload(): array
|
||||
'learning_goal' => $version->learning_goal,
|
||||
'duration_minutes' => $version->duration_minutes === null ? null : (int) $version->duration_minutes,
|
||||
'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,
|
||||
'members' => array_values(array_map(
|
||||
fn (array $row): array => [
|
||||
'role' => trim((string) ($row['role'] ?? '')),
|
||||
'target' => (string) ($row['target'] ?? ''),
|
||||
'note' => trim((string) ($row['note'] ?? '')),
|
||||
...$this->memberExtras($row),
|
||||
],
|
||||
$rows,
|
||||
)),
|
||||
@@ -2145,6 +2387,7 @@ protected function normalizePayload(array $payload): array
|
||||
'role' => trim((string) ($member['role'] ?? '')),
|
||||
'target' => (string) ($member['target'] ?? ''),
|
||||
'note' => trim((string) ($member['note'] ?? '')),
|
||||
...$this->memberExtras($member),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -2152,6 +2395,9 @@ protected function normalizePayload(array $payload): array
|
||||
'learning_goal' => $payload['learning_goal'] ?? null,
|
||||
'duration_minutes' => $payload['duration_minutes'] ?? 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,
|
||||
'members' => $members,
|
||||
];
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Filament\Pages\Uebernahme;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Support\ListsCompositions;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
@@ -33,12 +34,12 @@ protected function fixedKind(): ?CompositionKind
|
||||
|
||||
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
|
||||
{
|
||||
$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;
|
||||
}
|
||||
@@ -55,6 +56,18 @@ public function content(Schema $schema): Schema
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
if ($this->kind() === CompositionKind::Exercise) {
|
||||
return [
|
||||
$this->createCompositionAction($this->kind()),
|
||||
Action::make('shinkan')
|
||||
->label('Aus Shinkan übernehmen')
|
||||
->icon('heroicon-o-arrow-down-tray')
|
||||
->color('gray')
|
||||
->visible(fn (): bool => ContentElementResource::editor())
|
||||
->url(fn (): string => Uebernahme::getUrl()),
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->onDesk()) {
|
||||
return [$this->createCompositionAction($this->kind())];
|
||||
}
|
||||
|
||||
@@ -18,11 +18,13 @@
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\ProductOptions;
|
||||
use App\Filament\Pages\Zahlungsjournal;
|
||||
use App\Filament\Resources\Offers\OfferResource;
|
||||
use App\Filament\Support\CatalogLabels;
|
||||
use App\Filament\Support\CatalogOptions;
|
||||
use App\Filament\Support\PublicationReadiness;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
@@ -366,6 +368,11 @@ private function angebotDaten(): array
|
||||
'wire' => "mountAction('end')",
|
||||
'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),
|
||||
|
||||
@@ -4,14 +4,17 @@
|
||||
|
||||
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;
|
||||
@@ -66,6 +69,11 @@ public function infolist(Schema $schema): Schema
|
||||
])->columns(1);
|
||||
}
|
||||
|
||||
private function hasStripePayment(): bool
|
||||
{
|
||||
return $this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists();
|
||||
}
|
||||
|
||||
private function order(): Order
|
||||
{
|
||||
/** @var Order $order */
|
||||
@@ -84,11 +92,15 @@ public function confirmInvoiceAction(): Action
|
||||
->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());
|
||||
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.');
|
||||
@@ -111,12 +123,27 @@ public function refundAction(): Action
|
||||
->modalSubmitActionLabel('Vollständig erstatten')
|
||||
->schema([
|
||||
Textarea::make('reason')->label('Begründung')->required()->rows(2)->maxLength(500)
|
||||
->helperText('Bleibt am Widerruf der Berechtigungen stehen, zum Beispiel „Widerruf geprüft, Frist gewahrt“.'),
|
||||
->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']);
|
||||
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.');
|
||||
@@ -188,6 +215,15 @@ private function bestellDaten(): array
|
||||
])->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' => [
|
||||
[
|
||||
|
||||
@@ -20,7 +20,7 @@ class PillarResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Pillar::class;
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Stammdaten';
|
||||
|
||||
protected static ?string $navigationLabel = 'Fachliche Säulen';
|
||||
|
||||
@@ -32,7 +32,7 @@ class PillarResource extends Resource
|
||||
|
||||
protected static ?string $slug = 'saeulen';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
|
||||
@@ -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 = 2;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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) {
|
||||
continue;
|
||||
}
|
||||
@@ -94,7 +94,7 @@ public static function readyTargets(): array
|
||||
$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);
|
||||
}
|
||||
|
||||
|
||||
@@ -266,7 +266,7 @@ public function elementUsage(ContentElement $element): array
|
||||
->get();
|
||||
|
||||
foreach ($members as $member) {
|
||||
$lines[] = self::compositionLabel($member->compositionVersion->composition)
|
||||
$lines[] = self::compositionLabelOf($member->compositionVersion->composition)
|
||||
.' · Fassung '.$member->compositionVersion->number
|
||||
.' · Rolle '.$member->role;
|
||||
}
|
||||
@@ -280,7 +280,9 @@ public function elementUsage(ContentElement $element): array
|
||||
foreach ($contents as $content) {
|
||||
$lines[] = 'Lizenzartikel '.$content->release->article->code
|
||||
.' · Stand '.$content->release->number
|
||||
.' · '.$content->path;
|
||||
.' · '.$content->path
|
||||
.($content->variant_key !== null ? ' · Variante '.$content->variant_key : '')
|
||||
.($content->requirement === CompositionMember::SUPPLEMENTARY ? ' · ergänzend' : '');
|
||||
}
|
||||
|
||||
return $lines === []
|
||||
@@ -313,7 +315,7 @@ public function compositionMembers(Composition $composition): array
|
||||
}
|
||||
|
||||
$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;
|
||||
@@ -365,7 +367,7 @@ public function compositionUsage(Composition $composition): array
|
||||
->get();
|
||||
|
||||
foreach ($parents as $member) {
|
||||
$lines[] = self::compositionLabel($member->compositionVersion->composition)
|
||||
$lines[] = self::compositionLabelOf($member->compositionVersion->composition)
|
||||
.' · Fassung '.$member->compositionVersion->number
|
||||
.' · 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
|
||||
{
|
||||
$kind = $composition->kind;
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Resources\Courses\CourseResource;
|
||||
use App\Filament\Resources\Exercises\ExerciseResource;
|
||||
use App\Filament\Resources\Practices\PracticeResource;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -33,6 +34,7 @@ class EditorialCatalog
|
||||
public function rows(CompositionVersion $version, int $exceptCompositionId): array
|
||||
{
|
||||
$version->loadMissing([
|
||||
'members.variant',
|
||||
'members.contentElementVersion.element.editorialContentKind',
|
||||
'members.nestedCompositionVersion.composition.editorialContentKind',
|
||||
]);
|
||||
@@ -50,6 +52,10 @@ public function rows(CompositionVersion $version, int $exceptCompositionId): arr
|
||||
|
||||
$row['role'] = $member->role;
|
||||
$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;
|
||||
}
|
||||
|
||||
@@ -140,6 +146,12 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
|
||||
}
|
||||
|
||||
$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
|
||||
?: ($composition->kind instanceof CompositionKind ? $composition->kind->deskLabel() : 'Zusammenstellung');
|
||||
|
||||
@@ -238,7 +250,11 @@ public function search(string $query, string $scope, int $exceptCompositionId):
|
||||
->with('composition.editorialContentKind')
|
||||
->whereHas('composition', function ($builder) use ($scope, $query, $like): void {
|
||||
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 === '') {
|
||||
@@ -311,7 +327,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
||||
->where('composition_id', '!=', $exceptCompositionId)
|
||||
->whereHas('composition', function ($builder) use ($query, $like, $kind, $dimensionId, $pillarId): void {
|
||||
if ($kind === 'modul') {
|
||||
$builder->where('kind', CompositionKind::Uebung);
|
||||
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
|
||||
}
|
||||
|
||||
if ($dimensionId > 0) {
|
||||
@@ -357,7 +373,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
||||
$builder->where('status', ContentVersionStatus::Bereit);
|
||||
})
|
||||
->when($kind === 'modul', function ($builder): void {
|
||||
$builder->where('kind', CompositionKind::Uebung);
|
||||
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
|
||||
})
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
@@ -1028,6 +1044,10 @@ private function suggestPicture(array $members, array $seen = []): ?array
|
||||
|
||||
$nested = $version->composition;
|
||||
|
||||
if ($nested === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->cardUrl('komposition', $nested->id, $nested->thumbnail_path) !== null) {
|
||||
return [
|
||||
'kind' => 'komposition',
|
||||
@@ -1063,6 +1083,7 @@ public function create(string $designation, CompositionKind $kind): Composition
|
||||
$slug = match ($kind) {
|
||||
CompositionKind::Kurs => 'programm',
|
||||
CompositionKind::Uebung => 'modul',
|
||||
CompositionKind::Exercise => 'uebung',
|
||||
default => null,
|
||||
};
|
||||
$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::Kombination => CombinationResource::class,
|
||||
CompositionKind::Uebung => ExerciseResource::class,
|
||||
CompositionKind::Exercise => PracticeResource::class,
|
||||
};
|
||||
|
||||
return $resource::getUrl('edit', ['record' => $composition]);
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Domain\Catalog\CompositionMember;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\ExerciseSource;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
use App\Domain\Catalog\Pillar;
|
||||
use App\Domain\Catalog\PillarFilterCompat;
|
||||
@@ -74,6 +76,7 @@ public function bestand(): array
|
||||
$einheit = match ($fixed) {
|
||||
CompositionKind::Kurs => ['Programm', 'Programme'],
|
||||
CompositionKind::Uebung => ['Modul', 'Module'],
|
||||
CompositionKind::Exercise => ['Übung', 'Übungen'],
|
||||
CompositionKind::Kombination => ['Fachliche Kombination', 'Fachliche Kombinationen'],
|
||||
default => ['Programm oder Modul', 'Programme und Module'],
|
||||
};
|
||||
@@ -150,6 +153,10 @@ public function entries(): array
|
||||
$canEdit = ContentElementResource::editor();
|
||||
$rows = [];
|
||||
|
||||
$shinkan = $kinds === [CompositionKind::Exercise] || in_array(CompositionKind::Exercise, $kinds, true)
|
||||
? ExerciseSource::query()->whereNotNull('composition_id')->pluck('composition_id')->all()
|
||||
: [];
|
||||
|
||||
$compositions = Composition::query()
|
||||
->whereIn('kind', $kinds)
|
||||
->with(['editorialContentKind', 'versions.members.contentElementVersion.element'])
|
||||
@@ -188,7 +195,7 @@ public function entries(): array
|
||||
$rows[] = [
|
||||
'schluessel' => 'c'.$composition->id,
|
||||
'titel' => $title,
|
||||
'meta' => $kind->deskLabel().($title !== $composition->designation ? ' · '.$composition->designation : ''),
|
||||
'meta' => $kind->deskLabel().($title !== $composition->designation ? ' · '.$composition->designation : '').($kind === CompositionKind::Exercise ? ' · Herkunft: '.$this->exerciseOrigin($composition, $shinkan) : ''),
|
||||
'text' => $summary,
|
||||
'bild' => $cover['url'],
|
||||
'bildFehlt' => 'Kein Titelbild',
|
||||
@@ -214,16 +221,41 @@ public function entries(): array
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Herkunft einer Übung: lokal angelegt, aus Shinkan übernommen oder aus Shinkan übernommen und lokal ergänzt.
|
||||
*
|
||||
* @param list<int> $shinkan Übungen mit Quellbindung
|
||||
*/
|
||||
private function exerciseOrigin(Composition $composition, array $shinkan): string
|
||||
{
|
||||
if (! in_array($composition->id, $shinkan, true)) {
|
||||
return 'lokal';
|
||||
}
|
||||
|
||||
$latest = $composition->versions->sortByDesc('number')->first();
|
||||
$local = $latest !== null && CompositionMember::query()->where('composition_version_id', $latest->id)->where('origin', 'lokal')->exists();
|
||||
|
||||
return $local ? 'Shinkan, lokal bearbeitet' : 'Shinkan';
|
||||
}
|
||||
|
||||
/**
|
||||
* Anlegedialog für Module und Programme; derselbe auf dem Arbeitsplatz und in den Listen.
|
||||
*/
|
||||
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')
|
||||
->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.')
|
||||
->modalSubmitActionLabel($label.' anlegen')
|
||||
->modalWidth('lg')
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use App\Domain\Catalog\OfferStatus;
|
||||
use App\Domain\Commerce\Cart;
|
||||
use App\Domain\Commerce\Checkout;
|
||||
use App\Domain\Commerce\LedgerEntry;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\OrderHolders;
|
||||
use App\Domain\Commerce\SalesTerms;
|
||||
@@ -144,6 +145,7 @@ public function show(Request $request, Order $order): View
|
||||
'stripePayment' => Shop::stripe(),
|
||||
'zahlung' => $request->query('zahlung'),
|
||||
'live' => Shop::live(),
|
||||
'receipts' => LedgerEntry::query()->where('order_id', $order->id)->where('derived', false)->orderBy('occurred_at')->orderBy('id')->get(),
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -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\ContentElement;
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\IdentityDimension;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
@@ -501,8 +502,10 @@ private function maySeeThumbnail(Request $request, string $kind, int $subject):
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ein gesperrtes Medium zeigt auch kein Vorschaubild mehr (Sperre gilt für Ausgaben und Ableitungen).
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use App\Domain\Commerce\Stripe\StripeSignature;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -42,7 +43,7 @@ public function __invoke(Request $request, StripeSignature $signature, Checkout
|
||||
$session = (array) ($event['data']['object'] ?? []);
|
||||
|
||||
return match ($event['type']) {
|
||||
'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $this->paid($session, $checkout),
|
||||
'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $this->paid($session, $checkout, $event),
|
||||
'checkout.session.expired', 'checkout.session.async_payment_failed' => $this->notPaid($session, (string) $event['type']),
|
||||
default => response()->json(['received' => true, 'handled' => false]),
|
||||
};
|
||||
@@ -50,8 +51,9 @@ public function __invoke(Request $request, StripeSignature $signature, Checkout
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $session
|
||||
* @param array<string, mixed> $event
|
||||
*/
|
||||
private function paid(array $session, Checkout $checkout): JsonResponse
|
||||
private function paid(array $session, Checkout $checkout, array $event): JsonResponse
|
||||
{
|
||||
if (($session['payment_status'] ?? null) !== 'paid') {
|
||||
return response()->json(['received' => true, 'handled' => false]);
|
||||
@@ -73,6 +75,9 @@ private function paid(array $session, Checkout $checkout): JsonResponse
|
||||
$reference,
|
||||
(int) ($session['amount_total'] ?? -1),
|
||||
(string) ($session['currency'] ?? ''),
|
||||
(bool) ($event['livemode'] ?? $session['livemode'] ?? false),
|
||||
is_numeric($event['created'] ?? null) ? CarbonImmutable::createFromTimestampUTC((int) $event['created']) : null,
|
||||
filled($session['payment_intent'] ?? null) ? (string) $session['payment_intent'] : null,
|
||||
);
|
||||
} catch (DomainRuleException $exception) {
|
||||
// Dauerhafter Fehler (Betragsabweichung, Bestellung nicht mehr offen): nichts freischalten, Zahlung zur
|
||||
|
||||
@@ -5,11 +5,13 @@
|
||||
use App\Domain\Catalog\ArticleRelease;
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\CompositionDisplayRelease;
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Domain\Catalog\CompositionStructureReader;
|
||||
use App\Domain\Catalog\CompositionVersion;
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\ExerciseGuide;
|
||||
use App\Domain\Catalog\ReleaseStatus;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Entitlement\DecideAccess;
|
||||
@@ -389,7 +391,7 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI
|
||||
'view_url' => $view,
|
||||
'poster_url' => $poster,
|
||||
'download_url' => $download,
|
||||
'program_url' => $this->programUrl($node),
|
||||
'program_url' => $this->exerciseUrl($user, $rootId, $node) ?? $this->programUrl($node),
|
||||
'composition_id' => $node->compositionId,
|
||||
'element_id' => $node->contentElementId,
|
||||
'version_id' => $node->contentElementVersionId,
|
||||
@@ -491,6 +493,46 @@ private function element(int $id): ?ContentElement
|
||||
return $this->elements[$id];
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Übung im Zusammenhang des erworbenen Moduls oder Programms: die im Stand gebundene Fassung und ihre Varianten,
|
||||
* nicht die jeweils neueste Fassung der Übung. Gefunden wird der jüngste auslieferbare Stand des Kontos, dessen
|
||||
* festgeschriebene Wurzel diese Fassung an einer Stelle einbindet.
|
||||
*/
|
||||
private function exerciseUrl(User $user, int $rootId, StructureNode $node): ?string
|
||||
{
|
||||
if ($node->compositionVersionId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$nested = CompositionVersion::query()->with('composition')->find($node->compositionVersionId);
|
||||
|
||||
if ($nested?->composition?->kind !== CompositionKind::Exercise) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$guide = app(ExerciseGuide::class);
|
||||
|
||||
foreach ($this->grants($user) as $grant) {
|
||||
$releases = ArticleRelease::query()
|
||||
->where('license_article_id', $grant->license_article_id)
|
||||
->whereIn('status', [ReleaseStatus::Veroeffentlicht, ReleaseStatus::AbgeloestVerfuegbar])
|
||||
->whereHas('rootCompositionVersion', fn ($query) => $query->where('composition_id', $rootId))
|
||||
->with('rootCompositionVersion')
|
||||
->orderByDesc('number')
|
||||
->get();
|
||||
|
||||
foreach ($releases as $release) {
|
||||
$path = $guide->pathTo($release->rootCompositionVersion, $nested->id);
|
||||
|
||||
if ($path !== null) {
|
||||
return route('member.exercise', ['article' => $grant->license_article_id, 'release' => $release->id, 'path' => $path]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function programUrl(StructureNode $node): ?string
|
||||
{
|
||||
if ($node->compositionId === null || $node->compositionVersionId === null) {
|
||||
|
||||
@@ -67,6 +67,12 @@ public function panel(Panel $panel): Panel
|
||||
->authMiddleware([
|
||||
Authenticate::class,
|
||||
])
|
||||
// Favicon zur Anfragezeit: ->favicon(asset(...)) würde beim Start der Anwendung berechnet, vor der
|
||||
// Auswertung von Proxy-Kopfzeilen und geöffneter Adresse, und könnte auf einen falschen Host zeigen.
|
||||
->renderHook(
|
||||
PanelsRenderHook::HEAD_END,
|
||||
fn (): string => view('components.site.favicon')->render(),
|
||||
)
|
||||
->renderHook(
|
||||
PanelsRenderHook::STYLES_AFTER,
|
||||
fn (): string => view('filament.cms.styles')->render().view('filament.verwaltung.styles')->render(),
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Brand;
|
||||
|
||||
use Illuminate\Support\HtmlString;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Kleingrafiken des Brand-Kits (docs/Brand-UI-Kit/16_Lara-Felix-Kleingrafiken) als Inline-SVG.
|
||||
*
|
||||
* - Nur Dateien aus resources/svg/brand/<Satz>/ sind zulässig; ein unbekannter Name ist ein Fehler, kein stiller Leerplatz.
|
||||
* - Die Kit-Dateien tragen alle dieselbe ID (motif-title) und einen Titel. Beim Einbetten werden ID, Titel, Rolle und feste
|
||||
* Größe entfernt, damit mehrere Symbole auf einer Seite keine doppelten IDs erzeugen. Symbole sind Beiwerk
|
||||
* (aria-hidden); die Aussage trägt immer der danebenstehende Text.
|
||||
* - Sätze: „symbole“ (Symbole und Akzente aus dem Kit, feste Markenfarben) und „glyphen“ (kleine Zeichen für Tags, Farbe
|
||||
* über currentColor, Geometrie aus den Tag-Dateien des Kits).
|
||||
* - Nicht enthalten: die Motive mit Text als Pfad (Pinsel, Pillen, Tags, Kompositionen). Text bleibt HTML.
|
||||
*/
|
||||
final class Symbols
|
||||
{
|
||||
public const SET_SYMBOLS = 'symbole';
|
||||
|
||||
public const SET_GLYPHS = 'glyphen';
|
||||
|
||||
/** @var array<string, string> */
|
||||
private static array $cache = [];
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function names(string $set = self::SET_SYMBOLS): array
|
||||
{
|
||||
$files = glob(self::directory($set).'/*.svg') ?: [];
|
||||
$names = array_map(fn (string $file): string => basename($file, '.svg'), $files);
|
||||
sort($names);
|
||||
|
||||
return $names;
|
||||
}
|
||||
|
||||
public static function symbol(string $name, string $attributes = ''): HtmlString
|
||||
{
|
||||
return self::render(self::SET_SYMBOLS, $name, $attributes);
|
||||
}
|
||||
|
||||
public static function glyph(string $name, string $attributes = ''): HtmlString
|
||||
{
|
||||
return self::render(self::SET_GLYPHS, $name, $attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $attributes bereits maskierte Attribute (aus der Attributtasche der Komponente)
|
||||
*/
|
||||
private static function render(string $set, string $name, string $attributes): HtmlString
|
||||
{
|
||||
if (! preg_match('/^[a-z0-9-]+$/', $name) || ! in_array($name, self::names($set), true)) {
|
||||
throw new InvalidArgumentException("Unbekanntes Markensymbol „{$name}“ im Satz „{$set}“.");
|
||||
}
|
||||
|
||||
$svg = self::$cache["$set/$name"] ??= self::clean((string) file_get_contents(self::directory($set)."/$name.svg"));
|
||||
$extra = trim($attributes) === '' ? '' : ' '.trim($attributes);
|
||||
|
||||
return new HtmlString(preg_replace('/^<svg\b/', '<svg aria-hidden="true" focusable="false"'.$extra, $svg, 1) ?? $svg);
|
||||
}
|
||||
|
||||
private static function clean(string $svg): string
|
||||
{
|
||||
$svg = trim($svg);
|
||||
$svg = preg_replace('#<title\b[^>]*>.*?</title>#s', '', $svg) ?? $svg;
|
||||
$svg = preg_replace('/\r?\n\s*/', '', $svg) ?? $svg;
|
||||
|
||||
return (string) preg_replace_callback('/^<svg\b[^>]*>/', function (array $root): string {
|
||||
return (string) preg_replace('/\s(?:id|role|aria-labelledby|width|height)="[^"]*"/', '', $root[0]);
|
||||
}, $svg);
|
||||
}
|
||||
|
||||
private static function directory(string $set): string
|
||||
{
|
||||
if (! in_array($set, [self::SET_SYMBOLS, self::SET_GLYPHS], true)) {
|
||||
throw new InvalidArgumentException("Unbekannter Symbolsatz „{$set}“.");
|
||||
}
|
||||
|
||||
return resource_path("svg/brand/$set");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
use App\Domain\Cms\Widgets\Types\CardsWidget;
|
||||
use App\Domain\Cms\Widgets\Types\CatalogCardsWidget;
|
||||
use App\Domain\Cms\Widgets\Types\FaqWidget;
|
||||
use App\Domain\Cms\Widgets\Types\FeaturesWidget;
|
||||
use App\Domain\Cms\Widgets\Types\HeadingWidget;
|
||||
use App\Domain\Cms\Widgets\Types\HeroWidget;
|
||||
use App\Domain\Cms\Widgets\Types\ImageTextWidget;
|
||||
@@ -26,6 +27,7 @@
|
||||
ProseWidget::class,
|
||||
ImageTextWidget::class,
|
||||
CardsWidget::class,
|
||||
FeaturesWidget::class,
|
||||
CatalogCardsWidget::class,
|
||||
TopicCardWidget::class,
|
||||
MediaCardWidget::class,
|
||||
|
||||
@@ -42,6 +42,12 @@
|
||||
'api_base' => env('STRIPE_API_BASE', 'https://api.stripe.com'),
|
||||
],
|
||||
|
||||
// Übernahme von Übungen aus dem Shinkan-Katalog. Adresse und Schlüssel stehen nur in der Umgebungsdatei des Servers.
|
||||
'shinkan' => [
|
||||
'url' => env('SHINKAN_DISTRIBUTION_URL'),
|
||||
'key' => env('SHINKAN_DISTRIBUTION_KEY'),
|
||||
],
|
||||
|
||||
'slack' => [
|
||||
'notifications' => [
|
||||
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
|
||||
|
||||
@@ -18,9 +18,23 @@
|
||||
|
||||
/*
|
||||
| Kauf auf Rechnung für Vereine und Organisationen (PAY-006): auf Anfrage, Rechnung manuell durch den Betreiber.
|
||||
| Standardmäßig aus: Das Mitglied sieht die Möglichkeit erst, wenn der Prozess vollständig ist (Rechnungserstellung
|
||||
| und Nummernkreis, Benachrichtigung des Betreibers, rechtliche Klärung OPEN-06). Die Umsetzung bleibt erhalten;
|
||||
| bereits angelegte Rechnungsbestellungen bleiben in der Verwaltung bearbeitbar.
|
||||
*/
|
||||
|
||||
'invoice' => (bool) env('SHOP_INVOICE', true),
|
||||
'invoice' => (bool) env('SHOP_INVOICE', false),
|
||||
|
||||
/*
|
||||
| Zahlungsbeleg für Mitglieder (PDF). Aussteller: Zeilen durch „|“ getrennt (zum Beispiel Name|Straße|PLZ Ort), erst
|
||||
| zu pflegen, wenn die Angaben feststehen; ohne sie druckt der Beleg keinen Aussteller. Hinweis: optionaler Zusatztext
|
||||
| (Umgebungsvariablen SHOP_RECEIPT_ISSUER, SHOP_RECEIPT_NOTE). Beide hängen an der rechtlichen Klärung (OPEN-06).
|
||||
*/
|
||||
|
||||
'receipt' => [
|
||||
'issuer' => env('SHOP_RECEIPT_ISSUER'),
|
||||
'note' => env('SHOP_RECEIPT_NOTE'),
|
||||
],
|
||||
|
||||
/*
|
||||
| Preis- und Steuerhinweis im Warenkorb und in der Bestellübersicht. Der Wortlaut hängt an der Steuerentscheidung
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Zahlungsjournal: eine unveränderliche Zeile je Geldbewegung (Zahlungseingang, Erstattung). Rein ergänzend.
|
||||
*
|
||||
* Die Tabelle `payments` hält nur den aktuellen Zustand einer Zahlung und überschreibt ihn bei der Erstattung. Für den
|
||||
* Nachweis gegenüber dem Finanzamt braucht es dagegen je Bewegung Datum, Betrag, Beleg beim Anbieter, handelnde
|
||||
* Person, Begründung und den Zahler zum Zeitpunkt der Bewegung. Zeilen werden nie geändert oder gelöscht; eine
|
||||
* Korrektur ist eine neue Gegenbuchung. Auf PostgreSQL erzwingt das ein Trigger auch gegen direkte SQL-Zugriffe.
|
||||
*
|
||||
* Bestehende bestätigte und erstattete Zahlungen werden nachgetragen und als „nachgetragen“ markiert: Ihr Datum ist
|
||||
* aus den Zeitstempeln der Zahlung abgeleitet und nicht der belegte Zahlungs- oder Erstattungszeitpunkt.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('payment_ledger', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('kind', 16);
|
||||
$table->foreignId('order_id')->constrained('orders')->restrictOnDelete();
|
||||
$table->foreignId('payment_id')->nullable()->constrained('payments')->restrictOnDelete();
|
||||
$table->timestamp('occurred_at');
|
||||
$table->integer('amount_cents');
|
||||
$table->string('currency', 3)->default('EUR');
|
||||
$table->string('provider', 32);
|
||||
$table->string('provider_reference', 191);
|
||||
$table->string('provider_payment_ref', 191)->nullable();
|
||||
$table->string('provider_status', 32)->nullable();
|
||||
$table->boolean('live')->default(false);
|
||||
$table->boolean('derived')->default(false);
|
||||
$table->unsignedBigInteger('actor_id')->nullable();
|
||||
$table->string('actor_name', 160)->nullable();
|
||||
$table->text('reason')->nullable();
|
||||
$table->json('payer');
|
||||
$table->json('order_snapshot');
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
|
||||
$table->unique(['kind', 'provider', 'provider_reference'], 'payment_ledger_event_unique');
|
||||
$table->index(['occurred_at']);
|
||||
$table->index(['order_id']);
|
||||
});
|
||||
|
||||
$this->backfill();
|
||||
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
DB::unprepared(<<<'SQL'
|
||||
CREATE FUNCTION payment_ledger_immutable() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'Das Zahlungsjournal ist unveränderlich. Korrekturen sind neue Gegenbuchungen.';
|
||||
END;
|
||||
$$ LANGUAGE plpgsql
|
||||
SQL);
|
||||
DB::unprepared('CREATE TRIGGER payment_ledger_no_change BEFORE UPDATE OR DELETE ON payment_ledger FOR EACH ROW EXECUTE PROCEDURE payment_ledger_immutable()');
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
DB::unprepared('DROP TRIGGER IF EXISTS payment_ledger_no_change ON payment_ledger');
|
||||
DB::unprepared('DROP FUNCTION IF EXISTS payment_ledger_immutable()');
|
||||
}
|
||||
|
||||
Schema::dropIfExists('payment_ledger');
|
||||
}
|
||||
|
||||
private function backfill(): void
|
||||
{
|
||||
$payments = DB::table('payments')->whereIn('status', ['bestaetigt', 'erstattet'])->orderBy('id')->get();
|
||||
|
||||
foreach ($payments as $payment) {
|
||||
$order = DB::table('orders')->where('id', $payment->order_id)->first();
|
||||
|
||||
if ($order === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$amount = (int) ($payment->amount_cents ?? $order->total_cents ?? 0);
|
||||
$payer = json_encode($this->payer($order), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
$snapshot = json_encode($this->orderSnapshot($order), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||||
$base = [
|
||||
'order_id' => $order->id,
|
||||
'payment_id' => $payment->id,
|
||||
'currency' => $order->currency ?? 'EUR',
|
||||
'provider' => $payment->provider,
|
||||
'provider_payment_ref' => $payment->provider_payment_ref,
|
||||
'live' => false,
|
||||
'derived' => true,
|
||||
'actor_id' => $payment->confirmed_by,
|
||||
'payer' => $payer,
|
||||
'order_snapshot' => $snapshot,
|
||||
];
|
||||
|
||||
DB::table('payment_ledger')->insert($base + [
|
||||
'kind' => 'eingang',
|
||||
'occurred_at' => $payment->created_at ?? $order->created_at,
|
||||
'amount_cents' => $amount,
|
||||
'provider_reference' => $payment->provider_reference,
|
||||
]);
|
||||
|
||||
if ($payment->status === 'erstattet') {
|
||||
DB::table('payment_ledger')->insert($base + [
|
||||
'kind' => 'erstattung',
|
||||
'occurred_at' => $payment->updated_at ?? $payment->created_at ?? $order->created_at,
|
||||
'amount_cents' => -$amount,
|
||||
'provider_reference' => 'nachgetragen-'.$payment->id,
|
||||
'actor_id' => null,
|
||||
'reason' => 'Nachgetragen: Zeitpunkt, Referenz und Begründung der Erstattung wurden damals nicht festgehalten.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function payer(object $order): array
|
||||
{
|
||||
$party = $order->party_id === null ? null : DB::table('parties')->where('id', $order->party_id)->first();
|
||||
$user = $order->user_id === null ? null : DB::table('users')->where('id', $order->user_id)->first();
|
||||
$address = $order->party_id === null ? null : DB::table('billing_addresses')->where('party_id', $order->party_id)->first();
|
||||
|
||||
return [
|
||||
'holder' => $party?->display_name,
|
||||
'holder_kind' => $order->holder_kind,
|
||||
'buyer' => $user?->name,
|
||||
'buyer_email' => $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(object $order): array
|
||||
{
|
||||
$lines = DB::table('order_lines')->where('order_id', $order->id)->orderBy('id')->get(['offer_name', 'price_cents', 'discount_cents']);
|
||||
|
||||
return [
|
||||
'subtotal_cents' => (int) ($order->subtotal_cents ?? $order->total_cents ?? 0),
|
||||
'discount_cents' => (int) ($order->discount_cents ?? 0),
|
||||
'discount_code' => json_decode((string) ($order->discount_snapshot ?? 'null'), true)['code'] ?? null,
|
||||
'lines' => $lines->map(fn (object $line): array => [
|
||||
'name' => $line->offer_name,
|
||||
'price_cents' => (int) $line->price_cents,
|
||||
'discount_cents' => (int) ($line->discount_cents ?? 0),
|
||||
])->all(),
|
||||
];
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Übungsverwaltung, rein additiv. Alle neuen Spalten sind nullable oder haben einen Vorgabewert. Der Rückfall auf den
|
||||
* vorherigen Programmstand setzt nur den Code zurück: Dieser kennt die Spalten nicht, liest Übungen wegen des
|
||||
* Bereichsfilters am Modell (SupportedKindScope) nicht und verweigert das Veröffentlichen von Aufbauten mit Übungen.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('composition_versions', function (Blueprint $table) {
|
||||
$table->unsignedInteger('duration_max')->nullable();
|
||||
$table->text('prerequisites')->nullable();
|
||||
// Änderungsnachweis über Felder, Varianten und Verwendungen; resolved_hash deckt nur die Medienmenge ab.
|
||||
$table->string('structure_hash')->nullable();
|
||||
});
|
||||
|
||||
Schema::table('compatibility_attestations', function (Blueprint $table) {
|
||||
$table->string('structure_hash')->nullable();
|
||||
});
|
||||
|
||||
Schema::create('composition_version_variants', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('composition_version_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('key');
|
||||
$table->unsignedInteger('position');
|
||||
$table->string('name');
|
||||
$table->text('description')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['composition_version_id', 'key']);
|
||||
$table->unique(['composition_version_id', 'position']);
|
||||
});
|
||||
|
||||
Schema::table('composition_members', function (Blueprint $table) {
|
||||
$table->foreignId('variant_id')->nullable()->constrained('composition_version_variants')->restrictOnDelete();
|
||||
$table->string('requirement')->default('erforderlich');
|
||||
$table->json('variant_selection')->nullable();
|
||||
});
|
||||
|
||||
Schema::table('release_contents', function (Blueprint $table) {
|
||||
$table->string('requirement')->nullable();
|
||||
$table->string('variant_key')->nullable();
|
||||
});
|
||||
|
||||
Schema::table('media_deliveries', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('composition_version_id')->nullable();
|
||||
});
|
||||
|
||||
$now = now();
|
||||
DB::table('editorial_content_kinds')->insertOrIgnore([
|
||||
'slug' => 'uebung',
|
||||
'label' => 'Übung',
|
||||
'sort_order' => 25,
|
||||
'is_active' => true,
|
||||
'contexts' => json_encode(['uebung', 'lizenzartikel']),
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::table('editorial_content_kinds')->where('slug', 'uebung')->delete();
|
||||
|
||||
Schema::table('media_deliveries', function (Blueprint $table) {
|
||||
$table->dropColumn('composition_version_id');
|
||||
});
|
||||
Schema::table('release_contents', function (Blueprint $table) {
|
||||
$table->dropColumn(['requirement', 'variant_key']);
|
||||
});
|
||||
Schema::table('composition_members', function (Blueprint $table) {
|
||||
$table->dropConstrainedForeignId('variant_id');
|
||||
$table->dropColumn(['requirement', 'variant_selection']);
|
||||
});
|
||||
Schema::dropIfExists('composition_version_variants');
|
||||
Schema::table('compatibility_attestations', function (Blueprint $table) {
|
||||
$table->dropColumn('structure_hash');
|
||||
});
|
||||
Schema::table('composition_versions', function (Blueprint $table) {
|
||||
$table->dropColumn(['duration_max', 'prerequisites', 'structure_hash']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Übernahme aus einer Quelle (Shinkan), rein additiv. Die Quelle ist an ihre stabile Kennung gebunden; jeder Inhaltsstand
|
||||
* (Prüfsumme) wird genau einmal festgehalten. Eine lokale Fassung entsteht erst mit der bewussten Übernahme.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('exercise_sources', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('source_system')->default('shinkan');
|
||||
$table->string('source_id');
|
||||
$table->foreignId('composition_id')->nullable()->constrained()->nullOnDelete();
|
||||
$table->string('title')->nullable();
|
||||
// bereitgestellt | nicht_mehr_bereitgestellt: nur die Verfügbarkeit an der Quelle, kein Rechtsvorgang.
|
||||
$table->string('availability')->default('bereitgestellt');
|
||||
$table->string('last_hash')->nullable();
|
||||
$table->timestamp('last_seen_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['source_system', 'source_id']);
|
||||
});
|
||||
|
||||
Schema::create('exercise_source_snapshots', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('exercise_source_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('content_hash');
|
||||
$table->json('payload');
|
||||
$table->unsignedBigInteger('adopted_version_id')->nullable();
|
||||
$table->timestamp('fetched_at');
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['exercise_source_id', 'content_hash']);
|
||||
});
|
||||
|
||||
Schema::create('exercise_import_runs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('source_system')->default('shinkan');
|
||||
$table->string('status');
|
||||
$table->string('cursor')->nullable();
|
||||
$table->unsignedInteger('added')->default(0);
|
||||
$table->unsignedInteger('updated')->default(0);
|
||||
$table->unsignedInteger('removed')->default(0);
|
||||
$table->text('error')->nullable();
|
||||
$table->timestamp('started_at');
|
||||
$table->timestamp('finished_at')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::table('content_elements', function (Blueprint $table) {
|
||||
$table->string('source_ref')->nullable()->index();
|
||||
});
|
||||
|
||||
Schema::table('composition_versions', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('source_snapshot_id')->nullable();
|
||||
});
|
||||
|
||||
Schema::table('composition_members', function (Blueprint $table) {
|
||||
// quelle | lokal: Was stammt aus der Quelle, was hat die Redaktion lokal ergänzt?
|
||||
$table->string('origin')->default('lokal');
|
||||
});
|
||||
|
||||
Schema::table('composition_version_variants', function (Blueprint $table) {
|
||||
$table->string('origin')->default('lokal');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('composition_version_variants', function (Blueprint $table) {
|
||||
$table->dropColumn('origin');
|
||||
});
|
||||
Schema::table('composition_members', function (Blueprint $table) {
|
||||
$table->dropColumn('origin');
|
||||
});
|
||||
Schema::table('composition_versions', function (Blueprint $table) {
|
||||
$table->dropColumn('source_snapshot_id');
|
||||
});
|
||||
Schema::table('content_elements', function (Blueprint $table) {
|
||||
$table->dropColumn('source_ref');
|
||||
});
|
||||
Schema::dropIfExists('exercise_import_runs');
|
||||
Schema::dropIfExists('exercise_source_snapshots');
|
||||
Schema::dropIfExists('exercise_sources');
|
||||
}
|
||||
};
|
||||
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 835 B |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 44 KiB |
@@ -0,0 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-labelledby="favicon-title">
|
||||
<title id="favicon-title">Lara & Felix</title>
|
||||
<rect x="1" y="1" width="62" height="62" rx="15" fill="#032551" stroke="#426184" stroke-width="2"/>
|
||||
<g fill="none" stroke="#fff" stroke-width="8.4" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14.8 20 Q14 31 14.8 39 Q20.6 39 25.4 37.8"/>
|
||||
<path d="M37.4 38.8 Q36.8 29.1 37.8 18.6 Q44.6 17.1 50.1 18.2 M37.5 28.7 Q43 27.9 47.4 28.1"/>
|
||||
</g>
|
||||
<path d="M13 51 Q31 44.2 51 49.3" fill="none" stroke="#FCD10A" stroke-width="5.5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 661 B |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 7.3 KiB |