Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
759b3e1c02 | ||
|
|
57b2131632 |
No files matched your search
@@ -63,6 +63,6 @@ ## Entwicklung
|
||||
## Verwaltungsoberfläche
|
||||
|
||||
- Maßgeblich sind `docs/ux/verwaltung/14-verwaltungsstandard.md` (Design und Interaktion) und `15-umbauauftrag.md` (Auftrag, Nachweise). Keine neue allgemeine Designabstimmung verlangen. Einstieg für alle Agenten: `AGENTS.md`, `.cursor/rules/verwaltung-ux.mdc`.
|
||||
- Gemeinsame Bausteine wiederverwenden statt neue Masken bauen: `resources/views/filament/verwaltung/` (`kopf`, `redaktion`, `texte`, `praesentation`, `einordnung`, `picker`, `bestaetigung`, `abgang`, `aufbau`, `bestand`) mit dem Trait `App\Filament\Support\ManagesEditorialSurface`. Listen nutzen `verwaltung/bestand` mit `ShowsBestand` (bzw. `ListsCompositions`, `ListsCatalog`) und den Eintrag `<x-vw.eintrag>`, den auch der Picker verwendet; Katalogobjekte die Seite `catalog/objekt`. CMS: Seitenkopf `cms/seite-kopf` (Register, Kontexte „Abschnitt gestalten“ und „Konfigurieren“); Seiten und Menüs in der Webpräsenz (`App\Filament\Pages\Webpraesenz`, Menüs als Arbeitsstand mit einer Speicherhandlung). Der Picker liegt im Trait `ChoosesMedia` (Redaktion über `ManagesEditorialSurface`, CMS-Bilder über `ChoosesWebsiteImages`); keine eigenen Auswahllisten für Medien bauen. Redaktionelle Auswahlwerte (Materialart, Einordnung) nur über `App\Domain\Catalog\EditorialVocabulary` anbieten und prüfen (aktiv, zulässiger Kontext, vorhandene Zuordnungen erhalten); gepflegt werden sie unter „Redaktionelle Stammdaten“. Fachliche Säulen gibt es nur in der Säulenverwaltung (`pillars`); Zuordnung über `PillarService::assign`, nie über eine Dimension. Ersetzt eine Seite die Filament-Tabelle, muss sie den Dialogbereich ausgeben (in `bestand` enthalten), sonst öffnen „… anlegen“-Dialoge nicht. Gestaltungswerte nur in `verwaltung/styles.blade.php` (Tokens `--vw-…`, dokumentiert in `docs/ux/verwaltung/tokens.md`).
|
||||
- Gemeinsame Bausteine wiederverwenden statt neue Masken bauen: `resources/views/filament/verwaltung/` (`kopf`, `redaktion`, `texte`, `praesentation`, `einordnung`, `picker`, `bestaetigung`, `abgang`, `aufbau`, `bestand`) mit dem Trait `App\Filament\Support\ManagesEditorialSurface`. Listen nutzen `verwaltung/bestand` mit `ShowsBestand` (bzw. `ListsCompositions`, `ListsCatalog`) und den Eintrag `<x-vw.eintrag>`, den auch der Picker verwendet; Katalogobjekte die Seite `catalog/objekt`. CMS: Seitenkopf `cms/seite-kopf` (Register, Kontexte „Abschnitt gestalten“ und „Konfigurieren“); Seiten und Menüs in der Webpräsenz (`App\Filament\Pages\Webpraesenz`, Menüs als Arbeitsstand mit einer Speicherhandlung). Der Picker liegt im Trait `ChoosesMedia` (Redaktion über `ManagesEditorialSurface`, CMS-Bilder über `ChoosesWebsiteImages`); keine eigenen Auswahllisten für Medien bauen. Redaktionelle Auswahlwerte (Materialart, Einordnung) nur über `App\Domain\Catalog\EditorialVocabulary` anbieten und prüfen (aktiv, zulässiger Kontext, vorhandene Zuordnungen erhalten); gepflegt werden sie unter „Redaktionelle Stammdaten“. Ersetzt eine Seite die Filament-Tabelle, muss sie den Dialogbereich ausgeben (in `bestand` enthalten), sonst öffnen „… anlegen“-Dialoge nicht. Gestaltungswerte nur in `verwaltung/styles.blade.php` (Tokens `--vw-…`, dokumentiert in `docs/ux/verwaltung/tokens.md`).
|
||||
- Die Redaktion ist ein Arbeitsstand: nur „Redaktion speichern“ schreibt Texte, Einordnung, Präsentationsmedien und Abweichungen. Kein verdecktes Mitspeichern aus anderen Dialogen, offene Eingaben bleiben beim Wechsel erhalten.
|
||||
- Jede UI-Änderung in der echten Anwendung prüfen (luf-test, breite und schmale Fenster, Tastatur) und mit Screenshots in `docs/ux/verwaltung/abnahme/` belegen. Stand der Abnahme: `abnahme/teil-a.md`, `abnahme/teil-b.md`, `abnahme/teil-c.md`, `abnahme/stammdaten.md`.
|
||||
@@ -1,25 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Domain\Catalog\LegacyPillarAdoption;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class AdoptLegacyPillars extends Command
|
||||
{
|
||||
protected $signature = 'luf:saeulen-uebernehmen {--dry-run : Nur berichten, nichts schreiben}';
|
||||
|
||||
protected $description = 'Übernimmt die alte Dimension „Fachliche Säule“ in die zentrale Säulenverwaltung und berichtet ungeklärte Fälle';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$report = (new LegacyPillarAdoption)->run($dryRun);
|
||||
|
||||
foreach (LegacyPillarAdoption::lines($report, $dryRun) as $line) {
|
||||
$this->line($line);
|
||||
}
|
||||
|
||||
return $report['unresolved'] === [] ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Composition extends Model
|
||||
@@ -45,13 +44,4 @@ public function versions(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompositionVersion::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Direkt zugeordnete fachliche Säulen (zentrale Säulenverwaltung). Die Säulen der enthaltenen Medien sind davon
|
||||
* getrennt und werden zur Laufzeit abgeleitet (CatalogReading::memberPillars).
|
||||
*/
|
||||
public function pillars(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Pillar::class)->orderBy('pillars.sort_order')->orderBy('pillars.name');
|
||||
}
|
||||
}
|
||||
@@ -20,15 +20,20 @@ public function values(): HasMany
|
||||
}
|
||||
|
||||
/**
|
||||
* Fachliche Säulen werden für alle Objektarten über die zentrale Säulenverwaltung gewählt (`pillars`), nie über
|
||||
* eine Dimension. Die alte Dimension „Fachliche Säule“ bleibt nur als Verlauf in der Datenbank und wird nirgends
|
||||
* mehr angeboten, geändert oder gefiltert.
|
||||
* Inhaltselemente pflegen Themen über die Säulen, nicht noch einmal über die Dimension.
|
||||
* Module, Programme und Lizenzartikel haben keine Säulenauswahl und behalten die Dimension.
|
||||
*
|
||||
* @return Collection<int, self>
|
||||
*/
|
||||
public static function forSubject(Model $subject): Collection
|
||||
{
|
||||
return static::query()->with('values')->where('slug', '!=', self::PILLAR_SLUG)->orderBy('label')->get();
|
||||
$query = static::query()->with('values')->orderBy('label');
|
||||
|
||||
if ($subject instanceof ContentElement) {
|
||||
$query->where('slug', '!=', self::PILLAR_SLUG);
|
||||
}
|
||||
|
||||
return $query->get();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
class EditorialDimensionValue extends Model
|
||||
{
|
||||
protected $fillable = ['editorial_dimension_id', 'pillar_id', 'slug', 'label', 'sort_order', 'is_active'];
|
||||
protected $fillable = ['editorial_dimension_id', 'slug', 'label', 'sort_order', 'is_active'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
|
||||
@@ -181,13 +181,13 @@ public function dimensionGroups(Model $subject, array $assignedIds): array
|
||||
* @param list<int> $selectedIds
|
||||
* @return list<array{label: string, values: list<array{id: int, label: string}>}>
|
||||
*/
|
||||
public function dimensionFilterGroups(array $selectedIds = []): array
|
||||
public function dimensionFilterGroups(array $selectedIds = [], bool $withPillars = true): array
|
||||
{
|
||||
$used = DB::table('identity_dimension_values')->distinct()->pluck('editorial_dimension_value_id')->map(fn ($id): int => (int) $id)->all();
|
||||
$groups = [];
|
||||
|
||||
foreach (EditorialDimension::query()->with('values')->orderBy('label')->get() as $dimension) {
|
||||
if ($dimension->slug === EditorialDimension::PILLAR_SLUG) {
|
||||
if (! $withPillars && $dimension->slug === EditorialDimension::PILLAR_SLUG) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -217,7 +217,7 @@ public function dimensionFilterGroups(array $selectedIds = []): array
|
||||
*/
|
||||
public function memberFilterDimensions(array $selectedIds = []): Collection
|
||||
{
|
||||
$dimensions = EditorialDimension::query()->with('values')->where('slug', '!=', EditorialDimension::PILLAR_SLUG)->orderBy('label')->get();
|
||||
$dimensions = EditorialDimension::query()->with('values')->orderBy('label')->get();
|
||||
|
||||
foreach ($dimensions as $dimension) {
|
||||
$dimension->setRelation('values', $dimension->values
|
||||
|
||||
@@ -1,270 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Übernimmt die frühere Kopie „Fachliche Säule“ (Dimension `saeule`) in die zentrale Säulenverwaltung (Tabelle
|
||||
* `pillars`). Verlustfrei, wiederholbar und ohne Raten:
|
||||
*
|
||||
* - **Zuordnung Wert → Säule** nur über die gespeicherte Kennung `pfeiler-{Säulenkennung}`, die die Migration
|
||||
* vom 16.11.2026 beim Spiegeln geschrieben hat, und nur, wenn die Säule existiert und nicht jünger als der Wert ist
|
||||
* (sonst kann die Kennung nicht aus ihr entstanden sein). Eine abweichende Bezeichnung ist nach einem Umbenennen
|
||||
* erwartet und wird nur berichtet. Die Verknüpfung steht in `editorial_dimension_values.pillar_id`.
|
||||
* - **Übernommen** werden nur direkte Zuordnungen von Modulen, Programmen und Lizenzartikeln in `composition_pillar`
|
||||
* und `license_article_pillar` (insert-or-ignore, daher beliebig oft ausführbar).
|
||||
* - **Nicht übernommen, sondern gemeldet:** Werte ohne belastbare Kennung, Zuordnungen zu fehlenden Objekten,
|
||||
* abgeleitete Zuordnungen und unbekannte Objektarten. Abgeleitete Säulen eines Programms oder Moduls entstehen zur
|
||||
* Laufzeit aus den enthaltenen Medien und werden nie als direkte Zuordnung gespeichert.
|
||||
* - **Medien:** Die gespiegelten Zeilen sind eine veraltete Kopie; maßgeblich ist `content_element_pillar`. Sie werden
|
||||
* nicht zurückgemischt, nur gezählt.
|
||||
* - Alte Zeilen werden weder geändert noch gelöscht.
|
||||
*
|
||||
* Nur die Datenbankfassade, damit spätere Änderungen an Modellen die Migration nicht berühren.
|
||||
*/
|
||||
final class LegacyPillarAdoption
|
||||
{
|
||||
/** @var array<string, array{table: string, column: string, subjects: string}> */
|
||||
private const TARGETS = [
|
||||
'composition' => ['table' => 'composition_pillar', 'column' => 'composition_id', 'subjects' => 'compositions'],
|
||||
'license_article' => ['table' => 'license_article_pillar', 'column' => 'license_article_id', 'subjects' => 'license_articles'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* mapping: list<array<string, mixed>>,
|
||||
* unresolved: list<array<string, mixed>>,
|
||||
* copied: array<string, int>,
|
||||
* already: array<string, int>,
|
||||
* before: array<string, int>,
|
||||
* after: array<string, int>,
|
||||
* mirror: array<string, int>
|
||||
* }
|
||||
*/
|
||||
public function run(bool $dryRun = false): array
|
||||
{
|
||||
$report = [
|
||||
'mapping' => [],
|
||||
'unresolved' => [],
|
||||
'copied' => ['composition' => 0, 'license_article' => 0],
|
||||
'already' => ['composition' => 0, 'license_article' => 0],
|
||||
'before' => $this->counts(),
|
||||
'after' => [],
|
||||
'mirror' => ['element_rows' => 0, 'missing_in_pivot' => 0, 'only_in_pivot' => 0],
|
||||
];
|
||||
|
||||
$dimension = DB::table('editorial_dimensions')->where('slug', 'saeule')->first();
|
||||
|
||||
if ($dimension === null) {
|
||||
$report['after'] = $report['before'];
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
$resolved = [];
|
||||
|
||||
foreach (DB::table('editorial_dimension_values')->where('editorial_dimension_id', $dimension->id)->orderBy('id')->get() as $value) {
|
||||
$pillar = $this->pillarFor($value);
|
||||
|
||||
if (is_string($pillar)) {
|
||||
$report['unresolved'][] = ['art' => 'Wert', 'wert_id' => (int) $value->id, 'wert' => $value->label, 'kennung' => $value->slug, 'grund' => $pillar];
|
||||
$report['mapping'][] = ['wert_id' => (int) $value->id, 'wert' => $value->label, 'saeule_id' => null, 'status' => 'offen'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$resolved[(int) $value->id] = (int) $pillar->id;
|
||||
$status = $value->pillar_id === null ? 'zugeordnet' : 'bereits zugeordnet';
|
||||
$hint = $value->label !== $pillar->name ? 'über Kennung zugeordnet, Bezeichnung weicht ab („'.$pillar->name.'“)' : null;
|
||||
$report['mapping'][] = ['wert_id' => (int) $value->id, 'wert' => $value->label, 'saeule_id' => (int) $pillar->id, 'saeule' => $pillar->name, 'status' => $status, 'hinweis' => $hint];
|
||||
|
||||
if ($value->pillar_id === null && ! $dryRun) {
|
||||
DB::table('editorial_dimension_values')->where('id', $value->id)->update(['pillar_id' => $pillar->id]);
|
||||
}
|
||||
}
|
||||
|
||||
$subjectTypes = $this->subjectTypes();
|
||||
|
||||
foreach (DB::table('identity_dimension_values')
|
||||
->whereIn('editorial_dimension_value_id', DB::table('editorial_dimension_values')->where('editorial_dimension_id', $dimension->id)->select('id'))
|
||||
->orderBy('id')->get() as $row) {
|
||||
$valueId = (int) $row->editorial_dimension_value_id;
|
||||
$label = DB::table('editorial_dimension_values')->where('id', $valueId)->value('label');
|
||||
$target = $subjectTypes[$row->subject_type] ?? null;
|
||||
|
||||
if ($target === 'content_element') {
|
||||
$report['mirror']['element_rows']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$where = ['art' => 'Zuordnung', 'zuordnung_id' => (int) $row->id, 'wert_id' => $valueId, 'wert' => $label, 'objektart' => $row->subject_type, 'objekt_id' => (int) $row->subject_id, 'herkunft' => $row->origin];
|
||||
|
||||
if ($target === null) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'unbekannte Objektart'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($row->origin !== 'direkt') {
|
||||
$report['unresolved'][] = $where + ['grund' => 'abgeleitete Zuordnung (wird nicht als direkte übernommen)'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! isset($resolved[$valueId])) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'Wert ohne belastbare Säule'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$config = self::TARGETS[$target];
|
||||
|
||||
if (! DB::table($config['subjects'])->where('id', $row->subject_id)->exists()) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'Objekt nicht mehr vorhanden'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$present = DB::table($config['table'])->where($config['column'], $row->subject_id)->where('pillar_id', $resolved[$valueId])->exists();
|
||||
|
||||
if ($present) {
|
||||
$report['already'][$target]++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $dryRun) {
|
||||
DB::table($config['table'])->insertOrIgnore([$config['column'] => $row->subject_id, 'pillar_id' => $resolved[$valueId]]);
|
||||
}
|
||||
|
||||
$report['copied'][$target]++;
|
||||
}
|
||||
|
||||
$report['mirror'] = array_merge($report['mirror'], $this->mirrorDivergence($dimension->id, $resolved));
|
||||
$report['after'] = $dryRun ? $report['before'] : $this->counts();
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $report
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function lines(array $report, bool $dryRun = false): array
|
||||
{
|
||||
$names = ['composition' => 'Module und Programme', 'license_article' => 'Lizenzartikel'];
|
||||
$lines = [$dryRun ? 'Probelauf, es wird nichts geschrieben.' : 'Übernahme abgeschlossen.', ''];
|
||||
|
||||
foreach ($report['mapping'] as $row) {
|
||||
$lines[] = sprintf('Wert %d „%s“ → %s%s', $row['wert_id'], $row['wert'], $row['saeule_id'] === null ? 'keine Säule (offen)' : 'Säule '.$row['saeule_id'].' „'.($row['saeule'] ?? '').'“ ('.$row['status'].')', ! empty($row['hinweis']) ? ' – '.$row['hinweis'] : '');
|
||||
}
|
||||
|
||||
$lines[] = '';
|
||||
|
||||
foreach ($names as $key => $label) {
|
||||
$lines[] = sprintf('%s: %d übernommen, %d bereits vorhanden, Zuordnungen vorher %d, nachher %d', $label, $report['copied'][$key], $report['already'][$key], $report['before'][$key], $report['after'][$key]);
|
||||
}
|
||||
|
||||
$lines[] = sprintf('Medien (nur Information): %d gespiegelte Zeilen, %d nicht mehr in der Medienzuordnung, %d nur dort. Maßgeblich bleibt die Medienzuordnung.', $report['mirror']['element_rows'], $report['mirror']['missing_in_pivot'], $report['mirror']['only_in_pivot']);
|
||||
|
||||
if ($report['unresolved'] === []) {
|
||||
$lines[] = 'Keine ungeklärten Fälle.';
|
||||
} else {
|
||||
$lines[] = '';
|
||||
$lines[] = 'Ungeklärt, bitte entscheiden (nichts wurde geändert):';
|
||||
|
||||
foreach ($report['unresolved'] as $row) {
|
||||
$lines[] = '- '.json_encode($row, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Säule zu einem alten Wert, oder der Grund, warum es keine belastbare gibt.
|
||||
*/
|
||||
private function pillarFor(object $value): object|string
|
||||
{
|
||||
if (preg_match('/^pfeiler-(\d+)$/', (string) $value->slug, $match) !== 1) {
|
||||
return 'Kennung ist nicht „pfeiler-<Nummer>“, keine belastbare Verknüpfung';
|
||||
}
|
||||
|
||||
$pillar = DB::table('pillars')->where('id', (int) $match[1])->first();
|
||||
|
||||
if ($pillar === null) {
|
||||
return 'Die Säule zur Kennung existiert nicht mehr';
|
||||
}
|
||||
|
||||
if ($value->pillar_id !== null && (int) $value->pillar_id !== (int) $pillar->id) {
|
||||
return 'Gespeicherte Verknüpfung (Säule '.$value->pillar_id.') und Kennung (Säule '.$pillar->id.') widersprechen sich';
|
||||
}
|
||||
|
||||
if ($pillar->created_at !== null && $value->created_at !== null && $pillar->created_at > $value->created_at) {
|
||||
return 'Die Säule ist jünger als der Wert; die Kennung kann nicht aus ihr entstanden sein';
|
||||
}
|
||||
|
||||
return $pillar;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> Objektart wie gespeichert => Ziel
|
||||
*/
|
||||
private function subjectTypes(): array
|
||||
{
|
||||
$types = [];
|
||||
|
||||
foreach ([
|
||||
'composition' => [Composition::class],
|
||||
'license_article' => [LicenseArticle::class],
|
||||
'content_element' => [ContentElement::class],
|
||||
] as $target => $classes) {
|
||||
foreach ($classes as $class) {
|
||||
$types[$class] = $target;
|
||||
$types[(new $class)->getMorphClass()] = $target;
|
||||
}
|
||||
}
|
||||
|
||||
return $types;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
private function counts(): array
|
||||
{
|
||||
return [
|
||||
'composition' => DB::table('composition_pillar')->count(),
|
||||
'license_article' => DB::table('license_article_pillar')->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $resolved
|
||||
* @return array{missing_in_pivot: int, only_in_pivot: int}
|
||||
*/
|
||||
private function mirrorDivergence(int $dimensionId, array $resolved): array
|
||||
{
|
||||
$mirrored = [];
|
||||
|
||||
foreach (DB::table('identity_dimension_values')
|
||||
->whereIn('subject_type', array_unique([ContentElement::class, (new ContentElement)->getMorphClass()]))
|
||||
->whereIn('editorial_dimension_value_id', array_keys($resolved) ?: [0])
|
||||
->get() as $row) {
|
||||
$mirrored[$row->subject_id.':'.$resolved[(int) $row->editorial_dimension_value_id]] = true;
|
||||
}
|
||||
|
||||
$pivot = [];
|
||||
|
||||
foreach (DB::table('content_element_pillar')->get() as $row) {
|
||||
$pivot[$row->content_element_id.':'.$row->pillar_id] = true;
|
||||
}
|
||||
|
||||
return [
|
||||
'missing_in_pivot' => count(array_diff_key($mirrored, $pivot)),
|
||||
'only_in_pivot' => count(array_diff_key($pivot, $mirrored)),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Berechtigter Nutzerkreis einer Lizenzoption: Einzellizenz (ein Trainer) oder Mehrfachlizenz (festgelegte Zahl von
|
||||
* Trainern). Das ist eine vertragliche Angabe der Lizenzoption. Sie ist unabhängig vom Lizenzinhaber (Person oder
|
||||
* Verein), vom technischen Downloadzugriff (nur das bestellende Konto) und vom Nutzungszweck (ehrenamtlich,
|
||||
* kommerziell, institutionell). Sie wird weder aus dem Zweck noch aus dem Preis abgeleitet.
|
||||
*/
|
||||
final class LicenceScope
|
||||
{
|
||||
public const SINGLE = 'einzel';
|
||||
|
||||
public const MULTI = 'mehrfach';
|
||||
|
||||
/** Obergrenze der Trainerzahl einer Mehrfachlizenz (Eingabeschutz). */
|
||||
public const MAX_TRAINERS = 999;
|
||||
|
||||
/**
|
||||
* @return array{0: ?string, 1: ?int} Nutzerkreis und Trainerzahl, geprüft und vereinheitlicht
|
||||
*/
|
||||
public static function normalise(?string $scope, mixed $trainers): array
|
||||
{
|
||||
$scope = filled($scope) ? (string) $scope : null;
|
||||
|
||||
if ($scope === null) {
|
||||
if (filled($trainers)) {
|
||||
throw new DomainRuleException('Die Trainerzahl gehört zu einer Einzel- oder Mehrfachlizenz. Wähle zuerst den Nutzerkreis.');
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
if ($scope === self::SINGLE) {
|
||||
if (filled($trainers) && (int) $trainers !== 1) {
|
||||
throw new DomainRuleException('Eine Einzellizenz gilt für genau einen Trainer.');
|
||||
}
|
||||
|
||||
return [self::SINGLE, 1];
|
||||
}
|
||||
|
||||
if ($scope === self::MULTI) {
|
||||
$count = filled($trainers) ? (int) $trainers : 0;
|
||||
|
||||
if ($count < 2 || $count > self::MAX_TRAINERS) {
|
||||
throw new DomainRuleException('Eine Mehrfachlizenz gilt für mindestens 2 und höchstens '.self::MAX_TRAINERS.' Trainer. Gib die Zahl der Trainer an.');
|
||||
}
|
||||
|
||||
return [self::MULTI, $count];
|
||||
}
|
||||
|
||||
throw new DomainRuleException('Der Nutzerkreis ist Einzellizenz oder Mehrfachlizenz.');
|
||||
}
|
||||
|
||||
/** Kurzform: „Einzellizenz · 1 Trainer“, „Mehrfachlizenz · bis zu 5 Trainer“ oder „keine Angabe“. */
|
||||
public static function label(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Einzellizenz · 1 Trainer',
|
||||
self::MULTI => 'Mehrfachlizenz · bis zu '.(int) $trainers.' Trainer',
|
||||
default => 'Nutzerkreis nicht festgelegt',
|
||||
};
|
||||
}
|
||||
|
||||
/** Erklärung für Käufer: was der Umfang bedeutet und was er nicht bedeutet. */
|
||||
public static function explanation(?string $scope, ?int $trainers): ?string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Die Inhalte dürfen von einem Trainer eingesetzt werden.',
|
||||
self::MULTI => 'Die Inhalte dürfen von bis zu '.(int) $trainers.' Trainern eingesetzt werden. Zugriff und Download erhält zum Start nur das bestellende Konto.',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Wert für Vergleich identischer Lizenzen („Bereits erworben“). */
|
||||
public static function key(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return ($scope ?? '-').'|'.($trainers ?? 0);
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public static function options(): array
|
||||
{
|
||||
return [
|
||||
self::SINGLE => 'Einzellizenz (ein Trainer)',
|
||||
self::MULTI => 'Mehrfachlizenz (mehrere Trainer)',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class LicenseArticle extends Model
|
||||
@@ -50,10 +49,4 @@ public function editorialContentKind(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EditorialContentKind::class);
|
||||
}
|
||||
|
||||
/** Direkt zugeordnete fachliche Säulen (zentrale Säulenverwaltung). */
|
||||
public function pillars(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Pillar::class)->orderBy('pillars.sort_order')->orderBy('pillars.name');
|
||||
}
|
||||
}
|
||||
@@ -3,37 +3,14 @@
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Offer extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'composition_id',
|
||||
'option_label',
|
||||
'standalone_bundle',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'standalone_bundle' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
/** Bezeichnung der Option auf der Produktseite. */
|
||||
public function optionName(): string
|
||||
{
|
||||
return filled($this->option_label) ? (string) $this->option_label : (string) $this->name;
|
||||
}
|
||||
|
||||
public function versions(): HasMany
|
||||
{
|
||||
return $this->hasMany(OfferVersion::class);
|
||||
|
||||
@@ -22,23 +22,6 @@ public function currentActiveVersion(Offer $offer): OfferVersion
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die aktive, als Kauf angebotene Fassung mit Preis; sonst null (nicht kaufbar, zurückgezogen oder kostenlos).
|
||||
*/
|
||||
public function purchasableVersion(Offer $offer): ?OfferVersion
|
||||
{
|
||||
$version = $offer->versions()
|
||||
->where('status', OfferStatus::Aktiv)
|
||||
->orderByDesc('number')
|
||||
->first();
|
||||
|
||||
if ($version === null || $version->grant_kind !== 'kauf' || $version->price_cents === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $capabilities
|
||||
* @param array<string, mixed> $options
|
||||
@@ -102,18 +85,10 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
'dynamic' => false,
|
||||
'grant_kind' => 'kauf',
|
||||
'holder_kind' => 'person',
|
||||
'licence_scope' => null,
|
||||
'trainer_count' => null,
|
||||
], $attributes);
|
||||
|
||||
if ($offer->standalone_bundle && (count($lines) !== 1 || ! $lines[0]['target'] instanceof BundleVersion)) {
|
||||
throw new DomainRuleException('Ein Angebot mit eigener Paketseite besteht aus genau einer Paketfassung. Wähle eine Paketfassung oder ordne das Angebot der Seite eines Programms zu.');
|
||||
}
|
||||
|
||||
$this->assertAttributes($attributes);
|
||||
[$attributes['licence_scope'], $attributes['trainer_count']] = LicenceScope::normalise($attributes['licence_scope'], $attributes['trainer_count']);
|
||||
$scope = $this->scopeFor($lines);
|
||||
$this->assertSellableContent($scope);
|
||||
$this->assertCoverage($lines, $attributes);
|
||||
|
||||
return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion {
|
||||
@@ -134,8 +109,6 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
'dynamic' => $attributes['dynamic'],
|
||||
'grant_kind' => $attributes['grant_kind'],
|
||||
'holder_kind' => $attributes['holder_kind'],
|
||||
'licence_scope' => $attributes['licence_scope'],
|
||||
'trainer_count' => $attributes['trainer_count'],
|
||||
]);
|
||||
|
||||
foreach (array_values($lines) as $index => $line) {
|
||||
@@ -165,45 +138,6 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Zieht die Option aus dem Verkauf zurück: Die aktive Fassung wird beendet und bleibt gespeichert. Bereits
|
||||
* begründete Berechtigungen und Bestellungen ändern sich nicht; offene Warenkörbe zeigen die Position als
|
||||
* zurückgezogen und blockieren den Abschluss, bis der Käufer sie entfernt.
|
||||
*/
|
||||
public function end(Offer $offer): OfferVersion
|
||||
{
|
||||
return DB::transaction(function () use ($offer): OfferVersion {
|
||||
$offer = Offer::query()->lockForUpdate()->findOrFail($offer->id);
|
||||
$version = $this->currentActiveVersion($offer);
|
||||
$version->status = OfferStatus::Beendet;
|
||||
$version->save();
|
||||
|
||||
return $version;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Produktzuordnung der Option: Die Komposition bestimmt die öffentliche Produktseite und die Alternativgruppe,
|
||||
* die Bezeichnung benennt die Option auf dieser Seite. Beides sind keine bindenden Konditionen.
|
||||
*/
|
||||
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel, bool $ownBundlePage = false): Offer
|
||||
{
|
||||
if ($compositionId !== null) {
|
||||
Composition::query()->findOrFail($compositionId);
|
||||
}
|
||||
|
||||
if ($ownBundlePage && $compositionId !== null) {
|
||||
throw new DomainRuleException('Ein Paket hat entweder eine eigene Paketseite oder die Seite eines Programms, nicht beides.');
|
||||
}
|
||||
|
||||
$offer->composition_id = $compositionId;
|
||||
$offer->standalone_bundle = $ownBundlePage;
|
||||
$offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null;
|
||||
$offer->save();
|
||||
|
||||
return $offer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<int>
|
||||
*/
|
||||
@@ -234,32 +168,6 @@ private function assertAttributes(array $attributes): void
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Angebot ohne verkaufbaren Inhalt wird nicht aktiviert: Jeder Lizenzartikel des Umfangs braucht einen
|
||||
* veröffentlichten Stand, sonst erhielten Käufer nichts. Die Prüfung liegt im Domänenmodell, nicht nur in der
|
||||
* Maske, damit auch jeder andere Weg (Skript, Import) sie durchläuft.
|
||||
*
|
||||
* @param list<array{license_article_id: int, rights_profile_version_id: int}> $scope
|
||||
*/
|
||||
private function assertSellableContent(array $scope): void
|
||||
{
|
||||
$ids = array_values(array_unique(array_column($scope, 'license_article_id')));
|
||||
$missing = LicenseArticle::query()->with('currentRelease')->whereIn('id', $ids)->orderBy('code')->get()
|
||||
->filter(fn (LicenseArticle $article): bool => ! ($article->currentRelease instanceof ArticleRelease
|
||||
&& StatusValue::of($article->currentRelease->status) === ReleaseStatus::Veroeffentlicht->value));
|
||||
|
||||
if ($missing->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$names = $missing->map(fn (LicenseArticle $article): string => '„'.($article->working_title ?: $article->code).'“ ('.$article->code.')')->implode(', ');
|
||||
|
||||
throw new DomainRuleException(($missing->count() === 1 ? 'Der Lizenzartikel ' : 'Die Lizenzartikel ').$names
|
||||
.($missing->count() === 1 ? ' hat' : ' haben')
|
||||
.' noch keinen veröffentlichten Stand und vergibt'.($missing->count() === 1 ? '' : ' keine').' keine Inhalte. '
|
||||
.'Lege zuerst am Artikel den Inhalt fest, bevor das Angebot aktiviert wird.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
||||
* @return list<array{license_article_id: int, rights_profile_version_id: int}>
|
||||
|
||||
@@ -19,8 +19,6 @@ class OfferVersion extends Model
|
||||
'dynamic',
|
||||
'grant_kind',
|
||||
'holder_kind',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'activated_at',
|
||||
];
|
||||
|
||||
|
||||
@@ -34,16 +34,6 @@ public function pages(): BelongsToMany
|
||||
return $this->belongsToMany(Page::class);
|
||||
}
|
||||
|
||||
public function compositions(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Composition::class);
|
||||
}
|
||||
|
||||
public function licenseArticles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(LicenseArticle::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Pillar> $query
|
||||
* @return Builder<Pillar>
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Alte Filteradressen: Vor der Vereinheitlichung war „Fachliche Säule“ ein Wert der redaktionellen Einordnung
|
||||
* (`?einordnung=…`, `?pillar=…`, `dimension[]=…`). Verweist ein solcher Wert über `pillar_id` auf eine zentrale Säule,
|
||||
* gilt der Filter jetzt für diese Säule, statt stillschweigend zu entfallen.
|
||||
*/
|
||||
final class PillarFilterCompat
|
||||
{
|
||||
/**
|
||||
* @return int|null|false Kennung der Säule; null: alter Säulenwert ohne belastbare Verknüpfung; false: kein Säulenwert
|
||||
*/
|
||||
public static function pillarOfLegacyValue(int $valueId): int|false|null
|
||||
{
|
||||
$row = DB::table('editorial_dimension_values')
|
||||
->join('editorial_dimensions', 'editorial_dimensions.id', '=', 'editorial_dimension_values.editorial_dimension_id')
|
||||
->where('editorial_dimension_values.id', $valueId)
|
||||
->where('editorial_dimensions.slug', EditorialDimension::PILLAR_SLUG)
|
||||
->first(['editorial_dimension_values.pillar_id']);
|
||||
|
||||
if ($row === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $row->pillar_id === null ? null : (int) $row->pillar_id;
|
||||
}
|
||||
}
|
||||
@@ -40,55 +40,19 @@ public function present(Pillar $pillar, string $name, string $slug, ?string $sum
|
||||
|
||||
public function delete(Pillar $pillar): void
|
||||
{
|
||||
$usage = $this->usage($pillar);
|
||||
|
||||
if (array_sum($usage) > 0) {
|
||||
throw new DomainRuleException('Eine Säule mit zugeordneten Objekten wird nicht gelöscht ('.$this->usageText($usage).'). Ordnen Sie sie zuerst anders zu.');
|
||||
if ($pillar->elements()->exists() || $pillar->pages()->exists()) {
|
||||
throw new DomainRuleException('Eine Säule mit zugeordneten Medien oder Seiten wird nicht gelöscht.');
|
||||
}
|
||||
|
||||
$pillar->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Zuordnungen je Objektart: Medien, Module und Programme, Lizenzartikel, Seiten.
|
||||
*
|
||||
* @return array{medien: int, zusammenstellungen: int, lizenzartikel: int, seiten: int}
|
||||
* @param list<int> $pillarIds
|
||||
*/
|
||||
public function usage(Pillar $pillar): array
|
||||
public function assign(ContentElement $element, array $pillarIds): void
|
||||
{
|
||||
return [
|
||||
'medien' => $pillar->elements()->count(),
|
||||
'zusammenstellungen' => $pillar->compositions()->count(),
|
||||
'lizenzartikel' => $pillar->licenseArticles()->count(),
|
||||
'seiten' => $pillar->pages()->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{medien: int, zusammenstellungen: int, lizenzartikel: int, seiten: int} $usage
|
||||
*/
|
||||
public function usageText(array $usage): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
foreach (['medien' => ['Medium', 'Medien'], 'zusammenstellungen' => ['Modul oder Programm', 'Module und Programme'], 'lizenzartikel' => ['Lizenzartikel', 'Lizenzartikel'], 'seiten' => ['Seite', 'Seiten']] as $key => [$one, $many]) {
|
||||
if ($usage[$key] > 0) {
|
||||
$parts[] = $usage[$key].' '.($usage[$key] === 1 ? $one : $many);
|
||||
}
|
||||
}
|
||||
|
||||
return $parts === [] ? 'nirgends zugeordnet' : implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordnet einem Medium, Modul, Programm, Lizenzartikel oder einer Seite Säulen zu. Alle Objektarten verwenden
|
||||
* dieselbe zentrale Säule und dieselbe Speicherregel; die Zuordnung ersetzt die bisherige vollständig.
|
||||
*
|
||||
* @param list<int|string> $pillarIds
|
||||
*/
|
||||
public function assign(ContentElement|Composition|LicenseArticle|Page $subject, array $pillarIds): void
|
||||
{
|
||||
$subject->pillars()->sync($this->ids($pillarIds));
|
||||
$element->pillars()->sync($this->ids($pillarIds));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,7 +60,7 @@ public function assign(ContentElement|Composition|LicenseArticle|Page $subject,
|
||||
*/
|
||||
public function assignPages(Page $page, array $pillarIds): void
|
||||
{
|
||||
$this->assign($page, $pillarIds);
|
||||
$page->pillars()->sync($this->ids($pillarIds));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
* Redaktionsvorschau (Route editorial.card, nur für angemeldete Redaktion); öffentlich nie ausgegeben, weil es
|
||||
* keine Freigabe für die Website hat.
|
||||
* - missing: was für eine vollständige Karte fehlt, als Hinweis nur in der Redaktionsvorschau.
|
||||
* - texts: die zentralen Texte des Fachobjekts, aus denen die Karte einen wählen kann (teaser, summary, description).
|
||||
* summary bleibt der Text der Vorgabe („Automatisch“); texts wird nur gelesen, wenn die Redaktion einen wählt.
|
||||
*/
|
||||
final readonly class CardSubject
|
||||
{
|
||||
@@ -38,39 +36,24 @@ public function __construct(
|
||||
public ?string $previewImage = null,
|
||||
public array $missing = [],
|
||||
public ?string $style = null,
|
||||
public array $texts = [],
|
||||
) {}
|
||||
|
||||
public function withText(?string $title, ?string $summary): self
|
||||
{
|
||||
return $this->copy(['title' => $title ?? $this->title, 'summary' => $summary ?? $this->summary]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Text der Karte aus einem zentralen Text des Fachobjekts. Ist er nicht gepflegt, bleibt die Karte ohne Text
|
||||
* (kein stiller Ersatz aus einem anderen Feld); in der Redaktionsvorschau steht dann ein Hinweis.
|
||||
*/
|
||||
public function withTextChoice(string $field, string $missingHint): self
|
||||
{
|
||||
if (! array_key_exists($field, $this->texts)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$text = $this->texts[$field];
|
||||
$missing = array_values(array_filter($this->missing, fn (string $hint): bool => ! str_contains($hint, 'Kurzbeschreibung')));
|
||||
|
||||
if ($text === null) {
|
||||
$missing[] = $missingHint;
|
||||
}
|
||||
|
||||
return $this->copy(['summary' => $text, 'missing' => $missing]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $changes
|
||||
*/
|
||||
private function copy(array $changes): self
|
||||
{
|
||||
return new self(...array_merge(get_object_vars($this), $changes));
|
||||
return new self(
|
||||
title: $title ?? $this->title,
|
||||
summary: $summary ?? $this->summary,
|
||||
kind: $this->kind,
|
||||
badge: $this->badge,
|
||||
meta: $this->meta,
|
||||
url: $this->url,
|
||||
public: $this->public,
|
||||
notice: $this->notice,
|
||||
visual: $this->visual,
|
||||
visualLabel: $this->visualLabel,
|
||||
previewImage: $this->previewImage,
|
||||
missing: $this->missing,
|
||||
style: $this->style,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -265,13 +265,6 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
|
||||
$profile = app(EditorialProfileReader::class)->read($composition, 'kachel');
|
||||
$summary = $profile->value('teaser') ?: $profile->value('summary');
|
||||
$goal = filled($version?->learning_goal) ? trim((string) $version->learning_goal) : null;
|
||||
// Zentrale Texte, aus denen die Redaktion den Kartentext wählen kann (Zielgruppe „Öffentliche Kachel“).
|
||||
$texts = [
|
||||
'teaser' => $profile->value('teaser'),
|
||||
'summary' => $profile->value('summary'),
|
||||
'description' => $profile->value('description'),
|
||||
'goal' => $goal,
|
||||
];
|
||||
$missing = [];
|
||||
|
||||
if ($summary === null) {
|
||||
@@ -320,7 +313,6 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
|
||||
visualLabel: $kind,
|
||||
previewImage: $includeNonPublic ? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path) : null,
|
||||
missing: $missing,
|
||||
texts: $texts,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,13 +8,11 @@
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
|
||||
/**
|
||||
* Lesesicht „Medien und Materialien“ für Premium-Karten (Website-CMS-Zielarchitektur 6.2).
|
||||
*
|
||||
* Auswahl in der Redaktion: jedes nicht archivierte Inhaltselement mit mindestens einer nicht gesperrten Fassung, dazu
|
||||
* jeder Film, der nur aus einer Website-Datei besteht (Medium ohne Inhaltsfassung, z. B. ein Teaser).
|
||||
* Auswahl in der Redaktion: jedes nicht archivierte Inhaltselement mit mindestens einer nicht gesperrten Fassung.
|
||||
*
|
||||
* Öffentliche Sichtbarkeit (Übergangsregel, solange öffentliche Fachobjektprofile nach ADR-29 fehlen):
|
||||
* Ein Medium hat keine eigene öffentliche Seite. Öffentlich genannt wird es heute nur als Bestandteil der gezeigten
|
||||
@@ -22,17 +20,10 @@
|
||||
* öffentlich, mit Verweis auf diese Programmseite, und nur mit bereitgestellter Fassung. Traineranleitungen erscheinen
|
||||
* nie öffentlich (vertraulich für Trainerinnen und Trainer).
|
||||
*
|
||||
* Ein Film nur mit Website-Datei hat weder Fassung noch Programm. Er erscheint öffentlich, sobald seine Website-Datei
|
||||
* für die Website freigegeben ist (die Freigabe ist die ausdrückliche Entscheidung der Redaktion), ohne Verweis auf
|
||||
* eine Programmseite und damit ohne Aktion. Ohne Freigabe bleibt er auf die Redaktionsvorschau beschränkt.
|
||||
*
|
||||
* Öffentlich gelesen werden Anzeigetitel (sonst Arbeitstitel), Inhaltsart und Ausgabeart sowie einer der Texte
|
||||
* Teaser, Kurzbeschreibung oder ausführliche Beschreibung. Welcher Text erscheint, entscheidet die Redaktion je Karte
|
||||
* (Einstellung „Text der Karte“); ohne Wahl gilt die Kurzbeschreibung, sonst der Teaser. Die ausführliche Beschreibung
|
||||
* erscheint nur, wenn die Redaktion sie ausdrücklich wählt. Nie: Einsatzhinweis, Lizenzvermerk, Dateien, Lehrtexte,
|
||||
* Ausgabeadressen. Das Vorschaubild der Bibliothek ist nicht für die Website freigegeben; es erscheint nur in der
|
||||
* Redaktionsvorschau und kann in der Karte ausdrücklich als Website-Bild übernommen werden (FilmStill).
|
||||
* Eine Karte spielt höchstens den für die Website freigegebenen Trailer ab (CardClip), bietet keinen Download und gibt kein Medium frei.
|
||||
* Öffentlich gelesen werden Anzeigetitel (sonst Arbeitstitel), Kurzbeschreibung, Inhaltsart und Ausgabeart. Nie:
|
||||
* Beschreibung, Einsatzhinweis, Lizenzvermerk, Dateien, Lehrtexte, Ausgabeadressen. Das Vorschaubild (Filmstandbild)
|
||||
* der Bibliothek ist nicht für die Website freigegeben; es erscheint nur in der Redaktionsvorschau.
|
||||
* Eine Karte spielt nichts ab, bietet keinen Download und gibt kein Medium frei.
|
||||
*/
|
||||
class PublicMaterialReader
|
||||
{
|
||||
@@ -50,36 +41,14 @@ public function __construct(
|
||||
public function isSelectable(ContentElement $element): bool
|
||||
{
|
||||
return $element->archived_at === null
|
||||
&& ($element->versions()->where('status', '!=', ContentVersionStatus::Gesperrt->value)->exists()
|
||||
|| $this->isWebsiteOnlyFilm($element));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Film ohne jede Inhaltsfassung, der nur die Website-Datei (`teaser/…`) hat, zum Beispiel ein Teaser. Er kann
|
||||
* auf der Medienkarte gewählt werden; was daraus öffentlich wird, bestimmt allein die Freigabe der Datei.
|
||||
*/
|
||||
public function isWebsiteOnlyFilm(ContentElement $element): bool
|
||||
{
|
||||
return $element->output_class === 'film'
|
||||
&& filled($element->preview_path)
|
||||
&& ! $element->versions()->exists();
|
||||
&& $element->versions()->where('status', '!=', ContentVersionStatus::Gesperrt->value)->exists();
|
||||
}
|
||||
|
||||
public function isReady(ContentElement $element): bool
|
||||
{
|
||||
if ($this->isWebsiteOnlyFilm($element)) {
|
||||
return $this->isWebsiteReleased($element);
|
||||
}
|
||||
|
||||
return $element->versions()->where('status', ContentVersionStatus::Bereit->value)->exists();
|
||||
}
|
||||
|
||||
/** Die Website-Datei des Films ist freigegeben und wird tatsächlich ausgeliefert (WebsiteMedia). */
|
||||
private function isWebsiteReleased(ContentElement $element): bool
|
||||
{
|
||||
return app(WebsiteMedia::class)->present($element)?->kind === 'film';
|
||||
}
|
||||
|
||||
/**
|
||||
* Öffentliches Programm, in dessen gezeigter Fassung das Element vorkommt, sonst null.
|
||||
*
|
||||
@@ -95,7 +64,7 @@ public function isPublic(ContentElement $element): bool
|
||||
return $this->isSelectable($element)
|
||||
&& $this->isReady($element)
|
||||
&& ! in_array($element->editorialContentKind?->slug, self::CONFIDENTIAL_KINDS, true)
|
||||
&& ($this->publicProgramFor($element) !== null || $this->isWebsiteOnlyFilm($element));
|
||||
&& $this->publicProgramFor($element) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -108,13 +77,7 @@ public function search(?string $term, int $limit = 25): array
|
||||
$candidates = ContentElement::query()
|
||||
->with('editorialContentKind')
|
||||
->whereNull('archived_at')
|
||||
->where(fn ($selectable) => $selectable
|
||||
->whereHas('versions', fn ($query) => $query->where('status', '!=', ContentVersionStatus::Gesperrt->value))
|
||||
->orWhere(fn ($websiteOnly) => $websiteOnly
|
||||
->where('output_class', 'film')
|
||||
->whereNotNull('preview_path')
|
||||
->where('preview_path', '!=', '')
|
||||
->whereDoesntHave('versions')))
|
||||
->whereHas('versions', fn ($query) => $query->where('status', '!=', ContentVersionStatus::Gesperrt->value))
|
||||
->when($term !== '', function ($query) use ($term): void {
|
||||
$like = '%'.mb_strtolower($term).'%';
|
||||
$query->where(fn ($inner) => $inner
|
||||
@@ -161,7 +124,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
|
||||
$shown = clone $element;
|
||||
|
||||
foreach (['working_title', 'display_title', 'teaser', 'summary', 'description', 'thumbnail_path', 'thumbnail_alt'] as $field) {
|
||||
foreach (['working_title', 'display_title', 'summary', 'thumbnail_path', 'thumbnail_alt'] as $field) {
|
||||
if (! array_key_exists($field, $draft)) {
|
||||
continue;
|
||||
}
|
||||
@@ -183,30 +146,17 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
$summary = trim((string) $shown->teaser);
|
||||
}
|
||||
|
||||
$texts = [];
|
||||
|
||||
foreach (['teaser', 'summary', 'description'] as $field) {
|
||||
$own = filled($shown->getAttribute($field)) ? trim((string) $shown->getAttribute($field)) : null;
|
||||
|
||||
if (! array_key_exists($field, $draft) && $profile->origin($field) === 'variante') {
|
||||
$own = $profile->value($field);
|
||||
}
|
||||
|
||||
$texts[$field] = $own;
|
||||
}
|
||||
|
||||
$title = (string) ($shown->display_title ?: $shown->working_title);
|
||||
|
||||
if (! array_key_exists('display_title', $draft) && $profile->origin('display_title') === 'variante') {
|
||||
$title = (string) $profile->value('display_title');
|
||||
}
|
||||
|
||||
$websiteOnly = $this->isWebsiteOnlyFilm($element);
|
||||
$meta = [$output];
|
||||
if ($program !== null) {
|
||||
$meta[] = 'Im Programm „'.$program['title'].'“';
|
||||
}
|
||||
if ($film && ! $websiteOnly) {
|
||||
if ($film) {
|
||||
$meta[] = 'Vollständiger Film nur mit Lizenz im Mitgliederbereich';
|
||||
}
|
||||
|
||||
@@ -234,7 +184,6 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
previewImage: $previewImage,
|
||||
missing: $missing,
|
||||
style: $film ? 'media' : 'material',
|
||||
texts: $texts,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -255,11 +204,7 @@ public function visibilityNote(ContentElement $element): string
|
||||
if ($this->isPublic($element)) {
|
||||
$program = $this->publicProgramFor($element);
|
||||
|
||||
if ($program === null) {
|
||||
return 'Öffentlich mit der für die Website freigegebenen Datei, ohne Verweis auf eine Programmseite. Die Originaldatei wird nie ausgeliefert.';
|
||||
}
|
||||
|
||||
return 'Öffentlich nur als Teil der Programmseite „'.$program['title'].'“. Die Mediendatei wird dabei nicht ausgeliefert.';
|
||||
return 'Öffentlich nur als Teil der Programmseite „'.($program['title'] ?? '').'“. Die Mediendatei wird dabei nicht ausgeliefert.';
|
||||
}
|
||||
|
||||
return $this->notice($element, $this->publicProgramFor($element));
|
||||
@@ -272,7 +217,6 @@ private function notice(ContentElement $element, ?array $program): string
|
||||
{
|
||||
$reason = match (true) {
|
||||
in_array($element->editorialContentKind?->slug, self::CONFIDENTIAL_KINDS, true) => 'Traineranleitungen erscheinen nie öffentlich.',
|
||||
$this->isWebsiteOnlyFilm($element) => 'Die Website-Datei ist nicht für die Website freigegeben (Medium öffnen → Reiter „Website“ → freigeben).',
|
||||
! $this->isReady($element) => 'Das Medium hat noch keine bereitgestellte Fassung.',
|
||||
$program === null => 'Das Medium gehört zu keinem öffentlich gezeigten Programm. Medien haben noch keine eigene öffentliche Freigabe (öffentliches Profil, ADR-29).',
|
||||
default => 'Das Medium ist nicht öffentlich.',
|
||||
@@ -283,14 +227,9 @@ private function notice(ContentElement $element, ?array $program): string
|
||||
|
||||
private function optionLabel(ContentElement $element): string
|
||||
{
|
||||
$visibility = match (true) {
|
||||
$this->isWebsiteOnlyFilm($element) => $this->isPublic($element)
|
||||
? 'öffentlich mit Website-Datei'
|
||||
: 'Website-Datei nicht freigegeben, nur Redaktionsvorschau',
|
||||
$this->isPublic($element) => 'öffentlich über Programmseite',
|
||||
$this->isReady($element) => 'nur Redaktionsvorschau',
|
||||
default => 'Entwurf, nur Redaktionsvorschau',
|
||||
};
|
||||
$visibility = $this->isPublic($element)
|
||||
? 'öffentlich über Programmseite'
|
||||
: ($this->isReady($element) ? 'nur Redaktionsvorschau' : 'Entwurf, nur Redaktionsvorschau');
|
||||
$kind = $element->editorialContentKind?->label ?: self::outputLabel((string) $element->output_class);
|
||||
|
||||
return (string) ($element->display_title ?: $element->working_title).' · '.$kind.' · '.$visibility;
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Support;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\PresentationAssignment;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Der kurze Clip, den eine Premium-Karte beim Überfahren oder Antippen abspielt.
|
||||
*
|
||||
* Gelesen wird nur, was die Redaktion ohnehin für die Website freigegeben hat (WebsiteMedia, Route website.media):
|
||||
* 1. der Trailer des Fachobjekts (Präsentationsrolle „Trailer“), sonst der Vorschauclip,
|
||||
* 2. bei einem Film ersatzweise dessen eigener freigegebener Teaser.
|
||||
* Der vollständige Film, die Originaldatei und nicht freigegebene Clips kommen nie über die Karte. Die Karte gibt
|
||||
* nichts frei; ohne freigegebenen Clip bleibt es beim Kartenbild.
|
||||
*
|
||||
* In der Redaktionsvorschau erklärt `notice`, warum kein Clip läuft (zugeordnet, aber nicht freigegeben).
|
||||
*/
|
||||
class CardClip
|
||||
{
|
||||
/** Rollen in der Reihenfolge, in der ein Clip gesucht wird. */
|
||||
public const ROLES = ['trailer', 'vorschauclip'];
|
||||
|
||||
public function __construct(private readonly WebsiteMedia $media) {}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, source: string, notice: string|null, hint: string|null}
|
||||
*/
|
||||
public function for(Model $subject, bool $preview): array
|
||||
{
|
||||
$assigned = PresentationAssignment::query()
|
||||
->with(['role', 'element'])
|
||||
->where('subject_type', $subject->getMorphClass())
|
||||
->where('subject_id', $subject->getKey())
|
||||
->whereHas('role', fn ($query) => $query->whereIn('slug', self::ROLES))
|
||||
->orderBy('position')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->sortBy(fn (PresentationAssignment $row): int => (int) array_search($row->role?->slug, self::ROLES, true))
|
||||
->values();
|
||||
|
||||
$unreleased = null;
|
||||
|
||||
foreach ($assigned as $assignment) {
|
||||
$element = $assignment->element;
|
||||
|
||||
if (! $element instanceof ContentElement || $element->archived_at !== null || $element->output_class !== 'film') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$present = $this->media->present($element);
|
||||
|
||||
if ($present !== null && $present->kind === 'film') {
|
||||
return $this->found($present->url, $present->title, $assignment->role?->slug === 'trailer' ? 'trailer' : 'vorschauclip');
|
||||
}
|
||||
|
||||
$unreleased ??= $element;
|
||||
}
|
||||
|
||||
if ($subject instanceof ContentElement && $subject->output_class === 'film') {
|
||||
$own = $this->media->present($subject);
|
||||
|
||||
if ($own !== null && $own->kind === 'film') {
|
||||
return $this->found($own->url, $own->title, 'teaser');
|
||||
}
|
||||
}
|
||||
|
||||
if (! $preview) {
|
||||
return $this->none();
|
||||
}
|
||||
|
||||
if ($unreleased instanceof ContentElement) {
|
||||
$title = (string) ($unreleased->display_title ?: $unreleased->working_title);
|
||||
|
||||
return $this->none('Der Trailer „'.$title.'“ ist nicht für die Website freigegeben; öffentlich bleibt es beim Kartenbild (Medium öffnen → Reiter „Website“ → freigeben).');
|
||||
}
|
||||
|
||||
return $this->none(null, 'Kein Trailer zugeordnet; die Karte zeigt nur das Bild (Rolle „Trailer“ in der Präsentation des Mediums).');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, source: string, notice: string|null, hint: string|null}
|
||||
*/
|
||||
private function found(string $url, string $title, string $source): array
|
||||
{
|
||||
return ['url' => $url, 'title' => $title, 'source' => $source, 'notice' => null, 'hint' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, source: string, notice: string|null, hint: string|null}
|
||||
*/
|
||||
private function none(?string $notice = null, ?string $hint = null): array
|
||||
{
|
||||
return ['url' => null, 'title' => '', 'source' => 'none', 'notice' => $notice, 'hint' => $hint];
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Support;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
|
||||
/**
|
||||
* Das Video des Einstiegs (Hero): ein stummer Clip auf der Fläche des Fotos.
|
||||
*
|
||||
* Gewählt wird ein Film aus dem Medienmanager. Abgespielt wird nur, was die Redaktion für die Website freigegeben hat,
|
||||
* und zwar nach derselben Regel wie auf der Karte (CardClip): Trailer des Films, sonst sein Vorschauclip, sonst seine
|
||||
* eigene freigegebene Website-Datei. Der vollständige Film, die Originaldatei und nicht freigegebene Clips kommen nie
|
||||
* über den Einstieg. Ohne freigegebenen Clip bleibt es beim Foto; die Auswahl gibt nichts frei.
|
||||
*/
|
||||
final class HeroVideo
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CardClip $clips,
|
||||
private readonly PublicMaterialReader $materials,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Auswahlliste: Filme, die auf der Website gezeigt werden dürfen, mit dem Stand ihrer Freigabe.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function options(?string $term, int $limit = 25): array
|
||||
{
|
||||
$term = trim((string) $term);
|
||||
|
||||
$candidates = ContentElement::query()
|
||||
->with('editorialContentKind')
|
||||
->where('output_class', 'film')
|
||||
->whereNull('archived_at')
|
||||
->when($term !== '', function ($query) use ($term): void {
|
||||
$like = '%'.mb_strtolower($term).'%';
|
||||
$query->where(fn ($inner) => $inner
|
||||
->whereRaw('LOWER(working_title) LIKE ?', [$like])
|
||||
->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like]));
|
||||
})
|
||||
->orderBy('working_title')
|
||||
->limit($limit * 2)
|
||||
->get();
|
||||
|
||||
$options = [];
|
||||
|
||||
foreach ($candidates as $element) {
|
||||
if (! $this->allowed($element)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$options[$element->id] = $this->label($element);
|
||||
|
||||
if (count($options) >= $limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
public function labelFor(mixed $id): ?string
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
return $element instanceof ContentElement ? $this->label($element) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die gewählte Kennung. Gibt die Kennung zurück oder null, wenn keine gewählt ist oder die Wahl ungültig ist.
|
||||
*/
|
||||
public function clean(mixed $value, WidgetErrors $errors, string $key = 'refs.video'): ?int
|
||||
{
|
||||
if ($value === null || $value === '' || $value === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$element = is_numeric($value) ? ContentElement::query()->with('editorialContentKind')->find((int) $value) : null;
|
||||
|
||||
if (! $element instanceof ContentElement || ! $this->allowed($element)) {
|
||||
$errors->add($key, 'Bitte einen Film aus dem Medienmanager wählen (nicht archiviert, nicht gesperrt, keine Traineranleitung).');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $element->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, notice: string|null}
|
||||
*/
|
||||
public function resolve(mixed $id, bool $preview): array
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
if (! $element instanceof ContentElement) {
|
||||
return ['url' => null, 'title' => '', 'notice' => null];
|
||||
}
|
||||
|
||||
$title = (string) ($element->display_title ?: $element->working_title);
|
||||
|
||||
if (! $this->allowed($element)) {
|
||||
return ['url' => null, 'title' => $title, 'notice' => $preview ? 'Das gewählte Medium „'.$title.'“ ist archiviert oder gesperrt; es erscheint kein Video.' : null];
|
||||
}
|
||||
|
||||
$clip = $this->clips->for($element, $preview);
|
||||
|
||||
if ($clip['url'] !== null) {
|
||||
return ['url' => $clip['url'], 'title' => $clip['title'] !== '' ? $clip['title'] : $title, 'notice' => null];
|
||||
}
|
||||
|
||||
return [
|
||||
'url' => null,
|
||||
'title' => $title,
|
||||
'notice' => $preview
|
||||
? 'Für „'.$title.'“ gibt es kein für die Website freigegebenes Video (Trailer, Vorschauclip oder freigegebene Website-Datei des Mediums); öffentlich bleibt es beim Foto. Freigabe: Medium öffnen → Reiter „Website“.'
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
/** Ein Film, der nicht archiviert, nicht gesperrt und keine Traineranleitung ist. */
|
||||
private function allowed(ContentElement $element): bool
|
||||
{
|
||||
return $element->output_class === 'film'
|
||||
&& $this->materials->isSelectable($element)
|
||||
&& ! in_array($element->editorialContentKind?->slug, PublicMaterialReader::CONFIDENTIAL_KINDS, true);
|
||||
}
|
||||
|
||||
private function label(ContentElement $element): string
|
||||
{
|
||||
$state = $this->clips->for($element, false)['url'] !== null ? 'Video freigegeben' : 'noch kein freigegebenes Video';
|
||||
|
||||
return (string) ($element->display_title ?: $element->working_title).' · '.$state;
|
||||
}
|
||||
}
|
||||
@@ -127,10 +127,6 @@ public function url(mixed $value, bool $preview = false): ?string
|
||||
|
||||
$legacy = self::normalize($value);
|
||||
|
||||
if (is_string($legacy) && WebsiteMediaAlias::isRetired($legacy)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return is_string($legacy) ? PublicMedia::url($legacy) : null;
|
||||
}
|
||||
|
||||
@@ -179,10 +175,6 @@ public function status(mixed $value): ?array
|
||||
|
||||
$id = $this->elementId($value);
|
||||
|
||||
if ($id === null && WebsiteMediaAlias::isRetired($value)) {
|
||||
return ['public' => false, 'state' => 'missing', 'title' => basename((string) $value), 'note' => 'Das Medium wurde gelöscht.', 'thumb' => null, 'manageUrl' => null];
|
||||
}
|
||||
|
||||
if ($id === null) {
|
||||
return [
|
||||
'public' => true,
|
||||
|
||||
@@ -3,14 +3,12 @@
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeroVideo;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Components\Group;
|
||||
@@ -22,10 +20,6 @@
|
||||
* Containerbreite), Label, Überschriftenebene, Bildfokus in Prozent, Akzent, zwei Schaltflächen.
|
||||
* Die data-Schlüssel der Version 1 (heading, text, cta_*, alt) bleiben unverändert, damit ältere Revisionen und ein
|
||||
* Code-Rollback darstellbar bleiben.
|
||||
*
|
||||
* Optional ein Video (refs.video, ein Film aus dem Medienmanager): In der Variante „Foto mit Textfläche“ läuft ein
|
||||
* stummer, für die Website freigegebener Clip auf der Fläche des Fotos (HeroVideo, resources/js/hero-video.js). Neuer
|
||||
* Schlüssel ohne Versionssprung; ältere Revisionen ohne `video` bleiben unverändert darstellbar.
|
||||
*/
|
||||
class HeroWidget extends WidgetType
|
||||
{
|
||||
@@ -70,9 +64,9 @@ public function narrowBehavior(): string
|
||||
public function heights(): array
|
||||
{
|
||||
return [
|
||||
'compact' => 'Kompakt (niedriger, 75 % der Standardhöhe)',
|
||||
'normal' => 'Standard',
|
||||
'large' => 'Großzügig (höher, 130 % der Standardhöhe)',
|
||||
'compact' => 'Kompakt (mind. 400 px)',
|
||||
'normal' => 'Normal (mind. 512 px)',
|
||||
'large' => 'Groß (mind. 640 px)',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -115,18 +109,10 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['accent'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
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).'],
|
||||
'heading_level' => ['Überschriftenebene', 'Der erste Einstieg einer Seite ist immer die Hauptüberschrift (H1).'],
|
||||
'accent' => ['Markenakzent', 'Freigegebene Akzente aus dem Brand-UI-Kit. Vorgabe: gelbe Unterstreichung.'],
|
||||
];
|
||||
}
|
||||
@@ -166,7 +152,7 @@ public function dataRules(): array
|
||||
|
||||
public function refRules(): array
|
||||
{
|
||||
return ImageRefFields::rules() + ['video' => ['nullable']];
|
||||
return ImageRefFields::rules();
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
@@ -183,19 +169,7 @@ public function dataFields(): array
|
||||
|
||||
public function refFields(): array
|
||||
{
|
||||
return [...ImageRefFields::fields(live: true), $this->videoField()];
|
||||
}
|
||||
|
||||
private function videoField(): Select
|
||||
{
|
||||
return Select::make('video')
|
||||
->label('Video (optional)')
|
||||
->helperText('Ein Film aus dem Medienmanager. Läuft stumm auf der Fläche des Fotos, nur in der Variante „Foto mit Textfläche“ und nur, wenn ein Trailer, Vorschauclip oder die Website-Datei des Films für die Website freigegeben ist. Das Foto bleibt als Rückfall, bei „reduzierte Bewegung“ und im Datensparmodus startet das Video nur auf Wunsch. Die Auswahl gibt nichts frei.')
|
||||
->live()
|
||||
->searchable()
|
||||
->getSearchResultsUsing(fn (?string $search): array => app(HeroVideo::class)->options($search))
|
||||
->getOptionLabelUsing(fn (mixed $value): ?string => app(HeroVideo::class)->labelFor($value))
|
||||
->options(fn (): array => app(HeroVideo::class)->options(null));
|
||||
return ImageRefFields::fields(live: true);
|
||||
}
|
||||
|
||||
public function editorSchema(): array
|
||||
@@ -218,8 +192,6 @@ public function mediaSchema(): array
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
$refs = ImageRefFields::clean($refs, $errors);
|
||||
$video = app(HeroVideo::class)->clean($refs['video'] ?? null, $errors);
|
||||
$video === null ? $refs = array_diff_key($refs, ['video' => true]) : $refs['video'] = $video;
|
||||
$data['heading'] = trim((string) ($data['heading'] ?? ''));
|
||||
$data['text'] = filled($data['text'] ?? null) ? trim((string) $data['text']) : null;
|
||||
$data = PremiumFields::clean($data, $errors, $refs['image'] !== null);
|
||||
@@ -233,15 +205,8 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
|
||||
$images = app(WebsiteImage::class);
|
||||
$image = $widget['refs']['image'] ?? null;
|
||||
$video = app(HeroVideo::class)->resolve($widget['refs']['video'] ?? null, $context->preview);
|
||||
$photoSplit = ($widget['variant'] ?? 'photo_split') !== 'editorial_solid';
|
||||
|
||||
if (! $photoSplit && $video['title'] !== '') {
|
||||
$video = ['url' => null, 'title' => $video['title'], 'notice' => $context->preview ? 'Das Video erscheint nur in der Variante „Foto mit Textfläche“; die Markenfläche zeigt kein Video.' : null];
|
||||
}
|
||||
|
||||
return [
|
||||
'video' => $video,
|
||||
'imageUrl' => $images->url($image, $context->preview),
|
||||
'imageAlt' => $images->alt($image, $widget['data']['alt'] ?? null),
|
||||
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
|
||||
|
||||
@@ -73,7 +73,7 @@ public function heights(): array
|
||||
{
|
||||
return [
|
||||
'compact' => 'Kompakt (flacheres Bild, engere Abstände)',
|
||||
'normal' => 'Standard',
|
||||
'normal' => 'Normal',
|
||||
'spacious' => 'Großzügig (höheres Bild, mehr Abstand)',
|
||||
];
|
||||
}
|
||||
@@ -117,19 +117,11 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['surface'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'],
|
||||
'heading_level' => ['Überschriftenebene', '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.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Steht das Widget als erstes auf der Seite, ist die Überschrift immer H1.'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -7,17 +7,12 @@
|
||||
use App\Domain\Cms\Catalog\CardSubject;
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Media\FilmStill;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use Filament\Forms\Components\ViewField;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Medien- und Materialkarte (Kit v1.7 „media“): ein Inhaltselement mit Anzeigetitel, Kurzbeschreibung, Inhaltsart und
|
||||
* Ausgabeart. Filme erscheinen als Medienkarte (grüne Aktion, Filmtafel ohne freigegebenes Bild), Dokumente und andere
|
||||
* Materialien als Materialkarte (Materialsymbol). Öffentlich nur nach den Regeln von PublicMaterialReader; die Aktion
|
||||
* führt auf die öffentliche Programmseite. Die Karte spielt höchstens den für die Website freigegebenen Trailer ab (CardClip), bietet keinen Download und gibt kein Medium frei.
|
||||
* führt auf die öffentliche Programmseite. Die Karte spielt nichts ab, bietet keinen Download und gibt kein Medium frei.
|
||||
*/
|
||||
class MediaCardWidget extends PremiumCardWidget
|
||||
{
|
||||
@@ -33,7 +28,7 @@ public function label(): string
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Karte zu einem Film oder Material aus der Bibliothek; Titel und Art kommen aus den Fachdaten, Trailer nur wenn freigegeben, kein Download.';
|
||||
return 'Karte zu einem Film oder Material aus der Bibliothek; Titel und Art kommen aus den Fachdaten, kein Abspielen, kein Download.';
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
@@ -58,7 +53,7 @@ protected function refLabel(): string
|
||||
|
||||
protected function refHelp(): string
|
||||
{
|
||||
return 'Wählbar sind alle nicht archivierten, nicht gesperrten Filme und Materialien. Öffentlich erscheint die Karte nur mit bereitgestellter Fassung und wenn der Inhalt zu einem öffentlich gezeigten Programm gehört; ein Film nur mit Website-Datei (zum Beispiel ein Teaser) erscheint, sobald diese Datei für die Website freigegeben ist. Traineranleitungen nie. Titel, Teaser, Kurzbeschreibung und Beschreibung pflegen Sie im Medium; welcher Text auf der Karte erscheint, wählen Sie unter „Darstellung“.';
|
||||
return 'Wählbar sind alle nicht archivierten, nicht gesperrten Filme und Materialien. Öffentlich erscheint die Karte nur mit bereitgestellter Fassung und wenn der Inhalt zu einem öffentlich gezeigten Programm gehört; Traineranleitungen nie. Titel und Kurzbeschreibung pflegen Sie im Medium.';
|
||||
}
|
||||
|
||||
protected function searchSubjects(?string $term): array
|
||||
@@ -95,80 +90,6 @@ protected function cardStyle(): string
|
||||
return 'media';
|
||||
}
|
||||
|
||||
/**
|
||||
* Bei einem Film: das Vorschaubild des Films oder eine Stelle des Films als Kartenbild übernehmen. Das Bild wird
|
||||
* einmal als Bild-Medium abgelegt (FilmStill) und wie jedes andere Bild ausgewählt; die Karte liest nur diese Datei.
|
||||
*/
|
||||
protected function imageSourceFields(): array
|
||||
{
|
||||
return [
|
||||
ViewField::make('_filmbild')
|
||||
->label('Bild aus dem Film')
|
||||
->view('filament.cms.filmbild-feld')
|
||||
->dehydrated(false)
|
||||
->visible(fn (Get $get): bool => $this->filmFor($get('element')) !== null)
|
||||
->viewData(fn (Get $get): array => $this->filmFieldData($this->filmFor($get('element')))),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Anzeigedaten des Felds „Bild aus dem Film“. Die Stelle kommt aus der bereitgestellten Fassung, bei einem Film
|
||||
* nur mit Website-Datei aus dieser (Route content.website-frame).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function filmFieldData(?ContentElement $film): array
|
||||
{
|
||||
$stills = app(FilmStill::class);
|
||||
$version = $film instanceof ContentElement ? $stills->version($film) : null;
|
||||
|
||||
return [
|
||||
'film' => $film,
|
||||
'filmTitle' => $film instanceof ContentElement ? (string) ($film->display_title ?: $film->working_title) : '',
|
||||
'filmVersionId' => $version?->id,
|
||||
'filmWebsiteFrameUrl' => $film instanceof ContentElement && $version === null && $stills->websiteFile($film) !== null
|
||||
? route('content.website-frame', ['element' => $film])
|
||||
: null,
|
||||
'filmHasThumbnail' => $film instanceof ContentElement && is_string($film->thumbnail_path) && $film->thumbnail_path !== '',
|
||||
'filmThumbnailUrl' => $film instanceof ContentElement ? ThumbnailRef::url('editorial.card', 'element', (int) $film->id, $film->thumbnail_path) : null,
|
||||
'filmStartSecond' => $film instanceof ContentElement ? ($stills->thumbnailSecond($film) ?? '0') : '0',
|
||||
];
|
||||
}
|
||||
|
||||
private function filmFor(mixed $id): ?ContentElement
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
return $element instanceof ContentElement && app(FilmStill::class)->refusal($element) === null ? $element : null;
|
||||
}
|
||||
|
||||
protected function subjectNoun(): string
|
||||
{
|
||||
return 'Medium';
|
||||
}
|
||||
|
||||
protected function textChoices(): array
|
||||
{
|
||||
return [
|
||||
'auto' => 'Automatisch (Kurzbeschreibung, sonst Teaser)',
|
||||
'teaser' => 'Teaser',
|
||||
'summary' => 'Kurzbeschreibung',
|
||||
'description' => 'Ausführliche Beschreibung (erscheint öffentlich)',
|
||||
];
|
||||
}
|
||||
|
||||
protected function supportsClip(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function clipSubject(mixed $id): ?Model
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->find((int) $id) : null;
|
||||
|
||||
return $element instanceof ContentElement ? $element : null;
|
||||
}
|
||||
|
||||
protected function centralCoverId(mixed $id): ?int
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->find((int) $id) : null;
|
||||
|
||||
@@ -4,19 +4,16 @@
|
||||
|
||||
use App\Domain\Cms\Catalog\CardSubject;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\CardClip;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Field;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
@@ -59,56 +56,6 @@ abstract protected function defaultActionLabel(): string;
|
||||
/** Gestaltungsvariante des Kits: editorial, media oder catalog. */
|
||||
abstract protected function cardStyle(): string;
|
||||
|
||||
/**
|
||||
* Weitere Wege zum Kartenbild im Reiter „Medien“, zum Beispiel ein Bild aus dem Film. Standard: keine.
|
||||
*
|
||||
* @return list<Field>
|
||||
*/
|
||||
protected function imageSourceFields(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fachobjekt, dessen Trailer die Karte beim Überfahren oder Antippen abspielt (Medium, Programm, Modul).
|
||||
* Null: diese Karte hat keinen Clip (Thema). Der Clip kommt aus der Präsentation des Objekts (CardClip).
|
||||
*/
|
||||
protected function clipSubject(mixed $id): ?Model
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zentrale Texte des Fachobjekts, aus denen die Redaktion den Kartentext wählen kann: Wert => Bezeichnung.
|
||||
* Leer: keine Wahl (die Karte nimmt den Text ihrer Vorgabe). Mit Wahl gilt „auto“ als Vorgabe.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function textChoices(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Was die Redaktion bearbeitet, um einen Text zu pflegen („Medium“, „Programm oder Modul“); für Hinweise. */
|
||||
protected function subjectNoun(): string
|
||||
{
|
||||
return 'Objekt';
|
||||
}
|
||||
|
||||
/** Hinweis der Redaktionsvorschau, wenn der gewählte zentrale Text nicht gepflegt ist. */
|
||||
private function missingTextHint(string $field): string
|
||||
{
|
||||
$noun = $this->subjectNoun();
|
||||
|
||||
return match ($field) {
|
||||
'teaser' => 'Kein Teaser gepflegt ('.$noun.' bearbeiten → Teaser).',
|
||||
'summary' => 'Keine Kurzbeschreibung gepflegt ('.$noun.' bearbeiten → Kurzbeschreibung).',
|
||||
'description' => 'Keine ausführliche Beschreibung gepflegt ('.$noun.' bearbeiten → Beschreibung).',
|
||||
'goal' => 'Kein Lernziel gepflegt ('.$noun.' bearbeiten → Lernziel der Fassung).',
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
|
||||
public function view(): string
|
||||
{
|
||||
return 'widgets.premium_card';
|
||||
@@ -163,9 +110,7 @@ public function optionIcons(): array
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
$choices = $this->textChoices();
|
||||
|
||||
return ($choices === [] ? [] : ['text_source' => $choices]) + ($this->supportsClip() ? ['clip' => ['yes' => 'Abspielen', 'no' => 'Nicht abspielen'], 'show_body' => self::SHOW] : []) + [
|
||||
return [
|
||||
'format' => ['landscape' => 'Querformat 16:9', 'square' => 'Quadrat 1:1', 'portrait' => 'Hochformat 3:4'],
|
||||
'fit' => ['cover' => 'Ausschnitt füllt die Fläche', 'contain' => 'Ganzes Bild zeigen (Dokument, Poster)'],
|
||||
'heading_level' => ['h3' => 'H3', 'h2' => 'H2', 'h4' => 'H4'],
|
||||
@@ -176,34 +121,16 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Bild und Video' => ['format', 'fit', 'clip'],
|
||||
'Texte auf der Karte' => ['show_body', 'text_source', 'show_summary', 'show_kind', 'show_meta', 'show_action'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingHiddenWhen(): array
|
||||
{
|
||||
// „Texte auf der Karte: Ausblenden“ macht die Einzelschalter wirkungslos; sie bleiben gespeichert, aber unsichtbar.
|
||||
return array_fill_keys(['text_source', 'show_summary', 'show_kind', 'show_meta', 'show_action'], ['show_body', 'no']);
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'format' => ['Bildformat', 'Seitenverhältnis des Bildes oder Videos. Vorgabe: Querformat 16:9. Gilt auch neben dem Text; das Motiv wird nicht nachträglich hochkant beschnitten.'],
|
||||
'fit' => ['Bildausschnitt', 'Ausschnitt füllt die ganze Fläche; „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche. Vorgabe: Ausschnitt.'],
|
||||
'clip' => ['Trailer auf der Karte', 'Spielt den freigegebenen Trailer als stumme Vorschau, solange die Maus auf der Karte steht; ein Klick oder Tipp auf das Bild oder die kleine Schaltfläche (auch per Tastatur) spielt ihn mit Ton. Gewählt wird der Trailer (sonst der Vorschauclip) in der Präsentation des Objekts, bei einem Film ersatzweise sein freigegebener Teaser. Ohne freigegebenen Clip bleibt das Kartenbild. Vorgabe: Abspielen.'],
|
||||
'show_body' => ['Texte auf der Karte', 'Hauptschalter für alle Texte neben dem Bild. „Ausblenden“ zeigt nur Bild und Video, ohne Titel, Beschreibung, Art, Zusatzangaben und Schaltfläche; die Einzelschalter darunter verschwinden dann. Für Hilfstechnik bleibt der Titel unsichtbar erhalten. Sinnvoll, wenn das Video allein erklärt. Vorgabe: Anzeigen.'],
|
||||
'text_source' => ['Quelle der Beschreibung', 'Welche Angabe aus der Redaktion als Beschreibung erscheint. Vorgabe: Automatisch. Der Text erscheint öffentlich, wenn die Karte öffentlich ist; ist er nicht gepflegt, bleibt die Karte ohne Beschreibung.'],
|
||||
'show_summary' => ['Beschreibung', 'Der Beschreibungstext unter dem Titel, aus den Fachdaten. Vorgabe: Anzeigen.'],
|
||||
'show_kind' => ['Art-Label', 'Kleines Label über dem Titel, zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: Anzeigen.'],
|
||||
'show_meta' => ['Zusatzangaben', 'Angaben aus den Fachdaten, zum Beispiel Ausgabeart oder Programmzugehörigkeit. Vorgabe: Anzeigen.'],
|
||||
'show_action' => ['Schaltfläche', 'Verweis auf die öffentliche Seite des Fachobjekts, falls es eine gibt. Vorgabe: Anzeigen.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Vorgabe: H3, passend unter einer Abschnittsüberschrift (H2).'],
|
||||
'format' => ['Bildformat', 'Vorgabe: Querformat 16:9. Gilt auch neben dem Text; das Motiv wird nicht nachträglich hochkant beschnitten.'],
|
||||
'fit' => ['Bilddarstellung', 'Vorgabe: Ausschnitt. „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Vorgabe: H3, passend unter einer Abschnittsüberschrift (H2).'],
|
||||
'show_summary' => ['Kurzbeschreibung', 'Aus den Fachdaten. Vorgabe: anzeigen.'],
|
||||
'show_kind' => ['Art oder Label', 'Zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: anzeigen.'],
|
||||
'show_meta' => ['Zusatzangaben', 'Aus den Fachdaten, zum Beispiel Ausgabeart oder Programmzugehörigkeit. Vorgabe: anzeigen.'],
|
||||
'show_action' => ['Aktion', 'Verweis auf die öffentliche Seite des Fachobjekts, falls es eine gibt. Vorgabe: anzeigen.'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -268,13 +195,13 @@ public function editorSchema(): array
|
||||
->hintColor(fn (?string $state): string => filled($state) ? 'warning' : 'gray')
|
||||
->helperText('Leer übernimmt den Anzeigenamen des Fachobjekts. Eine Eintragung gilt nur für diese Karte und ändert die Quelle nicht.'),
|
||||
TextInput::make('summary')
|
||||
->label('Text nur für diese Karte')
|
||||
->label('Teaser nur für diese Karte')
|
||||
->maxLength(500)
|
||||
->live(onBlur: true)
|
||||
->placeholder(fn (Get $get): string => $this->centralText($get('../refs.'.$this->refKey()), 'summary', $get('../settings.text_source')) ?? 'Zentraler Text aus der Redaktion')
|
||||
->placeholder(fn (Get $get): string => $this->centralText($get('../refs.'.$this->refKey()), 'summary') ?? 'Zentraler Teaser oder Kurzbeschreibung')
|
||||
->hint(fn (?string $state): string => filled($state) ? 'Eigene Angabe für diese Karte' : 'Aus der Redaktion')
|
||||
->hintColor(fn (?string $state): string => filled($state) ? 'warning' : 'gray')
|
||||
->helperText('Leer übernimmt den Text, den „Text der Karte“ (Darstellung) wählt. Lehrinhalt, Rechte und Preise bleiben unberührt.'),
|
||||
->helperText('Leer übernimmt Teaser oder Kurzbeschreibung. Lehrinhalt, Rechte und Preise bleiben unberührt.'),
|
||||
])->statePath('data'),
|
||||
];
|
||||
}
|
||||
@@ -284,7 +211,7 @@ public function mediaSchema(): array
|
||||
[, , $alt, $focusX, $focusY] = $this->dataFields();
|
||||
|
||||
return [
|
||||
Group::make([...ImageRefFields::fields('Kartenbild', live: true), ...$this->imageSourceFields()])->statePath('refs'),
|
||||
Group::make(ImageRefFields::fields('Kartenbild', live: true))->statePath('refs'),
|
||||
Group::make([$alt, $focusX, $focusY])->statePath('data'),
|
||||
];
|
||||
}
|
||||
@@ -321,12 +248,6 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
$data = $widget['data'];
|
||||
|
||||
$subject = $this->subject($widget['refs'][$this->refKey()] ?? null, $context);
|
||||
$textSource = $option('text_source', 'auto');
|
||||
|
||||
if ($subject instanceof CardSubject && $textSource !== 'auto' && isset($this->textChoices()[$textSource])) {
|
||||
$subject = $subject->withTextChoice($textSource, $this->missingTextHint($textSource));
|
||||
}
|
||||
|
||||
$heading = filled($data['heading'] ?? null) ? trim((string) $data['heading']) : null;
|
||||
$lead = filled($data['summary'] ?? null) ? trim((string) $data['summary']) : null;
|
||||
|
||||
@@ -337,16 +258,8 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
$storedImage = WebsiteImage::normalize($widget['refs']['image'] ?? null);
|
||||
$imageRef = $storedImage ?? $this->centralCoverId($widget['refs'][$this->refKey()] ?? null);
|
||||
|
||||
$clip = null;
|
||||
|
||||
if ($this->supportsClip() && $option('clip', 'yes') === 'yes' && $subject instanceof CardSubject) {
|
||||
$owner = $this->clipSubject($widget['refs'][$this->refKey()] ?? null);
|
||||
$clip = $owner instanceof Model ? app(CardClip::class)->for($owner, $context->preview) : null;
|
||||
}
|
||||
|
||||
return [
|
||||
'subject' => $subject,
|
||||
'clip' => $clip,
|
||||
'cardStyle' => $subject?->style ?? $this->cardStyle(),
|
||||
'imageUrl' => app(WebsiteImage::class)->url($imageRef, $context->preview),
|
||||
'alt' => app(WebsiteImage::class)->alt($imageRef, $data['alt'] ?? null),
|
||||
@@ -364,7 +277,6 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
'actionLabel' => filled($data['action_label'] ?? null) ? (string) $data['action_label'] : $this->defaultActionLabel(),
|
||||
'note' => filled($data['note'] ?? null) ? (string) $data['note'] : null,
|
||||
'stacked' => $widget['variant'] === 'stacked',
|
||||
'bare' => $this->supportsClip() && $option('show_body', 'yes') === 'no',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -387,15 +299,10 @@ protected function centralCoverId(mixed $id): ?int
|
||||
return null;
|
||||
}
|
||||
|
||||
protected function supportsClip(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zentraler Anzeigename oder Teaser des gewählten Objekts (Redaktionsstand) für Platzhalter im Editor.
|
||||
*/
|
||||
private function centralText(mixed $id, string $field, mixed $textSource = null): ?string
|
||||
private function centralText(mixed $id, string $field): ?string
|
||||
{
|
||||
if (blank($id)) {
|
||||
return null;
|
||||
@@ -407,10 +314,6 @@ private function centralText(mixed $id, string $field, mixed $textSource = null)
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($subject instanceof CardSubject && is_string($textSource) && isset($this->textChoices()[$textSource]) && $textSource !== 'auto') {
|
||||
$subject = $subject->withTextChoice($textSource, $this->missingTextHint($textSource));
|
||||
}
|
||||
|
||||
$text = $subject?->{$field};
|
||||
|
||||
return is_string($text) && trim($text) !== '' ? Str::limit(trim($text), 120) : null;
|
||||
|
||||
@@ -7,11 +7,6 @@
|
||||
use App\Domain\Cms\Catalog\CardSubject;
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Media\CompositionStill;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use Filament\Forms\Components\ViewField;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Modul- und Programmkarte (Kit v1.7 „catalog“): ein Programm oder Modul über PublicCatalogReader, dieselbe
|
||||
@@ -46,59 +41,6 @@ public function schematic(): array
|
||||
return [[2, 2, 56, 32, 'line'], [5, 5, 22, 26, 'ink'], [8, 24, 10, 2, 'accent'], [31, 8, 10, 2, 'line'], [31, 13, 22, 4, 'ink'], [31, 25, 14, 5, 'ink']];
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Vorschaubild des Programms oder Moduls als Kartenbild übernehmen. Es wird einmal als Bild-Medium abgelegt
|
||||
* (CompositionStill) und wie jedes andere Bild ausgewählt; die Karte liest nur diese Datei.
|
||||
*/
|
||||
protected function imageSourceFields(): array
|
||||
{
|
||||
return [
|
||||
ViewField::make('_programmbild')
|
||||
->label('Bild aus dem Programm oder Modul')
|
||||
->view('filament.cms.kompositionsbild-feld')
|
||||
->dehydrated(false)
|
||||
->visible(fn (Get $get): bool => $this->compositionFor($get('composition')) !== null)
|
||||
->viewData(function (Get $get): array {
|
||||
$composition = $this->compositionFor($get('composition'));
|
||||
|
||||
return [
|
||||
'composition' => $composition,
|
||||
'compositionTitle' => $composition instanceof Composition ? (string) ($composition->display_title ?: $composition->designation) : '',
|
||||
'compositionThumbnailUrl' => $composition instanceof Composition && app(CompositionStill::class)->hasThumbnail($composition)
|
||||
? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path)
|
||||
: null,
|
||||
];
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
private function compositionFor(mixed $id): ?Composition
|
||||
{
|
||||
$composition = is_numeric($id) ? Composition::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
return $composition instanceof Composition && app(PublicCatalogReader::class)->isCardSelectable($composition) ? $composition : null;
|
||||
}
|
||||
|
||||
protected function subjectNoun(): string
|
||||
{
|
||||
return 'Programm oder Modul';
|
||||
}
|
||||
|
||||
/**
|
||||
* Wählbare Texte: die zentralen Texte des Programms oder Moduls und das Lernziel der Fassung. „Automatisch“ bleibt
|
||||
* wie bisher: Teaser, sonst Kurzbeschreibung, sonst Lernziel. Die ausführliche Beschreibung erscheint nur auf Wahl.
|
||||
*/
|
||||
protected function textChoices(): array
|
||||
{
|
||||
return [
|
||||
'auto' => 'Automatisch (Teaser, sonst Kurzbeschreibung, sonst Lernziel)',
|
||||
'teaser' => 'Teaser',
|
||||
'summary' => 'Kurzbeschreibung',
|
||||
'description' => 'Ausführliche Beschreibung (erscheint öffentlich)',
|
||||
'goal' => 'Lernziel der Fassung',
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
// Die Art (Programm oder Modul) bleibt immer sichtbar; sie lässt sich nicht ausblenden.
|
||||
@@ -157,18 +99,6 @@ protected function cardStyle(): string
|
||||
return 'catalog';
|
||||
}
|
||||
|
||||
protected function supportsClip(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function clipSubject(mixed $id): ?Model
|
||||
{
|
||||
$composition = is_numeric($id) ? Composition::query()->find((int) $id) : null;
|
||||
|
||||
return $composition instanceof Composition ? $composition : null;
|
||||
}
|
||||
|
||||
protected function centralCoverId(mixed $id): ?int
|
||||
{
|
||||
$composition = is_numeric($id) ? Composition::query()->find((int) $id) : null;
|
||||
|
||||
@@ -41,7 +41,7 @@ public function version(): int
|
||||
public const HEIGHTS = [
|
||||
'auto' => 'Automatisch',
|
||||
'compact' => 'Kompakt',
|
||||
'normal' => 'Standard',
|
||||
'normal' => 'Normal',
|
||||
'large' => 'Groß',
|
||||
'spacious' => 'Großzügig',
|
||||
'fill' => 'Abschnittshöhe füllen',
|
||||
@@ -194,29 +194,6 @@ public function settingLabels(): array
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gliederung der Einstellungen im Reiter „Darstellung“: Gruppentitel => Schlüssel der Einstellungen in der
|
||||
* Reihenfolge der Anzeige. Variante und Höhe stehen immer in der ersten Gruppe „Aufbau“. Einstellungen ohne
|
||||
* Gruppe erscheinen unter „Weitere Einstellungen“, so geht keine verloren.
|
||||
*
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Einstellungen, die im Editor ausgeblendet werden, solange eine andere Einstellung einen bestimmten Wert hat:
|
||||
* Schlüssel => [steuernde Einstellung, Wert, bei dem ausgeblendet wird]. Die Werte bleiben dabei erhalten.
|
||||
*
|
||||
* @return array<string, array{0: string, 1: string}>
|
||||
*/
|
||||
public function settingHiddenWhen(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle zulässigen Einstellungen einschließlich der gemeinsamen Höhe. Registry-Prüfung, Editor und Darstellung
|
||||
* verwenden ausschließlich diese Zusammenführung.
|
||||
|
||||
@@ -1,300 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Discount\DiscountResult;
|
||||
use App\Domain\Commerce\Discount\DiscountService;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Sitzungsgebundener Mehrangebotswarenkorb (Etappe 1). Er bleibt in derselben Browsersitzung über Anmeldung,
|
||||
* Registrierung und E-Mail-Bestätigung erhalten. Je Option gibt es genau eine Position. Optionen derselben Produktseite
|
||||
* (gleiche Komposition) sind Alternativen und werden nur nach ausdrücklichem Wechsel ersetzt.
|
||||
* Der Warenkorb reserviert weder Preis noch Konditionen; er merkt sich, was der Käufer gesehen hat.
|
||||
*/
|
||||
class Cart
|
||||
{
|
||||
public const KEY = 'shop.cart';
|
||||
|
||||
/** Eingelöster Rabattcode (Kennung); höchstens einer je Bestellung. */
|
||||
public const DISCOUNT_KEY = 'shop.discount';
|
||||
|
||||
public const ADDED = 'added';
|
||||
|
||||
public const PRESENT = 'present';
|
||||
|
||||
public const ALTERNATIVE = 'alternative';
|
||||
|
||||
public const UNAVAILABLE = 'unavailable';
|
||||
|
||||
public function __construct(
|
||||
private readonly OwnershipCheck $ownership,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly OfferService $offers,
|
||||
private readonly DiscountService $discounts,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<int, array{version_id: int, price_cents: int}>
|
||||
*/
|
||||
public function items(): array
|
||||
{
|
||||
return (array) session()->get(self::KEY, []);
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->items());
|
||||
}
|
||||
|
||||
public function has(Offer $offer): bool
|
||||
{
|
||||
return isset($this->items()[$offer->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die bereits enthaltene Alternative derselben Produktseite, falls vorhanden.
|
||||
*/
|
||||
public function alternativeTo(Offer $offer): ?Offer
|
||||
{
|
||||
$products = app(ProductOptions::class);
|
||||
$group = $products->groupKey($offer);
|
||||
|
||||
if ($group === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ids = array_diff(array_keys($this->items()), [$offer->id]);
|
||||
|
||||
return $ids === [] ? null : Offer::query()
|
||||
->whereIn('id', $ids)
|
||||
->get()
|
||||
->first(fn (Offer $other): bool => $products->groupKey($other) === $group);
|
||||
}
|
||||
|
||||
public function add(Offer $offer): string
|
||||
{
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version === null) {
|
||||
return self::UNAVAILABLE;
|
||||
}
|
||||
|
||||
if ($this->has($offer)) {
|
||||
return self::PRESENT;
|
||||
}
|
||||
|
||||
if ($this->alternativeTo($offer) !== null) {
|
||||
return self::ALTERNATIVE;
|
||||
}
|
||||
|
||||
$this->put($offer, $version);
|
||||
|
||||
return self::ADDED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ausdrücklicher Wechsel: die Alternative wird durch die gewählte Option ersetzt.
|
||||
*/
|
||||
public function switchTo(Offer $offer): bool
|
||||
{
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$alternative = $this->alternativeTo($offer);
|
||||
|
||||
if ($alternative !== null) {
|
||||
$this->remove($alternative);
|
||||
}
|
||||
|
||||
$this->put($offer, $version);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function remove(Offer $offer): void
|
||||
{
|
||||
$items = $this->items();
|
||||
unset($items[$offer->id]);
|
||||
session()->put(self::KEY, $items);
|
||||
}
|
||||
|
||||
/**
|
||||
* Der Käufer übernimmt Preis und Fassung, die der Shop jetzt zeigt.
|
||||
*/
|
||||
public function acceptCurrent(Offer $offer): void
|
||||
{
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version !== null && $this->has($offer)) {
|
||||
$this->put($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
session()->forget([self::KEY, self::DISCOUNT_KEY]);
|
||||
}
|
||||
|
||||
/** Der im Warenkorb eingelöste Code, auch wenn er gerade nicht (mehr) gilt. */
|
||||
public function discountCode(): ?DiscountCode
|
||||
{
|
||||
$id = session()->get(self::DISCOUNT_KEY);
|
||||
|
||||
return is_numeric($id) ? DiscountCode::query()->with('targets')->find((int) $id) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Löst einen Code ein. Er wird nur vorgemerkt, wenn er für diesen Warenkorb und dieses Konto gilt; sonst bleibt
|
||||
* der bisherige Stand und das Ergebnis nennt den Grund. Ein zweiter Code ersetzt den ersten (höchstens ein Code).
|
||||
*/
|
||||
public function applyCode(string $input, ?User $user, ?int $holderPartyId = null): DiscountResult
|
||||
{
|
||||
$code = $this->discounts->find($input);
|
||||
|
||||
if ($code === null) {
|
||||
return new DiscountResult(null, DiscountResult::UNKNOWN, 'Diesen Code kennen wir nicht. Prüfe die Schreibweise.');
|
||||
}
|
||||
|
||||
$previous = session()->get(self::DISCOUNT_KEY);
|
||||
session()->put(self::DISCOUNT_KEY, $code->id);
|
||||
$result = $this->review($user, $holderPartyId)->discount;
|
||||
|
||||
if ($result === null || ! $result->applied()) {
|
||||
$previous === null ? session()->forget(self::DISCOUNT_KEY) : session()->put(self::DISCOUNT_KEY, $previous);
|
||||
|
||||
return $result ?? new DiscountResult($code, DiscountResult::NO_MATCH, 'Der Code kann auf diese Bestellung nicht angewendet werden.');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function removeCode(): void
|
||||
{
|
||||
session()->forget(self::DISCOUNT_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serverseitige Prüfung: aktuelle Fassung, Preis, Kaufbarkeit, passende Inhaberart, vorhandene Rechte.
|
||||
*/
|
||||
public function review(?User $user = null, ?int $holderPartyId = null, bool $lockDiscount = false): CartReview
|
||||
{
|
||||
$offers = Offer::query()
|
||||
->whereIn('id', array_keys($this->items()))
|
||||
->with('composition')
|
||||
->get()
|
||||
->keyBy('id');
|
||||
$versions = [];
|
||||
|
||||
foreach ($this->items() as $offerId => $item) {
|
||||
$offer = $offers->get($offerId);
|
||||
|
||||
if ($offer !== null) {
|
||||
$versions[$offerId] = $this->purchasable($offer);
|
||||
}
|
||||
}
|
||||
|
||||
$holder = $user === null ? null : $this->holderFor($user, $holderPartyId, $versions);
|
||||
$lines = [];
|
||||
|
||||
foreach ($this->items() as $offerId => $item) {
|
||||
$offer = $offers->get($offerId);
|
||||
|
||||
if ($offer === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$version = $versions[$offerId] ?? null;
|
||||
$seen = (int) $item['price_cents'];
|
||||
|
||||
if ($version === null) {
|
||||
$lines[] = new CartLine($offer, null, CartLine::WITHDRAWN, $seen, null,
|
||||
'Diese Option ist nicht mehr erhältlich. Entferne sie, um mit den übrigen Positionen fortzufahren.');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = (int) $version->price_cents;
|
||||
|
||||
if ($holder !== null && ! $this->suitsHolder($version, $holder)) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::WRONG_HOLDER, $seen, $current,
|
||||
$version->holder_kind === 'organisation'
|
||||
? 'Diese Option ist für Organisationen. Bestelle als Verein oder entferne sie.'
|
||||
: 'Diese Option ist für Privatpersonen. Bestelle als Privatperson oder entferne sie.');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($holder !== null && $this->ownership->covers($holder, $version)) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::OWNED, $seen, $current);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($current !== $seen) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::PRICE_CHANGED, $seen, $current);
|
||||
} elseif ((int) $item['version_id'] !== $version->id) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::TERMS_CHANGED, $seen, $current,
|
||||
'Die Bedingungen dieser Option wurden aktualisiert. Bitte prüfe die Übersicht.');
|
||||
} else {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::OK, $seen, $current);
|
||||
}
|
||||
}
|
||||
|
||||
$code = $this->discountCode();
|
||||
$discount = null;
|
||||
|
||||
if ($code !== null) {
|
||||
$orderable = array_values(array_filter($lines, fn (CartLine $line): bool => $line->orderable()));
|
||||
$discount = $this->discounts->evaluate($code, $user, $orderable, lock: $lockDiscount);
|
||||
}
|
||||
|
||||
return new CartReview($lines, $holder, $discount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die aktive, als Kauf angebotene Fassung der Option; sonst null (nicht kaufbar oder zurückgezogen).
|
||||
*/
|
||||
public function purchasable(Offer $offer): ?OfferVersion
|
||||
{
|
||||
return $this->offers->purchasableVersion($offer);
|
||||
}
|
||||
|
||||
private function put(Offer $offer, OfferVersion $version): void
|
||||
{
|
||||
$items = $this->items();
|
||||
$items[$offer->id] = ['version_id' => $version->id, 'price_cents' => (int) $version->price_cents];
|
||||
session()->put(self::KEY, $items);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, OfferVersion|null> $versions
|
||||
*/
|
||||
private function holderFor(User $user, ?int $partyId, array $versions): ?Party
|
||||
{
|
||||
$onlyOrganisations = $versions !== [] && collect($versions)
|
||||
->filter()
|
||||
->every(fn (OfferVersion $version): bool => $version->holder_kind === 'organisation');
|
||||
|
||||
try {
|
||||
return $this->holders->resolve($user, $partyId, $onlyOrganisations);
|
||||
} catch (DomainRuleException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function suitsHolder(OfferVersion $version, Party $holder): bool
|
||||
{
|
||||
return ($version->holder_kind === 'organisation') === ($holder->type === PartyType::Organisation);
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
|
||||
/**
|
||||
* Eine Position des Warenkorbs mit dem Ergebnis der serverseitigen Prüfung.
|
||||
*/
|
||||
final class CartLine
|
||||
{
|
||||
public const OK = 'ok';
|
||||
|
||||
public const PRICE_CHANGED = 'preis_geaendert';
|
||||
|
||||
public const TERMS_CHANGED = 'bedingungen_geaendert';
|
||||
|
||||
public const WITHDRAWN = 'zurueckgezogen';
|
||||
|
||||
public const OWNED = 'bereits_erworben';
|
||||
|
||||
public const WRONG_HOLDER = 'falscher_inhaber';
|
||||
|
||||
public function __construct(
|
||||
public readonly Offer $offer,
|
||||
public readonly ?OfferVersion $version,
|
||||
public readonly string $state,
|
||||
public readonly int $seenPriceCents,
|
||||
public readonly ?int $currentPriceCents,
|
||||
public readonly ?string $note = null,
|
||||
) {}
|
||||
|
||||
/** Geht in Summe und Bestellung ein. */
|
||||
public function orderable(): bool
|
||||
{
|
||||
return in_array($this->state, [self::OK, self::PRICE_CHANGED, self::TERMS_CHANGED], true);
|
||||
}
|
||||
|
||||
/** Verhindert den Abschluss, bis der Käufer die Position selbst entfernt oder den Inhaber wechselt. */
|
||||
public function blocks(): bool
|
||||
{
|
||||
return in_array($this->state, [self::WITHDRAWN, self::WRONG_HOLDER], true);
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
if ($this->offer->standalone_bundle && $this->version !== null) {
|
||||
$bundle = app(ProductOptions::class)->bundleOf($this->version);
|
||||
|
||||
if ($bundle !== null) {
|
||||
return (string) $bundle->name;
|
||||
}
|
||||
}
|
||||
|
||||
$composition = $this->offer->composition;
|
||||
|
||||
return $composition !== null
|
||||
? (string) ($composition->display_title ?: $composition->designation)
|
||||
: (string) $this->offer->name;
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Commerce\Discount\DiscountResult;
|
||||
use App\Domain\Identity\Party;
|
||||
|
||||
/**
|
||||
* Prüfergebnis des Warenkorbs für einen vorgesehenen Lizenzinhaber. Die Prüfsumme bindet die Bestellung an genau
|
||||
* diese Übersicht: Inhaber, Fassung und Preis jeder Position samt Zustand, auch der ausgeschlossenen.
|
||||
*/
|
||||
final class CartReview
|
||||
{
|
||||
/**
|
||||
* @param list<CartLine> $lines
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly array $lines,
|
||||
public readonly ?Party $holder,
|
||||
public readonly ?DiscountResult $discount = null,
|
||||
) {}
|
||||
|
||||
/** @return list<CartLine> */
|
||||
public function orderable(): array
|
||||
{
|
||||
return array_values(array_filter($this->lines, fn (CartLine $line): bool => $line->orderable()));
|
||||
}
|
||||
|
||||
/** Summe der Listenpreise der Positionen, die in die Bestellung eingehen. */
|
||||
public function subtotalCents(): int
|
||||
{
|
||||
return array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $this->orderable()));
|
||||
}
|
||||
|
||||
public function discountCents(): int
|
||||
{
|
||||
return $this->discount?->totalCents() ?? 0;
|
||||
}
|
||||
|
||||
/** Endgültiger Zahlbetrag: Listenpreise abzüglich Rabatt. */
|
||||
public function totalCents(): int
|
||||
{
|
||||
return $this->subtotalCents() - $this->discountCents();
|
||||
}
|
||||
|
||||
/** Rabatt einer Position in Cent. */
|
||||
public function discountFor(CartLine $line): int
|
||||
{
|
||||
return $this->discount?->forOffer($line->offer->id) ?? 0;
|
||||
}
|
||||
|
||||
/** Ein vorgemerkter Code, der jetzt nicht gilt, hält die Bestellung an, bis er entfernt wird. */
|
||||
public function discountBlocks(): bool
|
||||
{
|
||||
return $this->discount !== null && ! $this->discount->applied();
|
||||
}
|
||||
|
||||
public function blocked(): bool
|
||||
{
|
||||
foreach ($this->lines as $line) {
|
||||
if ($line->blocks()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function empty(): bool
|
||||
{
|
||||
return $this->orderable() === [];
|
||||
}
|
||||
|
||||
public function canOrder(): bool
|
||||
{
|
||||
return $this->holder !== null && ! $this->blocked() && ! $this->empty() && ! $this->discountBlocks();
|
||||
}
|
||||
|
||||
public function digest(): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
foreach ($this->lines as $line) {
|
||||
$parts[] = $line->offer->id.':'.($line->version?->id ?? 0).':'.$line->currentPriceCents.':'.$line->state;
|
||||
}
|
||||
|
||||
sort($parts);
|
||||
|
||||
return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts).'|'.($this->discount?->digestPart() ?? '-'));
|
||||
}
|
||||
}
|
||||
@@ -5,19 +5,13 @@
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Stripe\StripeGateway;
|
||||
use App\Domain\Entitlement\Acquisition;
|
||||
use App\Domain\Entitlement\AcquisitionType;
|
||||
use App\Domain\Entitlement\GrantIssuer;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Domain\Identity\AccountStatus;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Mail\OrderConfirmed;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
@@ -26,21 +20,12 @@ class Checkout
|
||||
public function __construct(
|
||||
private readonly GrantIssuer $grants,
|
||||
private readonly OfferService $offers,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly PaymentJournal $journal,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Einzelkauf einer Option als Person (bestehender Weg, ohne Warenkorb).
|
||||
*/
|
||||
public function place(User $user, Offer $offer): Order
|
||||
{
|
||||
$this->assertActive($user);
|
||||
|
||||
// Dieser Einzelkauf kennt weder Zustimmungen noch „Zahlungspflichtig bestellen“. Im Livebetrieb gibt es nur den
|
||||
// Weg über die Kasse mit Pflichtangaben.
|
||||
if (Shop::live()) {
|
||||
throw new DomainRuleException('Bestelle über den Warenkorb und die Kasse.');
|
||||
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
||||
}
|
||||
|
||||
$version = $this->offers->currentActiveVersion($offer);
|
||||
@@ -53,114 +38,20 @@ public function place(User $user, Offer $offer): Order
|
||||
throw new DomainRuleException('Der Kauf braucht einen Preis an der Angebotsfassung.');
|
||||
}
|
||||
|
||||
$holder = $this->holders->resolve($user, null);
|
||||
|
||||
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]], null, null, Shop::driver() === 'stripe' ? 'stripe' : 'test'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bestellung aus dem Warenkorb, erst nach serverseitiger Prüfung. Die Prüfsumme bindet die Bestellung an die
|
||||
* Übersicht, die der Käufer gesehen hat: Hat sich Preis, Fassung oder Bedingung seither geändert, entsteht keine
|
||||
* Bestellung und der Käufer sieht zuerst die aktualisierte Übersicht. Positionen, deren Umfang der Inhaber bereits
|
||||
* mit denselben Rechten besitzt, erzeugen keine Bestellposition.
|
||||
*/
|
||||
public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, string $digest, ?array $consent = null, ?string $paymentMethod = null): Order
|
||||
{
|
||||
$this->assertActive($user);
|
||||
|
||||
if ($consent === null && Shop::live()) {
|
||||
throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.');
|
||||
}
|
||||
|
||||
$order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest, $consent, $paymentMethod): Order {
|
||||
// Optionen und den Rabattcode sperren, damit eine gleichzeitige Aktivierung, Deaktivierung oder ein Entzug
|
||||
// der Freigabe die Prüfung nicht unterläuft.
|
||||
Offer::query()->whereIn('id', array_keys($cart->items()))->orderBy('id')->lockForUpdate()->get();
|
||||
$discountId = session()->get(Cart::DISCOUNT_KEY);
|
||||
|
||||
if (is_numeric($discountId)) {
|
||||
DiscountCode::query()->whereKey((int) $discountId)->lockForUpdate()->first();
|
||||
}
|
||||
|
||||
$review = $cart->review($user, $holderPartyId, lockDiscount: true);
|
||||
|
||||
if ($review->holder === null) {
|
||||
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
|
||||
}
|
||||
|
||||
if (! hash_equals($review->digest(), $digest)) {
|
||||
throw new StaleOverview('Die Übersicht hat sich geändert. Bitte prüfe die aktualisierte Bestellübersicht.');
|
||||
}
|
||||
|
||||
if ($review->blocked()) {
|
||||
throw new DomainRuleException('Entferne zuerst die Positionen, die nicht bestellt werden können.');
|
||||
}
|
||||
|
||||
if ($review->empty()) {
|
||||
throw new DomainRuleException('Es gibt nichts zu bestellen. Alle Positionen sind bereits erworben.');
|
||||
}
|
||||
|
||||
if ($review->discountBlocks()) {
|
||||
throw new DomainRuleException(($review->discount?->message ?? 'Der Rabattcode gilt nicht.').' Entferne den Code, um ohne Rabatt zu bestellen.');
|
||||
}
|
||||
|
||||
$method = $paymentMethod ?? (Shop::driver() === 'stripe' ? 'stripe' : 'test');
|
||||
|
||||
if ($method === 'rechnung' && ! ($review->holder->type === PartyType::Organisation && Shop::invoice())) {
|
||||
throw new DomainRuleException('Der Kauf auf Rechnung ist nur für Vereine und Organisationen auf Anfrage möglich.');
|
||||
}
|
||||
|
||||
$pairs = array_map(fn (CartLine $line): array => [$line->offer, $line->version], $review->orderable());
|
||||
|
||||
return $this->createOrder($user, $review->holder, $pairs, $review, $consent === null ? null : SalesTerms::proof($consent), $method);
|
||||
});
|
||||
|
||||
$cart->clear();
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{0: Offer, 1: OfferVersion}> $pairs
|
||||
* @param array<string, mixed>|null $terms Nachweis der Zustimmungen (SalesTerms::proof)
|
||||
*/
|
||||
private function createOrder(User $user, Party $holder, array $pairs, ?CartReview $review, ?array $terms, string $method): Order
|
||||
{
|
||||
$subtotal = array_sum(array_map(fn (array $pair): int => (int) $pair[1]->price_cents, $pairs));
|
||||
$discount = $review?->discount;
|
||||
$discountCents = $review?->discountCents() ?? 0;
|
||||
|
||||
$order = Order::query()->create([
|
||||
'user_id' => $user->id,
|
||||
'party_id' => $holder->id,
|
||||
'status' => 'offen',
|
||||
'holder_kind' => $holder->type->value,
|
||||
'subtotal_cents' => $subtotal,
|
||||
'discount_cents' => $discountCents,
|
||||
'total_cents' => $subtotal - $discountCents,
|
||||
'currency' => 'EUR',
|
||||
'discount_code_id' => $discountCents > 0 ? $discount?->code?->id : null,
|
||||
'discount_snapshot' => $discountCents > 0 ? $discount?->snapshot() : null,
|
||||
'payment_method' => $method,
|
||||
'terms_accepted_at' => $terms === null ? null : now(),
|
||||
'terms_snapshot' => $terms,
|
||||
]);
|
||||
|
||||
foreach ($pairs as [$offer, $version]) {
|
||||
return DB::transaction(function () use ($user, $offer, $version): Order {
|
||||
$order = Order::query()->create([
|
||||
'user_id' => $user->id,
|
||||
'party_id' => $user->party_id,
|
||||
'status' => 'offen',
|
||||
'holder_kind' => 'person',
|
||||
]);
|
||||
$line = $order->lines()->create([
|
||||
'offer_version_id' => $version->id,
|
||||
'offer_name' => $offer->name,
|
||||
'price_cents' => $version->price_cents,
|
||||
'currency' => 'EUR',
|
||||
'term_rule' => $version->term_rule,
|
||||
'update_promise' => $version->update_promise,
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'tax_class' => $version->tax_class,
|
||||
'grant_kind' => $version->grant_kind,
|
||||
'holder_party_id' => $holder->id,
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
'discount_cents' => $discountCents > 0 ? $discount->forOffer($offer->id) : 0,
|
||||
]);
|
||||
$version->load('resolvedScopes.rights');
|
||||
|
||||
@@ -175,62 +66,14 @@ private function createOrder(User $user, Party $holder, array $pairs, ?CartRevie
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $order->load('lines.scopeItems');
|
||||
return $order->load('lines.scopeItems');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Freischaltung nach bestätigter Testzahlung: alle Bestellpositionen aus ihrem festgehaltenen Umfang, in einer
|
||||
* Transaktion. Wiederholte Bestätigung ist wirkungslos; ein Fehler hinterlässt weder Zahlung noch Rechte.
|
||||
*/
|
||||
public function confirmTestPayment(Order $order, string $reference): Order
|
||||
{
|
||||
$this->assertTestDriver();
|
||||
$this->assertTestOrder($order);
|
||||
|
||||
return $this->settle($order, 'test', $reference, null, now(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die
|
||||
* Bestellung. Wiederholte Meldungen sind wirkungslos. `$live` sagt, ob echtes Geld geflossen ist (Stripe meldet
|
||||
* es je Ereignis); ohne Angabe gilt der Betriebszustand des Shops. `$occurredAt` ist der Zeitpunkt der Zahlung
|
||||
* laut Anbieter, sonst jetzt.
|
||||
*/
|
||||
public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency, ?bool $live = null, ?CarbonInterface $occurredAt = null, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents') - $order->lines()->sum('discount_cents'));
|
||||
|
||||
if ($amountCents !== $expected || strtoupper($currency) !== strtoupper((string) ($order->currency ?? 'EUR'))) {
|
||||
throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.');
|
||||
}
|
||||
|
||||
return $this->settle($order, $provider, $reference, null, $occurredAt ?? now(), $live ?? Shop::live(), $paymentIntent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kauf auf Rechnung (PAY-006): Der Betreiber hat die Rechnung manuell erstellt und bestätigt den Zahlungseingang.
|
||||
* Nur für Bestellungen mit Zahlungsweg „Rechnung“; das Mitglied kann das nicht selbst auslösen. Die Referenz
|
||||
* (Rechnungsnummer oder Buchung) wird an der Zahlung festgehalten. `$receivedOn` ist der Tag, an dem das Geld auf
|
||||
* dem Konto einging (nicht in der Zukunft, nicht vor der Bestellung); ohne Angabe gilt heute. Er bestimmt, in
|
||||
* welchen Zeitraum die Einnahme fällt.
|
||||
*/
|
||||
public function confirmInvoicePayment(Order $order, string $reference, User $actor, string|CarbonInterface|null $receivedOn = null): Order
|
||||
{
|
||||
$order->refresh();
|
||||
|
||||
if ($order->payment_method !== 'rechnung') {
|
||||
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
|
||||
}
|
||||
|
||||
$day = PaymentJournal::dayOf($receivedOn ?? now(PaymentJournal::TIMEZONE), $order->created_at);
|
||||
|
||||
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor, $day, Shop::live());
|
||||
}
|
||||
|
||||
private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy, CarbonInterface $occurredAt, bool $live, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$reference = trim($reference);
|
||||
|
||||
if ($reference === '') {
|
||||
@@ -238,7 +81,7 @@ private function settle(Order $order, string $provider, string $reference, ?User
|
||||
}
|
||||
|
||||
$paidNow = false;
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, $occurredAt, $live, $paymentIntent, &$paidNow): Order {
|
||||
$order = DB::transaction(function () use ($order, $reference, &$paidNow): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status === 'bezahlt') {
|
||||
@@ -249,24 +92,22 @@ private function settle(Order $order, string $provider, string $reference, ?User
|
||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
||||
}
|
||||
|
||||
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
|
||||
$payment = $order->payments()->updateOrCreate(
|
||||
['provider_reference' => $reference],
|
||||
array_filter(
|
||||
['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id, 'provider_payment_ref' => $paymentIntent],
|
||||
fn (mixed $value): bool => $value !== null,
|
||||
),
|
||||
);
|
||||
$this->journal->recordPayment($order, $payment, $occurredAt, $confirmedBy, $live);
|
||||
$order->payments()->create([
|
||||
'provider' => 'test',
|
||||
'status' => 'bestaetigt',
|
||||
'provider_reference' => $reference,
|
||||
]);
|
||||
$order->status = 'bezahlt';
|
||||
$order->save();
|
||||
$paidNow = true;
|
||||
$actor = User::query()->findOrFail($order->user_id);
|
||||
|
||||
foreach ($order->lines()->orderBy('id')->get() as $line) {
|
||||
$holder = Party::query()->findOrFail($line->holder_party_id ?? $order->party_id);
|
||||
$this->grants->issueFromOrderLine($line, $holder, $actor);
|
||||
}
|
||||
$line = $order->lines()->firstOrFail();
|
||||
$this->grants->issue(
|
||||
$order->user,
|
||||
$line->offerVersion,
|
||||
AcquisitionType::Bestellposition,
|
||||
'order_line',
|
||||
$line->id,
|
||||
);
|
||||
|
||||
return $order->load('lines', 'payments');
|
||||
});
|
||||
@@ -281,7 +122,6 @@ private function settle(Order $order, string $provider, string $reference, ?User
|
||||
public function failTestPayment(Order $order, string $reference): Order
|
||||
{
|
||||
$this->assertTestDriver();
|
||||
$this->assertTestOrder($order);
|
||||
|
||||
return DB::transaction(function () use ($order, $reference): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
@@ -302,16 +142,7 @@ public function failTestPayment(Order $order, string $reference): Order
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen
|
||||
* (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Bundles sind Rückgabeeinheiten; freiwillige
|
||||
* Teilerstattungen gibt es zum Start nicht. Bei einer Zahlung über Stripe wird die Rückzahlung zuerst bei Stripe
|
||||
* veranlasst; erst wenn Stripe sie annimmt, werden Rechte entzogen. Wirkt sie dort nicht, bleibt alles unverändert.
|
||||
* Jede Erstattung wird im Zahlungsjournal gegengebucht, in derselben Transaktion: Bei Stripe mit Rückzahlungs-ID
|
||||
* und Zeitpunkt von Stripe, sonst (Überweisung, Testzahlung) mit `$refundedOn` (Tag der Rückzahlung, ohne Angabe
|
||||
* jetzt) und `$reference` (Überweisungsreferenz o. ä., sonst eine feste Kennung der Bestellung).
|
||||
*/
|
||||
public function refund(Order $order, string $reason, ?StripeGateway $stripe = null, ?User $actor = null, string|CarbonInterface|null $refundedOn = null, ?string $reference = null): Order
|
||||
public function refund(Order $order, string $reason): Order
|
||||
{
|
||||
$reason = trim($reason);
|
||||
|
||||
@@ -319,31 +150,22 @@ public function refund(Order $order, string $reason, ?StripeGateway $stripe = nu
|
||||
throw new DomainRuleException('Eine Erstattung braucht eine Begründung.');
|
||||
}
|
||||
|
||||
$current = Order::query()->findOrFail($order->id);
|
||||
$stripePayment = $current->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->latest('id')->first();
|
||||
$manualAt = $refundedOn === null ? now() : PaymentJournal::dayOf($refundedOn, $current->created_at);
|
||||
$booking = null;
|
||||
|
||||
if ($current->status === 'bezahlt' && $stripePayment !== null) {
|
||||
$result = ($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
|
||||
$booking = ['reference' => $result['id'], 'status' => $result['status'], 'at' => $result['created'] ?? now()];
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $reason, $actor, $manualAt, $reference, $booking): Order {
|
||||
return DB::transaction(function () use ($order, $reason): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status !== 'bezahlt') {
|
||||
throw new DomainRuleException('Nur eine bezahlte Bestellung kann erstattet werden.');
|
||||
}
|
||||
|
||||
foreach ($order->lines()->orderBy('id')->get() as $line) {
|
||||
$acquisition = Acquisition::query()->where([
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
])->first();
|
||||
$line = $order->lines()->firstOrFail();
|
||||
$acquisition = Acquisition::query()->where([
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
])->first();
|
||||
|
||||
foreach ($acquisition?->grants ?? [] as $grant) {
|
||||
if ($acquisition !== null) {
|
||||
foreach ($acquisition->grants as $grant) {
|
||||
if ($grant->status === GrantStatus::Aktiv) {
|
||||
$grant->status = GrantStatus::Widerrufen;
|
||||
$grant->status_reason = $reason;
|
||||
@@ -352,16 +174,6 @@ 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();
|
||||
@@ -370,43 +182,6 @@ public function refund(Order $order, string $reason, ?StripeGateway $stripe = nu
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Mitglied erklärt den Widerruf (Verkaufsstart: kein Selbstbedienungs-Widerruf). Es entzieht nichts und
|
||||
* erstattet nichts; der Betreiber prüft den Fall (Erlöschen des Widerrufsrechts bei sofortiger Bereitstellung mit
|
||||
* ausdrücklicher Zustimmung) und erstattet bei Bedarf in der Bestellverwaltung.
|
||||
*/
|
||||
public function requestWithdrawal(Order $order, string $note): Order
|
||||
{
|
||||
if (! in_array($order->status, ['bezahlt', 'offen'], true)) {
|
||||
throw new DomainRuleException('Für diese Bestellung kann kein Widerruf erklärt werden.');
|
||||
}
|
||||
|
||||
if ($order->withdrawal_requested_at !== null) {
|
||||
return $order;
|
||||
}
|
||||
|
||||
$order->withdrawal_requested_at = now();
|
||||
$order->withdrawal_note = trim($note) !== '' ? trim($note) : null;
|
||||
$order->save();
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
private function assertActive(User $user): void
|
||||
{
|
||||
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
||||
}
|
||||
}
|
||||
|
||||
/** Eine Bestellung auf Rechnung oder über Stripe wird nie mit der Testzahlung bestätigt. */
|
||||
private function assertTestOrder(Order $order): void
|
||||
{
|
||||
if (in_array(Order::query()->whereKey($order->id)->value('payment_method'), ['rechnung', 'stripe'], true)) {
|
||||
throw new DomainRuleException('Diese Bestellung wird nicht mit der Testzahlung bezahlt.');
|
||||
}
|
||||
}
|
||||
|
||||
private function assertTestDriver(): void
|
||||
{
|
||||
if (app()->isProduction() || config('services.payment.driver') !== 'test') {
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
/**
|
||||
* Reine Rechenregel für den Rabatt je Position (ganze Cent, keine Datenbank, keine Uhr).
|
||||
*
|
||||
* Prozent: je Position gerundet (kaufmännisch, ab 0,5 Cent nach oben), höchstens der Positionspreis. Die Summe ist
|
||||
* die Summe der gerundeten Positionsrabatte. Das kann um bis zu einen Cent je Position von der Rundung auf der
|
||||
* Warenkorbsumme abweichen (Rechenbeispiel in der Abnahme zum Verkaufsstart, Fachfrage).
|
||||
*
|
||||
* Betrag: Der Festbetrag gilt je Bestellung, höchstens bis zur Summe der betroffenen Positionen. Er wird anteilig
|
||||
* zum Positionspreis verteilt; verbleibende Cent erhalten die Positionen mit dem größten Rest, bei Gleichstand die
|
||||
* frühere Position.
|
||||
*/
|
||||
final class DiscountCalculator
|
||||
{
|
||||
/**
|
||||
* @param array<int|string, int> $prices Schlüssel der Position => Preis in Cent (nur betroffene Positionen)
|
||||
* @return array<int|string, int> Schlüssel => Rabatt in Cent
|
||||
*/
|
||||
public static function allocate(string $kind, ?int $percent, ?int $amountCents, array $prices): array
|
||||
{
|
||||
$discounts = array_fill_keys(array_keys($prices), 0);
|
||||
|
||||
if ($prices === []) {
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
if ($kind === DiscountCode::PERCENT) {
|
||||
$percent = max(0, min(100, (int) $percent));
|
||||
|
||||
foreach ($prices as $key => $price) {
|
||||
$discounts[$key] = min($price, intdiv($price * $percent + 50, 100));
|
||||
}
|
||||
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
$sum = array_sum($prices);
|
||||
$total = min(max(0, (int) $amountCents), $sum);
|
||||
|
||||
if ($total === 0 || $sum === 0) {
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
$remainders = [];
|
||||
$given = 0;
|
||||
|
||||
foreach ($prices as $key => $price) {
|
||||
$share = intdiv($total * $price, $sum);
|
||||
$discounts[$key] = $share;
|
||||
$remainders[$key] = ($total * $price) % $sum;
|
||||
$given += $share;
|
||||
}
|
||||
|
||||
$rest = $total - $given;
|
||||
$order = array_keys($prices);
|
||||
usort($order, fn ($left, $right): int => $remainders[$right] <=> $remainders[$left]);
|
||||
|
||||
foreach ($order as $key) {
|
||||
if ($rest === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
if ($discounts[$key] < $prices[$key]) {
|
||||
$discounts[$key]++;
|
||||
$rest--;
|
||||
}
|
||||
}
|
||||
|
||||
return $discounts;
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Domain\Commerce\Money;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Rabattcode (PAY-008, FACH-14). Zwei voneinander unabhängige Einstellungen:
|
||||
* - Geltungsbereich: gesamter Warenkorb oder nur ausdrücklich gewählte Ziele (Angebot, Lizenzartikel, Paket);
|
||||
* - Einlösungsberechtigung: allgemein oder nur für ausdrücklich freigeschaltete Konten (Freigabe gilt nur für diesen Code).
|
||||
* Der Rabatt ändert den Preis, nie den Nutzungsumfang.
|
||||
*/
|
||||
class DiscountCode extends Model
|
||||
{
|
||||
public const PERCENT = 'prozent';
|
||||
|
||||
public const AMOUNT = 'betrag';
|
||||
|
||||
public const SCOPE_CART = 'warenkorb';
|
||||
|
||||
public const SCOPE_SELECTED = 'auswahl';
|
||||
|
||||
public const OPEN = 'allgemein';
|
||||
|
||||
public const RESTRICTED = 'freigabe';
|
||||
|
||||
public const TARGET_OFFER = 'angebot';
|
||||
|
||||
public const TARGET_ARTICLE = 'lizenzartikel';
|
||||
|
||||
public const TARGET_BUNDLE = 'paket';
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'label',
|
||||
'kind',
|
||||
'percent',
|
||||
'amount_cents',
|
||||
'scope',
|
||||
'eligibility',
|
||||
'valid_from',
|
||||
'valid_until',
|
||||
'active',
|
||||
'note',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'valid_from' => 'datetime',
|
||||
'valid_until' => 'datetime',
|
||||
'active' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** Eingabe und Speicherung vereinheitlicht: ohne Leerzeichen, Großschreibung. */
|
||||
public static function normalise(string $input): string
|
||||
{
|
||||
return mb_strtoupper((string) preg_replace('/\s+/u', '', $input));
|
||||
}
|
||||
|
||||
public function targets(): HasMany
|
||||
{
|
||||
return $this->hasMany(DiscountCodeTarget::class);
|
||||
}
|
||||
|
||||
public function releases(): HasMany
|
||||
{
|
||||
return $this->hasMany(DiscountRelease::class)->latest('id');
|
||||
}
|
||||
|
||||
public function restricted(): bool
|
||||
{
|
||||
return $this->eligibility === self::RESTRICTED;
|
||||
}
|
||||
|
||||
public function forSelection(): bool
|
||||
{
|
||||
return $this->scope === self::SCOPE_SELECTED;
|
||||
}
|
||||
|
||||
/** Lesbare Höhe: „10 %“ oder „5,00 €“. */
|
||||
public function valueLabel(): string
|
||||
{
|
||||
return $this->kind === self::PERCENT
|
||||
? (int) $this->percent.' %'
|
||||
: Money::format((int) $this->amount_cents);
|
||||
}
|
||||
|
||||
/** Zeitlicher Zustand zum Zeitpunkt: 'aktiv', 'abgelaufen', 'noch_nicht' oder 'deaktiviert'. */
|
||||
public function stateAt(CarbonInterface $now): string
|
||||
{
|
||||
return match (true) {
|
||||
! $this->active => 'deaktiviert',
|
||||
$this->valid_from !== null && $this->valid_from->greaterThan($now) => 'noch_nicht',
|
||||
$this->valid_until !== null && ! $this->valid_until->greaterThan($now) => 'abgelaufen',
|
||||
default => 'aktiv',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Ausdrücklich gewähltes Ziel eines Codes mit Geltungsbereich „Auswahl“. Ein Paket ist ein eigenes Ziel; seine
|
||||
* Rabattfähigkeit folgt nie aus einem enthaltenen Lizenzartikel und umgekehrt.
|
||||
*/
|
||||
class DiscountCodeTarget extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'discount_code_id',
|
||||
'target_type',
|
||||
'target_id',
|
||||
];
|
||||
|
||||
public function code(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Freigabe eines Mitgliedskontos für genau einen Code. Freigaben werden nie gelöscht, nur entzogen; Verlauf und
|
||||
* Begründung bleiben erhalten. Eine Freigabe für Code X berechtigt nicht zur Nutzung von Code Y.
|
||||
*/
|
||||
class DiscountRelease extends Model
|
||||
{
|
||||
protected $table = 'discount_code_releases';
|
||||
|
||||
protected $fillable = [
|
||||
'discount_code_id',
|
||||
'user_id',
|
||||
'granted_by',
|
||||
'granted_at',
|
||||
'valid_until',
|
||||
'revoked_by',
|
||||
'revoked_at',
|
||||
'reason',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'granted_at' => 'datetime',
|
||||
'valid_until' => 'datetime',
|
||||
'revoked_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function code(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function grantor(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'granted_by');
|
||||
}
|
||||
|
||||
public function isActiveAt(CarbonInterface $now): bool
|
||||
{
|
||||
return $this->revoked_at === null
|
||||
&& $this->granted_at->lessThanOrEqualTo($now)
|
||||
&& ($this->valid_until === null || $this->valid_until->greaterThan($now));
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
/**
|
||||
* Ergebnis der Prüfung eines Codes gegen einen Warenkorb: angewandt (Rabatt je Option) oder nicht angewandt mit
|
||||
* einer verständlichen Begründung. Ein Code, der gerade nicht gilt, bleibt als Ergebnis sichtbar, damit der Käufer
|
||||
* den Grund erfährt.
|
||||
*/
|
||||
final class DiscountResult
|
||||
{
|
||||
public const OK = 'ok';
|
||||
|
||||
public const UNKNOWN = 'unbekannt';
|
||||
|
||||
public const INACTIVE = 'deaktiviert';
|
||||
|
||||
public const NOT_YET = 'noch_nicht';
|
||||
|
||||
public const EXPIRED = 'abgelaufen';
|
||||
|
||||
public const LOGIN = 'anmeldung';
|
||||
|
||||
public const NO_RELEASE = 'keine_freigabe';
|
||||
|
||||
public const NO_MATCH = 'keine_position';
|
||||
|
||||
public const TOO_HIGH = 'zu_hoch';
|
||||
|
||||
/**
|
||||
* @param array<int, int> $perOffer Kennung der Option => Rabatt in Cent
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly ?DiscountCode $code,
|
||||
public readonly string $state,
|
||||
public readonly ?string $message = null,
|
||||
public readonly array $perOffer = [],
|
||||
) {}
|
||||
|
||||
public function applied(): bool
|
||||
{
|
||||
return $this->state === self::OK && $this->totalCents() > 0;
|
||||
}
|
||||
|
||||
public function totalCents(): int
|
||||
{
|
||||
return $this->state === self::OK ? array_sum($this->perOffer) : 0;
|
||||
}
|
||||
|
||||
public function forOffer(int $offerId): int
|
||||
{
|
||||
return $this->state === self::OK ? (int) ($this->perOffer[$offerId] ?? 0) : 0;
|
||||
}
|
||||
|
||||
/** Für die Bestellung festgehaltene Angaben zum Zeitpunkt der Bestellung. */
|
||||
public function snapshot(): array
|
||||
{
|
||||
return [
|
||||
'code' => $this->code?->code,
|
||||
'label' => $this->code?->label,
|
||||
'kind' => $this->code?->kind,
|
||||
'percent' => $this->code?->percent,
|
||||
'amount_cents' => $this->code?->amount_cents,
|
||||
'scope' => $this->code?->scope,
|
||||
'eligibility' => $this->code?->eligibility,
|
||||
'discount_cents' => $this->totalCents(),
|
||||
];
|
||||
}
|
||||
|
||||
/** Teil der Prüfsumme der Bestellübersicht. */
|
||||
public function digestPart(): string
|
||||
{
|
||||
$parts = [];
|
||||
$perOffer = $this->perOffer;
|
||||
ksort($perOffer);
|
||||
|
||||
foreach ($perOffer as $offerId => $cents) {
|
||||
$parts[] = $offerId.'='.$cents;
|
||||
}
|
||||
|
||||
return ($this->code?->id ?? 0).':'.$this->state.':'.implode(',', $parts);
|
||||
}
|
||||
}
|
||||
@@ -1,327 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\CartLine;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Prüfung und Pflege von Rabattcodes. Die Prüfung läuft serverseitig bei der Eingabe, in jeder Übersicht und
|
||||
* unmittelbar vor Bestellabschluss (unter Sperre); sie liest nur und ändert keine Bestellung.
|
||||
*/
|
||||
class DiscountService
|
||||
{
|
||||
/** Kleinster Zahlbetrag einer Bestellung mit Rabatt (Mindestbetrag der Kartenzahlung bei Stripe: 0,50 EUR). */
|
||||
public const MIN_PAYABLE_CENTS = 50;
|
||||
|
||||
public function find(string $input): ?DiscountCode
|
||||
{
|
||||
$code = DiscountCode::normalise($input);
|
||||
|
||||
return $code === '' ? null : DiscountCode::query()->where('code', $code)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<CartLine> $lines nur Positionen, die in die Bestellung eingehen
|
||||
*/
|
||||
public function evaluate(DiscountCode $code, ?User $user, array $lines, ?CarbonInterface $now = null, bool $lock = false): DiscountResult
|
||||
{
|
||||
$now ??= now();
|
||||
|
||||
$timing = $code->stateAt($now);
|
||||
|
||||
if ($timing !== 'aktiv') {
|
||||
return new DiscountResult($code, $timing, match ($timing) {
|
||||
'deaktiviert' => 'Dieser Code ist nicht mehr gültig, der Betreiber hat ihn deaktiviert.',
|
||||
'noch_nicht' => 'Dieser Code gilt erst ab dem '.$code->valid_from?->timezone(config('app.timezone'))->format('d.m.Y').'.',
|
||||
default => 'Dieser Code ist abgelaufen (gültig bis '.$code->valid_until?->timezone(config('app.timezone'))->format('d.m.Y').').',
|
||||
});
|
||||
}
|
||||
|
||||
if ($code->restricted()) {
|
||||
if ($user === null) {
|
||||
return new DiscountResult($code, DiscountResult::LOGIN, 'Dieser Code gilt nur für freigeschaltete Konten. Melde dich an, damit wir prüfen können, ob er für dein Konto gilt.');
|
||||
}
|
||||
|
||||
if ($this->activeRelease($code, $user, $now, $lock) === null) {
|
||||
return new DiscountResult($code, DiscountResult::NO_RELEASE, 'Dieser Code ist für dein Konto nicht freigeschaltet. Er gilt nur für Konten, die der Betreiber ausdrücklich dafür freigegeben hat. Wenn du denkst, dass dir die Freigabe zusteht, wende dich an den Betreiber.');
|
||||
}
|
||||
}
|
||||
|
||||
$matching = [];
|
||||
|
||||
foreach ($lines as $line) {
|
||||
if ($line->version !== null && $this->matches($code, $line->offer, $line->version)) {
|
||||
$matching[$line->offer->id] = (int) $line->currentPriceCents;
|
||||
}
|
||||
}
|
||||
|
||||
if ($matching === []) {
|
||||
return new DiscountResult($code, DiscountResult::NO_MATCH, $code->forSelection()
|
||||
? 'Dieser Code gilt nur für bestimmte Angebote, und keines davon liegt in deiner Bestellung.'
|
||||
: 'In deiner Bestellung gibt es keine Position, auf die der Code angewendet werden kann.');
|
||||
}
|
||||
|
||||
$perOffer = DiscountCalculator::allocate($code->kind, $code->percent, $code->amount_cents, $matching);
|
||||
$payable = array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $lines)) - array_sum($perOffer);
|
||||
|
||||
if ($payable < self::MIN_PAYABLE_CENTS) {
|
||||
return new DiscountResult($code, DiscountResult::TOO_HIGH, 'Mit diesem Code läge der Zahlbetrag unter '.Money::format(self::MIN_PAYABLE_CENTS).'. Das ist beim Start nicht vorgesehen. Wähle zusätzlich eine weitere Position oder verzichte auf den Code.');
|
||||
}
|
||||
|
||||
return new DiscountResult($code, DiscountResult::OK, null, $perOffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Passt die Position? Verglichen werden nur die ausdrücklich gewählten Ziele mit den unmittelbaren Positionen der
|
||||
* Angebotsfassung. Ein Paket gilt nur, wenn es selbst gewählt ist; ein enthaltener Artikel macht es nicht
|
||||
* rabattfähig, und ein Artikel in einem Paket macht das Angebot nicht rabattfähig.
|
||||
*/
|
||||
public function matches(DiscountCode $code, Offer $offer, OfferVersion $version): bool
|
||||
{
|
||||
if (! $code->forSelection()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$targets = $code->targets->groupBy('target_type')->map(fn ($rows) => $rows->pluck('target_id')->map(fn ($id): int => (int) $id)->all());
|
||||
|
||||
if (in_array($offer->id, $targets->get(DiscountCode::TARGET_OFFER, []), true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$version->loadMissing('lines.bundleVersion');
|
||||
|
||||
foreach ($version->lines as $line) {
|
||||
if ($line->license_article_id !== null && in_array((int) $line->license_article_id, $targets->get(DiscountCode::TARGET_ARTICLE, []), true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($line->bundleVersion !== null && in_array((int) $line->bundleVersion->bundle_id, $targets->get(DiscountCode::TARGET_BUNDLE, []), true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function activeRelease(DiscountCode $code, User $user, ?CarbonInterface $now = null, bool $lock = false): ?DiscountRelease
|
||||
{
|
||||
$now ??= now();
|
||||
$query = DiscountRelease::query()->where('discount_code_id', $code->id)->where('user_id', $user->id)->whereNull('revoked_at');
|
||||
|
||||
if ($lock) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
return $query->get()->first(fn (DiscountRelease $release): bool => $release->isActiveAt($now));
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt einen Code an oder ändert ihn. Gleiche Prüfung für Anlegen und Bearbeiten.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @param list<array{type: string, id: int}> $targets
|
||||
*/
|
||||
public function save(array $data, array $targets, ?DiscountCode $existing = null): DiscountCode
|
||||
{
|
||||
$code = DiscountCode::normalise((string) ($data['code'] ?? ''));
|
||||
$label = trim((string) ($data['label'] ?? ''));
|
||||
|
||||
if (preg_match('/^[A-Z0-9][A-Z0-9_-]{2,39}$/', $code) !== 1) {
|
||||
throw new DomainRuleException('Der Code besteht aus 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich oder Unterstrich, ohne Leerzeichen.');
|
||||
}
|
||||
|
||||
if ($label === '') {
|
||||
throw new DomainRuleException('Der Name des Codes fehlt. Er ist nur für die Verwaltung und erscheint nicht im Shop.');
|
||||
}
|
||||
|
||||
if (DiscountCode::query()->where('code', $code)->when($existing !== null, fn ($query) => $query->whereKeyNot($existing->id))->exists()) {
|
||||
throw new DomainRuleException('Diesen Code gibt es schon.');
|
||||
}
|
||||
|
||||
$kind = (string) ($data['kind'] ?? '');
|
||||
$percent = null;
|
||||
$amount = null;
|
||||
|
||||
if ($kind === DiscountCode::PERCENT) {
|
||||
$percent = (int) ($data['percent'] ?? 0);
|
||||
|
||||
if ($percent < 1 || $percent > 100) {
|
||||
throw new DomainRuleException('Der Prozentsatz liegt zwischen 1 und 100.');
|
||||
}
|
||||
} elseif ($kind === DiscountCode::AMOUNT) {
|
||||
$amount = Money::parse($data['amount_euro'] ?? ($data['amount_cents'] ?? null));
|
||||
|
||||
if ($amount === null || $amount <= 0) {
|
||||
throw new DomainRuleException('Der Rabattbetrag ist ein Eurobetrag über 0,00 €.');
|
||||
}
|
||||
} else {
|
||||
throw new DomainRuleException('Die Art des Rabatts ist Prozent oder fester Betrag.');
|
||||
}
|
||||
|
||||
$scope = (string) ($data['scope'] ?? '');
|
||||
$eligibility = (string) ($data['eligibility'] ?? '');
|
||||
|
||||
if (! in_array($scope, [DiscountCode::SCOPE_CART, DiscountCode::SCOPE_SELECTED], true)) {
|
||||
throw new DomainRuleException('Der Geltungsbereich ist der gesamte Warenkorb oder eine Auswahl.');
|
||||
}
|
||||
|
||||
if (! in_array($eligibility, [DiscountCode::OPEN, DiscountCode::RESTRICTED], true)) {
|
||||
throw new DomainRuleException('Die Einlösung ist allgemein oder auf freigeschaltete Konten beschränkt.');
|
||||
}
|
||||
|
||||
$targets = $this->cleanTargets($targets);
|
||||
|
||||
if ($scope === DiscountCode::SCOPE_SELECTED && $targets === []) {
|
||||
throw new DomainRuleException('Wähle mindestens ein Angebot, einen Lizenzartikel oder ein Paket, für das der Code gilt, oder lass ihn für den gesamten Warenkorb gelten.');
|
||||
}
|
||||
|
||||
$from = $this->date($data['valid_from'] ?? null);
|
||||
$until = $this->date($data['valid_until'] ?? null, true);
|
||||
|
||||
if ($from !== null && $until !== null && $until->lessThanOrEqualTo($from)) {
|
||||
throw new DomainRuleException('Das Ende der Gültigkeit liegt vor dem Beginn.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($existing, $code, $label, $kind, $percent, $amount, $scope, $eligibility, $from, $until, $data, $targets): DiscountCode {
|
||||
$model = $existing ?? new DiscountCode;
|
||||
$model->fill([
|
||||
'code' => $code,
|
||||
'label' => $label,
|
||||
'kind' => $kind,
|
||||
'percent' => $percent,
|
||||
'amount_cents' => $amount,
|
||||
'scope' => $scope,
|
||||
'eligibility' => $eligibility,
|
||||
'valid_from' => $from,
|
||||
'valid_until' => $until,
|
||||
'active' => (bool) ($data['active'] ?? true),
|
||||
'note' => filled($data['note'] ?? null) ? trim((string) $data['note']) : null,
|
||||
]);
|
||||
$model->save();
|
||||
|
||||
$model->targets()->delete();
|
||||
|
||||
if ($scope === DiscountCode::SCOPE_SELECTED) {
|
||||
foreach ($targets as $target) {
|
||||
$model->targets()->create(['target_type' => $target['type'], 'target_id' => $target['id']]);
|
||||
}
|
||||
}
|
||||
|
||||
return $model->load('targets');
|
||||
});
|
||||
}
|
||||
|
||||
public function setActive(DiscountCode $code, bool $active): DiscountCode
|
||||
{
|
||||
$code->active = $active;
|
||||
$code->save();
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schaltet ein Konto für genau diesen Code frei. Eine zweite aktive Freigabe desselben Kontos gibt es nicht.
|
||||
*/
|
||||
public function release(DiscountCode $code, User $member, ?User $actor, ?CarbonInterface $until = null, ?string $reason = null): DiscountRelease
|
||||
{
|
||||
if (! $code->restricted()) {
|
||||
throw new DomainRuleException('Dieser Code ist allgemein einlösbar. Freigaben gibt es nur für Codes mit beschränkter Einlösung.');
|
||||
}
|
||||
|
||||
if ($member->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein Mitgliedskonto kann für einen Code freigeschaltet werden.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($code, $member, $actor, $until, $reason): DiscountRelease {
|
||||
DiscountCode::query()->whereKey($code->id)->lockForUpdate()->firstOrFail();
|
||||
|
||||
if ($this->activeRelease($code, $member) !== null) {
|
||||
throw new DomainRuleException('Dieses Konto ist für den Code bereits freigeschaltet.');
|
||||
}
|
||||
|
||||
if ($until !== null && $until->lessThanOrEqualTo(now())) {
|
||||
throw new DomainRuleException('Das Ende der Freigabe liegt in der Vergangenheit.');
|
||||
}
|
||||
|
||||
return DiscountRelease::query()->create([
|
||||
'discount_code_id' => $code->id,
|
||||
'user_id' => $member->id,
|
||||
'granted_by' => $actor?->id,
|
||||
'granted_at' => now(),
|
||||
'valid_until' => $until,
|
||||
'reason' => filled($reason) ? trim((string) $reason) : null,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Entzieht die Freigabe. Sie bleibt mit Zeitpunkt, Person und Begründung gespeichert.
|
||||
*/
|
||||
public function revoke(DiscountRelease $release, ?User $actor, ?string $reason = null): DiscountRelease
|
||||
{
|
||||
return DB::transaction(function () use ($release, $actor, $reason): DiscountRelease {
|
||||
$release = DiscountRelease::query()->lockForUpdate()->findOrFail($release->id);
|
||||
|
||||
if ($release->revoked_at !== null) {
|
||||
throw new DomainRuleException('Diese Freigabe ist bereits entzogen.');
|
||||
}
|
||||
|
||||
$release->revoked_at = now();
|
||||
$release->revoked_by = $actor?->id;
|
||||
$release->reason = filled($reason) ? trim((string) $reason) : $release->reason;
|
||||
$release->save();
|
||||
|
||||
return $release;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{type: string, id: int}> $targets
|
||||
* @return list<array{type: string, id: int}>
|
||||
*/
|
||||
private function cleanTargets(array $targets): array
|
||||
{
|
||||
$clean = [];
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$type = (string) ($target['type'] ?? '');
|
||||
$id = (int) ($target['id'] ?? 0);
|
||||
$exists = match ($type) {
|
||||
DiscountCode::TARGET_OFFER => Offer::query()->whereKey($id)->exists(),
|
||||
DiscountCode::TARGET_ARTICLE => LicenseArticle::query()->whereKey($id)->exists(),
|
||||
DiscountCode::TARGET_BUNDLE => Bundle::query()->whereKey($id)->exists(),
|
||||
default => false,
|
||||
};
|
||||
|
||||
if (! $exists) {
|
||||
throw new DomainRuleException('Ein gewähltes Ziel des Codes gibt es nicht (mehr).');
|
||||
}
|
||||
|
||||
$clean[$type.':'.$id] = ['type' => $type, 'id' => $id];
|
||||
}
|
||||
|
||||
return array_values($clean);
|
||||
}
|
||||
|
||||
/** Ein Datum ohne Uhrzeit gilt als Tag: ab Tagesbeginn, als Ende einschließlich des ganzen Tages. */
|
||||
private function date(mixed $value, bool $endOfDay = false): ?CarbonInterface
|
||||
{
|
||||
if (! filled($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = Carbon::parse((string) $value, config('app.timezone'));
|
||||
|
||||
return $endOfDay && strlen(trim((string) $value)) <= 10 ? $date->endOfDay() : $date;
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
|
||||
/**
|
||||
* Beträge werden als ganze Cent gespeichert und in Euro angezeigt und eingegeben (deutsches Format).
|
||||
*/
|
||||
final class Money
|
||||
{
|
||||
/** Obergrenze eines Preises (1.000.000 €), weit unter dem Wertebereich der Datenbank. */
|
||||
public const MAX_CENTS = 100_000_000;
|
||||
|
||||
public static function format(?int $cents): string
|
||||
{
|
||||
return $cents === null ? '–' : number_format($cents / 100, 2, ',', '.').' €';
|
||||
}
|
||||
|
||||
/**
|
||||
* Euro-Eingabe („12,50“, „1.299“, „5“) als Cent. Leere Eingabe ergibt null.
|
||||
*/
|
||||
public static function parse(string|int|float|null $input): ?int
|
||||
{
|
||||
if ($input === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$text = trim((string) $input);
|
||||
|
||||
if ($text === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$text = str_replace([' ', '€'], '', $text);
|
||||
|
||||
if (str_contains($text, ',')) {
|
||||
$text = str_replace('.', '', $text);
|
||||
$text = str_replace(',', '.', $text);
|
||||
} elseif (preg_match('/^\d{1,3}(\.\d{3})+$/', $text) === 1) {
|
||||
$text = str_replace('.', '', $text);
|
||||
}
|
||||
|
||||
if (preg_match('/^\d+(\.\d{1,2})?$/', $text) !== 1) {
|
||||
throw new DomainRuleException('Der Preis ist kein gültiger Eurobetrag, zum Beispiel 12,50.');
|
||||
}
|
||||
|
||||
$cents = (int) round(((float) $text) * 100);
|
||||
|
||||
if ($cents > self::MAX_CENTS) {
|
||||
throw new DomainRuleException('Der Preis ist zu hoch. Zulässig sind höchstens '.self::format(self::MAX_CENTS).'.');
|
||||
}
|
||||
|
||||
return $cents;
|
||||
}
|
||||
}
|
||||
@@ -15,41 +15,8 @@ class Order extends Model
|
||||
'party_id',
|
||||
'status',
|
||||
'holder_kind',
|
||||
'total_cents',
|
||||
'currency',
|
||||
'subtotal_cents',
|
||||
'discount_cents',
|
||||
'discount_code_id',
|
||||
'discount_snapshot',
|
||||
'payment_method',
|
||||
'terms_accepted_at',
|
||||
'terms_snapshot',
|
||||
'withdrawal_requested_at',
|
||||
'withdrawal_note',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'discount_snapshot' => 'array',
|
||||
'terms_snapshot' => 'array',
|
||||
'terms_accepted_at' => 'datetime',
|
||||
'withdrawal_requested_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** Listenpreise vor Rabatt; bei älteren Bestellungen die Summe der Positionen. */
|
||||
public function subtotal(): int
|
||||
{
|
||||
return (int) ($this->subtotal_cents ?? $this->total_cents ?? $this->lines->sum('price_cents'));
|
||||
}
|
||||
|
||||
/** Endgültiger Zahlbetrag. */
|
||||
public function payable(): int
|
||||
{
|
||||
return (int) ($this->total_cents ?? $this->lines->sum('price_cents'));
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Identity\Membership;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Für wen ein Konto bestellen darf: für sich selbst (Person) und für Organisationen, bei denen es eine aktive
|
||||
* Mitgliedschaft mit Bestellberechtigung hat. Eine Bestellung hat genau einen Lizenzinhaber.
|
||||
*/
|
||||
class OrderHolders
|
||||
{
|
||||
/**
|
||||
* @return Collection<int, Party>
|
||||
*/
|
||||
public function for(User $user): Collection
|
||||
{
|
||||
$holders = collect();
|
||||
|
||||
if ($user->party_id !== null) {
|
||||
$person = Party::query()->find($user->party_id);
|
||||
|
||||
if ($person !== null) {
|
||||
$holders->push($person);
|
||||
}
|
||||
}
|
||||
|
||||
$organisations = Membership::query()
|
||||
->active()
|
||||
->where('user_id', $user->id)
|
||||
->where('may_order', true)
|
||||
->with('organisation')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->map(fn (Membership $membership): ?Party => $membership->organisation)
|
||||
->filter(fn (?Party $party): bool => $party !== null && $party->type === PartyType::Organisation);
|
||||
|
||||
return $holders->concat($organisations)->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Der gewählte Inhaber; ohne Wahl die Person, bei Angeboten nur für Organisationen die erste Organisation.
|
||||
*/
|
||||
public function resolve(User $user, ?int $partyId, bool $preferOrganisation = false): Party
|
||||
{
|
||||
$holders = $this->for($user);
|
||||
|
||||
if ($partyId !== null) {
|
||||
$chosen = $holders->first(fn (Party $party): bool => $party->id === $partyId);
|
||||
|
||||
if ($chosen === null) {
|
||||
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
|
||||
}
|
||||
|
||||
return $chosen;
|
||||
}
|
||||
|
||||
if ($preferOrganisation) {
|
||||
$organisation = $holders->first(fn (Party $party): bool => $party->type === PartyType::Organisation);
|
||||
|
||||
if ($organisation !== null) {
|
||||
return $organisation;
|
||||
}
|
||||
}
|
||||
|
||||
$person = $holders->first(fn (Party $party): bool => $party->type === PartyType::Person);
|
||||
|
||||
return $person ?? throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Identity\Party;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
@@ -18,31 +17,13 @@ class OrderLine extends Model
|
||||
'term_rule',
|
||||
'update_promise',
|
||||
'holder_kind',
|
||||
'currency',
|
||||
'tax_class',
|
||||
'grant_kind',
|
||||
'holder_party_id',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'discount_cents',
|
||||
];
|
||||
|
||||
/** Preis dieser Position nach Rabatt. */
|
||||
public function payable(): int
|
||||
{
|
||||
return (int) $this->price_cents - (int) $this->discount_cents;
|
||||
}
|
||||
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
|
||||
public function holder(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Party::class, 'holder_party_id');
|
||||
}
|
||||
|
||||
public function offerVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(OfferVersion::class);
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Domain\Identity\Party;
|
||||
|
||||
/**
|
||||
* „Bereits erworben“ (FACH-59): Der vorgesehene Lizenzinhaber hat bereits eine gültige Lizenz mit demselben Umfang
|
||||
* und denselben Nutzungsrechten. Maßgeblich ist genau ein Erwerb, der jeden Umfangsposten der Angebotsfassung mit
|
||||
* gleichem Zweck, gleichen Fähigkeiten und gleichen Optionen trägt. Rechte mehrerer Erwerbe werden nicht zu einer
|
||||
* neuen Lizenz kombiniert. Alle Erwerbsarten zählen (Kauf, freier Abruf, manuelle Vergabe), sofern aktiv und gültig.
|
||||
*/
|
||||
class OwnershipCheck
|
||||
{
|
||||
public function covers(Party $holder, OfferVersion $version): bool
|
||||
{
|
||||
$needed = $this->needed($version);
|
||||
|
||||
if ($needed === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$now = now();
|
||||
$byAcquisition = Grant::query()
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id))
|
||||
->with('acquisition')
|
||||
->get()
|
||||
->filter(fn (Grant $grant): bool => ($grant->valid_from === null || ! $grant->valid_from->greaterThan($now))
|
||||
&& ($grant->valid_until === null || $grant->valid_until->greaterThan($now)))
|
||||
->groupBy('acquisition_id');
|
||||
|
||||
$wanted = LicenceScope::key($version->licence_scope, $version->trainer_count);
|
||||
|
||||
foreach ($byAcquisition as $grants) {
|
||||
$conditions = (array) ($grants->first()->acquisition?->conditions ?? []);
|
||||
|
||||
// Gleicher Umfang heißt auch gleicher Nutzerkreis: Eine Einzellizenz deckt keine Mehrfachlizenz ab und
|
||||
// umgekehrt (der Nutzerkreis wird nicht aus Zweck oder Preis abgeleitet).
|
||||
if (LicenceScope::key($conditions['licence_scope'] ?? null, isset($conditions['trainer_count']) ? (int) $conditions['trainer_count'] : null) !== $wanted) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$have = [];
|
||||
|
||||
foreach ($grants as $grant) {
|
||||
$have[$grant->license_article_id.'|'.$this->fingerprint($grant->rights_snapshot ?? [])] = true;
|
||||
}
|
||||
|
||||
if (array_diff_key($needed, $have) === []) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, true>
|
||||
*/
|
||||
private function needed(OfferVersion $version): array
|
||||
{
|
||||
$needed = [];
|
||||
$version->loadMissing('resolvedScopes.rights');
|
||||
|
||||
foreach ($version->resolvedScopes as $scope) {
|
||||
$needed[$scope->license_article_id.'|'.$this->fingerprint([
|
||||
'purpose' => $scope->rights->purpose,
|
||||
'capabilities' => $scope->rights->capabilities,
|
||||
'options' => $scope->rights->options ?? [],
|
||||
])] = true;
|
||||
}
|
||||
|
||||
return $needed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reihenfolge von Schlüsseln und Aktionen spielt keine Rolle.
|
||||
*
|
||||
* @param array<string, mixed> $rights
|
||||
*/
|
||||
private function fingerprint(array $rights): string
|
||||
{
|
||||
$capabilities = [];
|
||||
|
||||
foreach ((array) ($rights['capabilities'] ?? []) as $class => $actions) {
|
||||
$actions = array_values(array_unique((array) $actions));
|
||||
sort($actions);
|
||||
$capabilities[(string) $class] = $actions;
|
||||
}
|
||||
|
||||
ksort($capabilities);
|
||||
$options = (array) ($rights['options'] ?? []);
|
||||
ksort($options);
|
||||
|
||||
return md5(json_encode([
|
||||
'purpose' => (string) ($rights['purpose'] ?? ''),
|
||||
'capabilities' => $capabilities,
|
||||
'options' => $options,
|
||||
], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,6 @@ class Payment extends Model
|
||||
'provider',
|
||||
'status',
|
||||
'provider_reference',
|
||||
'provider_payment_ref',
|
||||
'amount_cents',
|
||||
'confirmed_by',
|
||||
];
|
||||
|
||||
public function order(): BelongsTo
|
||||
|
||||
@@ -1,353 +0,0 @@
|
||||
<?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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Filament\Support\CatalogLabels;
|
||||
|
||||
/**
|
||||
* Kaufbare Lizenzoptionen einer Produktseite aus dem veröffentlichten Katalog: aktive Angebotsfassungen mit Preis,
|
||||
* Eignung, Laufzeit, Umfang und Nutzungsrechten. Die Seite selbst (Titel, Beschreibung, Struktur) kommt aus der
|
||||
* zur Anzeige freigegebenen Komposition; hier entsteht kein zweiter Text.
|
||||
*/
|
||||
class ProductOptions
|
||||
{
|
||||
public function __construct(private readonly OfferService $offers) {}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forComposition(Composition $composition): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (Offer::query()->where('composition_id', $composition->id)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version !== null) {
|
||||
$options[] = $this->describe($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kaufbare Optionen der eigenen Produktseite eines Pakets: Angebote mit eigener Paketseite, deren aktive Fassung
|
||||
* dieses Paket verkauft.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forBundle(Bundle $bundle): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version !== null && $this->bundleOf($version)?->id === $bundle->id) {
|
||||
$options[] = $this->describe($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Paket, das die Fassung unmittelbar verkauft (erste Paketposition), sonst null.
|
||||
*/
|
||||
public function bundleOf(OfferVersion $version): ?Bundle
|
||||
{
|
||||
$version->loadMissing('lines.bundleVersion.bundle');
|
||||
|
||||
return $version->lines->first(fn ($line): bool => $line->bundleVersion !== null)?->bundleVersion?->bundle;
|
||||
}
|
||||
|
||||
/** Gruppenschlüssel der Alternativen: Produktseite eines Programms oder eigene Paketseite. */
|
||||
public function groupKey(Offer $offer): ?string
|
||||
{
|
||||
if ($offer->composition_id !== null) {
|
||||
return 'c:'.$offer->composition_id;
|
||||
}
|
||||
|
||||
if ($offer->standalone_bundle) {
|
||||
$version = $this->offers->purchasableVersion($offer) ?? $offer->versions()->orderByDesc('number')->first();
|
||||
$bundle = $version === null ? null : $this->bundleOf($version);
|
||||
|
||||
return $bundle === null ? null : 'b:'.$bundle->id;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Adresse der Produktseite, auf der die Option angeboten wird, sonst null. */
|
||||
public function pageUrl(Offer $offer): ?string
|
||||
{
|
||||
if ($offer->composition_id !== null) {
|
||||
return route('public.program', $offer->composition_id);
|
||||
}
|
||||
|
||||
$key = $this->groupKey($offer);
|
||||
|
||||
return $key !== null && str_starts_with($key, 'b:') ? route('public.package', (int) substr($key, 2)) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pakete mit eigener Produktseite und kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int}>
|
||||
*/
|
||||
public function bundleSummaries(): array
|
||||
{
|
||||
$summary = [];
|
||||
|
||||
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
$bundle = $version === null ? null : $this->bundleOf($version);
|
||||
|
||||
if ($bundle === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = $summary[$bundle->id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0];
|
||||
$summary[$bundle->id] = [
|
||||
'from_cents' => min($current['from_cents'], (int) $version->price_cents),
|
||||
'count' => $current['count'] + 1,
|
||||
];
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Der tatsächliche Umfang einer Paketseite: die Artikel aller Optionen ohne Doppelte, in der Reihenfolge der
|
||||
* Optionen, mit Name und Kurzbeschreibung aus der Redaktion.
|
||||
*
|
||||
* @param list<array<string, mixed>> $options
|
||||
* @return list<array{title: string, teaser: string}>
|
||||
*/
|
||||
public function bundleContents(array $options): array
|
||||
{
|
||||
$contents = [];
|
||||
|
||||
foreach ($options as $option) {
|
||||
$option['version']->loadMissing('resolvedScopes.article');
|
||||
|
||||
foreach ($option['version']->resolvedScopes as $item) {
|
||||
$article = $item->article;
|
||||
|
||||
if ($article === null || isset($contents[$article->id])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$profile = app(EditorialProfileReader::class)->read($article, 'detail');
|
||||
$contents[$article->id] = [
|
||||
'title' => $this->articleTitle($article),
|
||||
'teaser' => trim((string) ($profile->value('teaser') ?? '')),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($contents);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int}>
|
||||
*/
|
||||
public function summaries(): array
|
||||
{
|
||||
$summary = [];
|
||||
|
||||
foreach (Offer::query()->whereNotNull('composition_id')->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = $summary[$offer->composition_id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0];
|
||||
$summary[$offer->composition_id] = [
|
||||
'from_cents' => min($current['from_cents'], (int) $version->price_cents),
|
||||
'count' => $current['count'] + 1,
|
||||
];
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function describe(Offer $offer, OfferVersion $version): array
|
||||
{
|
||||
$version->loadMissing('resolvedScopes.article', 'resolvedScopes.rights');
|
||||
$scope = [];
|
||||
|
||||
foreach ($version->resolvedScopes as $item) {
|
||||
$faehigkeiten = CatalogLabels::faehigkeiten($item->rights?->capabilities);
|
||||
$scope[] = [
|
||||
'article' => $this->articleTitle($item->article),
|
||||
'purpose' => CatalogLabels::zweck($item->rights?->purpose),
|
||||
'rights' => $faehigkeiten,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'offer' => $offer,
|
||||
'version' => $version,
|
||||
'name' => $offer->optionName(),
|
||||
'price_cents' => (int) $version->price_cents,
|
||||
'price' => Money::format((int) $version->price_cents),
|
||||
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'term' => self::termLabel($version),
|
||||
'licence' => LicenceScope::label($version->licence_scope, $version->trainer_count),
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
'licence_note' => LicenceScope::explanation($version->licence_scope, $version->trainer_count),
|
||||
'scope' => $scope,
|
||||
];
|
||||
}
|
||||
|
||||
public static function termLabel(OfferVersion $version): string
|
||||
{
|
||||
return self::termRuleLabel($version->term_rule);
|
||||
}
|
||||
|
||||
/** Laufzeitregel aus der Angebotsfassung oder aus den Bedingungen eines Erwerbs (gleiche Schlüssel). */
|
||||
public static function termRuleLabel(?string $rule): string
|
||||
{
|
||||
return match ((string) $rule) {
|
||||
'dauerhaft' => 'Dauerhaft nutzbar',
|
||||
'befristet' => 'Befristet',
|
||||
'solange_angebot_aktiv' => 'Solange das Angebot aktiv ist',
|
||||
'periodisch' => 'Laufend, periodisch',
|
||||
default => (string) $rule,
|
||||
};
|
||||
}
|
||||
|
||||
public function articleTitle(?LicenseArticle $article): string
|
||||
{
|
||||
if ($article === null) {
|
||||
return '–';
|
||||
}
|
||||
|
||||
return $this->articleName($article) ?: (string) $article->code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Name wie in der Redaktion: eigener Name, sonst der Name des Inhalts (Anzeigename, Arbeitstitel oder
|
||||
* Bezeichnung), sonst der eigene Arbeitstitel; leer, wenn nichts davon vorhanden ist.
|
||||
*/
|
||||
public function articleName(LicenseArticle $article): string
|
||||
{
|
||||
$profile = app(EditorialProfileReader::class)->read($article, 'detail');
|
||||
$source = $profile->source;
|
||||
$candidates = [
|
||||
$profile->value('display_title'),
|
||||
$article->working_title,
|
||||
$source?->getAttribute('working_title'),
|
||||
$source?->getAttribute('designation'),
|
||||
];
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
if (filled($candidate)) {
|
||||
return trim((string) $candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
<?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
|
||||
{
|
||||
$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 >>';
|
||||
$objects[5] = '<< /Title ('.preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $title)).') /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);
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Cms\Page;
|
||||
|
||||
/**
|
||||
* Pflichtangaben und Zustimmungen im Bestellablauf (Verkaufsstart Deutschland, PAY-005, PAY-009).
|
||||
*
|
||||
* Die finalen Rechtstexte (AGB, Lizenzbedingungen, Widerrufsbelehrung, Impressum, Datenschutz) liegen als Seiten im
|
||||
* CMS und werden hier nur verlinkt. Der Wortlaut der Zustimmungen unten ist ein ENTWURF zur Prüfung durch die
|
||||
* Rechtsberatung. Er ist nicht rechtlich freigegeben; `VERSION` hält fest, welcher Wortlaut galt, damit die Zustimmung
|
||||
* je Bestellung nachvollziehbar bleibt.
|
||||
*/
|
||||
final class SalesTerms
|
||||
{
|
||||
public const VERSION = '2026-11-24-entwurf';
|
||||
|
||||
/** Schaltfläche zum verbindlichen Abschluss (Button-Lösung, § 312j Abs. 3 BGB). */
|
||||
public const ORDER_BUTTON = 'Zahlungspflichtig bestellen';
|
||||
|
||||
public const ORDER_BUTTON_INVOICE = 'Zahlungspflichtig auf Rechnung bestellen';
|
||||
|
||||
/**
|
||||
* Seiten der Rechtstexte: Schlüssel => Bezeichnung und mögliche Pfade im CMS (erste veröffentlichte Seite gilt).
|
||||
*
|
||||
* @return array<string, array{label: string, paths: list<string>, required: bool}>
|
||||
*/
|
||||
public static function pages(): array
|
||||
{
|
||||
return [
|
||||
'agb' => ['label' => 'Allgemeine Geschäftsbedingungen', 'paths' => ['/agb'], 'required' => true],
|
||||
'lizenz' => ['label' => 'Lizenzbedingungen', 'paths' => ['/lizenzbedingungen', '/lizenz'], 'required' => true],
|
||||
'widerruf' => ['label' => 'Widerrufsbelehrung', 'paths' => ['/widerruf', '/widerrufsbelehrung'], 'required' => true],
|
||||
'impressum' => ['label' => 'Impressum', 'paths' => ['/impressum'], 'required' => true],
|
||||
'datenschutz' => ['label' => 'Datenschutzerklärung', 'paths' => ['/datenschutz'], 'required' => true],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Veröffentlichte Seite des Rechtstextes oder null.
|
||||
*/
|
||||
public static function page(string $key): ?Page
|
||||
{
|
||||
$definition = self::pages()[$key] ?? null;
|
||||
|
||||
if ($definition === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Page::query()
|
||||
->whereIn('path', $definition['paths'])
|
||||
->whereNotNull('published_revision_id')
|
||||
->orderBy('id')
|
||||
->first();
|
||||
}
|
||||
|
||||
public static function url(string $key): ?string
|
||||
{
|
||||
return self::page($key)?->publicUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fehlende oder unveröffentlichte Rechtstexte (Schlüssel => Bezeichnung).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function missingPages(): array
|
||||
{
|
||||
$missing = [];
|
||||
|
||||
foreach (self::pages() as $key => $definition) {
|
||||
if ($definition['required'] && self::page($key) === null) {
|
||||
$missing[$key] = $definition['label'];
|
||||
}
|
||||
}
|
||||
|
||||
return $missing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustimmungen im Checkout: Schlüssel => Wortlaut (ENTWURF).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function consents(): array
|
||||
{
|
||||
return [
|
||||
'agb' => 'Ich habe die Allgemeinen Geschäftsbedingungen und die Lizenzbedingungen gelesen und stimme ihnen zu.',
|
||||
'sofort' => 'Ich verlange ausdrücklich, dass mit der Ausführung des Vertrags vor Ablauf der Widerrufsfrist begonnen wird und die digitalen Inhalte sofort nach Zahlungseingang bereitgestellt werden. Mir ist bekannt, dass ich mein Widerrufsrecht verliere, sobald die Ausführung begonnen hat.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die Zustimmungen und liefert den Nachweis für die Bestellung (Wortlaut, Fassung, Seiten, Zeit).
|
||||
*
|
||||
* @param array<string, mixed> $accepted Schlüssel => angekreuzt
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function proof(array $accepted): array
|
||||
{
|
||||
$texts = [];
|
||||
|
||||
foreach (self::consents() as $key => $wording) {
|
||||
if (empty($accepted[$key])) {
|
||||
throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.');
|
||||
}
|
||||
|
||||
$texts[$key] = $wording;
|
||||
}
|
||||
|
||||
$pages = [];
|
||||
|
||||
foreach (array_keys(self::pages()) as $key) {
|
||||
$page = self::page($key);
|
||||
$pages[$key] = $page === null ? null : ['path' => $page->path, 'revision_id' => $page->published_revision_id];
|
||||
}
|
||||
|
||||
return [
|
||||
'version' => self::VERSION,
|
||||
'consents' => $texts,
|
||||
'pages' => $pages,
|
||||
'recorded_at' => now()->toIso8601String(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
/**
|
||||
* Wann der Shop (Warenkorb, Kasse, Kopflink) aktiv ist.
|
||||
*
|
||||
* Test und Sandbox: nicht in Produktion, Zahlungstreiber „test“ oder „stripe“ (Testschlüssel).
|
||||
* Produktion: nur mit der ausdrücklichen Produktivfreigabe (`SHOP_LIVE_RELEASE`, Entscheidung von Lars), dem
|
||||
* Zahlungstreiber „stripe“ mit Live-Schlüssel und veröffentlichten Rechtstexten. Fehlt eines davon, bleibt der Shop in
|
||||
* Produktion abgeschaltet. Die Freigabe ist standardmäßig aus.
|
||||
*/
|
||||
final class Shop
|
||||
{
|
||||
public static function driver(): string
|
||||
{
|
||||
return (string) config('services.payment.driver');
|
||||
}
|
||||
|
||||
/** Produktivbetrieb ist freigegeben und vollständig vorbereitet (Freigabe, Live-Schlüssel, Rechtstexte). */
|
||||
public static function live(): bool
|
||||
{
|
||||
return app()->isProduction()
|
||||
&& config('shop.live_release') === true
|
||||
&& self::driver() === 'stripe'
|
||||
&& self::liveKey()
|
||||
&& SalesTerms::missingPages() === [];
|
||||
}
|
||||
|
||||
public static function enabled(): bool
|
||||
{
|
||||
if (app()->isProduction()) {
|
||||
return self::live();
|
||||
}
|
||||
|
||||
return in_array(self::driver(), ['test', 'stripe'], true);
|
||||
}
|
||||
|
||||
/** Stripe-Kasse: im Test nur mit Testschlüsseln, in Produktion nur nach der Produktivfreigabe. */
|
||||
public static function stripe(): bool
|
||||
{
|
||||
if (app()->isProduction()) {
|
||||
return self::live();
|
||||
}
|
||||
|
||||
return self::driver() === 'stripe';
|
||||
}
|
||||
|
||||
/** Kauf auf Rechnung für Organisationen (manuelle Rechnung, Zahlungseingang durch den Betreiber). */
|
||||
public static function invoice(): bool
|
||||
{
|
||||
return self::enabled() && (bool) config('shop.invoice', true);
|
||||
}
|
||||
|
||||
private static function liveKey(): bool
|
||||
{
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
|
||||
return str_starts_with($secret, 'sk_live_') || str_starts_with($secret, 'rk_live_');
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
|
||||
/**
|
||||
* Preis oder bindende Bedingungen haben sich nach Anzeige der Bestellübersicht geändert. Es entsteht keine
|
||||
* Bestellung; der Käufer sieht zuerst die aktualisierte Übersicht (FACH-59).
|
||||
*/
|
||||
class StaleOverview extends DomainRuleException {}
|
||||
@@ -1,257 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Stripe;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Stripe-Kasse (Checkout Session). Außerhalb der Produktion nur mit Testschlüsseln; ein Live-Schlüssel wird dort
|
||||
* abgewiesen. In Produktion nur nach der Produktivfreigabe (Shop::live) und nur mit Live-Schlüssel; in jedem anderen
|
||||
* Fall wird abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten berühren diese Anwendung
|
||||
* nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook). Der Betrag je Position ist der
|
||||
* Preis nach Rabatt, damit die Summe bei Stripe genau dem gespeicherten Zahlbetrag der Bestellung entspricht.
|
||||
*/
|
||||
class StripeGateway
|
||||
{
|
||||
/**
|
||||
* Legt für die Bestellung eine Checkout Session an oder liefert die noch offene wieder.
|
||||
*
|
||||
* @return array{id: string, url: string}
|
||||
*/
|
||||
public function checkoutFor(Order $order): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$order->loadMissing('lines', 'user');
|
||||
$taxRate = $this->taxRate();
|
||||
|
||||
if ($order->status !== 'offen') {
|
||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
||||
}
|
||||
|
||||
if ($order->payment_method === 'rechnung') {
|
||||
throw new DomainRuleException('Diese Bestellung wird auf Rechnung bezahlt, nicht bei Stripe.');
|
||||
}
|
||||
|
||||
$open = $this->reusableSession($order);
|
||||
|
||||
if ($open !== null) {
|
||||
return $open;
|
||||
}
|
||||
|
||||
$attempt = $order->payments()->where('provider', 'stripe')->count() + 1;
|
||||
$params = [
|
||||
'mode' => 'payment',
|
||||
'client_reference_id' => (string) $order->id,
|
||||
'customer_email' => $order->user->email,
|
||||
'locale' => 'de',
|
||||
'success_url' => route('member.order', $order).'?zahlung=zurueck',
|
||||
'cancel_url' => route('member.order', $order).'?zahlung=abbruch',
|
||||
'metadata' => ['order_id' => (string) $order->id],
|
||||
'payment_intent_data' => ['metadata' => ['order_id' => (string) $order->id]],
|
||||
];
|
||||
|
||||
foreach ($order->lines->values() as $index => $line) {
|
||||
$productData = ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'];
|
||||
|
||||
if ((int) $line->discount_cents > 0) {
|
||||
$productData['description'] = 'Listenpreis '.Money::format((int) $line->price_cents).', Rabatt '.Money::format((int) $line->discount_cents);
|
||||
}
|
||||
|
||||
$params['line_items'][$index] = [
|
||||
'quantity' => 1,
|
||||
'price_data' => [
|
||||
'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')),
|
||||
'unit_amount' => $line->payable(),
|
||||
'product_data' => $productData,
|
||||
],
|
||||
];
|
||||
|
||||
if ($taxRate !== null) {
|
||||
$params['line_items'][$index]['tax_rates'] = [$taxRate];
|
||||
}
|
||||
}
|
||||
|
||||
$response = $this->request()
|
||||
->withHeaders(['Idempotency-Key' => $this->idempotencyKey($order, $attempt, $params)])
|
||||
->post('/v1/checkout/sessions', $params);
|
||||
|
||||
$this->assertOk($response, 'angelegt');
|
||||
$id = (string) $response->json('id');
|
||||
$url = (string) $response->json('url');
|
||||
|
||||
if ($id === '' || $url === '') {
|
||||
throw new DomainRuleException('Stripe hat keine Kasse geliefert. Bitte versuche es später noch einmal.');
|
||||
}
|
||||
|
||||
$order->payments()->create(['provider' => 'stripe', 'status' => 'offen', 'provider_reference' => $id]);
|
||||
|
||||
return ['id' => $id, 'url' => $url];
|
||||
}
|
||||
|
||||
public function assertAllowed(): void
|
||||
{
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
|
||||
if ($secret === '') {
|
||||
throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.');
|
||||
}
|
||||
|
||||
if (app()->isProduction()) {
|
||||
if (! Shop::live()) {
|
||||
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) {
|
||||
throw new DomainRuleException('Außerhalb der Produktion erlaubt Stripe nur den Testmodus (Schlüssel sk_test_).');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vollerstattung der bezahlten Bestellung bei Stripe. Der Betrag ist der gespeicherte Zahlbetrag. Der
|
||||
* Idempotenzschlüssel verhindert eine doppelte Rückzahlung bei Wiederholung. Schlägt sie fehl, wird nichts
|
||||
* entzogen (Aufrufer: Checkout::refund). Geliefert werden Rückzahlungs-ID, Status (Stripe meldet unter Umständen
|
||||
* „pending“; er wird so festgehalten) und Zeitpunkt für das Zahlungsjournal.
|
||||
*
|
||||
* @return array{id: string, status: string, created: ?CarbonImmutable}
|
||||
*/
|
||||
public function refund(Order $order, Payment $payment, string $reason): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$intent = (string) $payment->provider_payment_ref;
|
||||
|
||||
if ($intent === '') {
|
||||
$session = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
|
||||
$this->assertOk($session, 'abgefragt');
|
||||
$intent = (string) $session->json('payment_intent');
|
||||
}
|
||||
|
||||
if ($intent === '') {
|
||||
throw new DomainRuleException('Zu dieser Zahlung gibt es bei Stripe keinen Zahlungsvorgang. Erstatte sie im Stripe-Dashboard und prüfe den Fall.');
|
||||
}
|
||||
|
||||
$response = $this->request()
|
||||
->withHeaders(['Idempotency-Key' => 'luf-refund-'.$order->id.'-'.$payment->id])
|
||||
->post('/v1/refunds', [
|
||||
'payment_intent' => $intent,
|
||||
'amount' => $order->payable(),
|
||||
'reason' => 'requested_by_customer',
|
||||
'metadata' => ['order_id' => (string) $order->id, 'grund' => mb_substr($reason, 0, 200)],
|
||||
]);
|
||||
|
||||
$this->assertOk($response, 'erstattet');
|
||||
$id = (string) $response->json('id');
|
||||
$status = (string) $response->json('status');
|
||||
|
||||
if ($id === '') {
|
||||
throw new DomainRuleException('Stripe hat keine Rückzahlung bestätigt. Prüfe den Fall im Stripe-Dashboard, bevor du es erneut versuchst.');
|
||||
}
|
||||
|
||||
if (in_array($status, ['failed', 'canceled'], true)) {
|
||||
throw new DomainRuleException('Stripe hat die Rückzahlung nicht ausgeführt (Status '.$status.'). Es wurde nichts verändert.');
|
||||
}
|
||||
|
||||
$payment->provider_payment_ref = $intent;
|
||||
$payment->save();
|
||||
|
||||
return [
|
||||
'id' => $id,
|
||||
'status' => $status !== '' ? $status : 'unbekannt',
|
||||
'created' => is_numeric($response->json('created')) ? CarbonImmutable::createFromTimestampUTC((int) $response->json('created')) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Stripe bindet einen Schlüssel an die Parameter der ersten Anfrage und lehnt dieselbe Kennung mit anderen
|
||||
* Parametern ab. Der Schlüssel enthält deshalb einen Fingerabdruck der Parameter und die Minute: Ein
|
||||
* doppelter Klick bleibt wirkungslos, eine geänderte Anfrage oder ein Neuversuch nach einer Korrektur nicht.
|
||||
*
|
||||
* @param array<string, mixed> $params
|
||||
*/
|
||||
private function idempotencyKey(Order $order, int $attempt, array $params): string
|
||||
{
|
||||
$fingerprint = substr(sha1(json_encode([$params, now()->format('YmdHi')], JSON_THROW_ON_ERROR)), 0, 12);
|
||||
|
||||
return 'luf-order-'.$order->id.'-'.$attempt.'-'.$fingerprint;
|
||||
}
|
||||
|
||||
/** Konfigurierter Steuersatz oder null; eine ungültige ID wird abgewiesen, statt geraten zu werden. */
|
||||
private function taxRate(): ?string
|
||||
{
|
||||
$id = trim((string) config('services.stripe.tax_rate'));
|
||||
|
||||
if ($id === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! preg_match('/^txr_[A-Za-z0-9]+$/', $id)) {
|
||||
throw new DomainRuleException('Die Steuersatz-ID für Stripe ist ungültig (erwartet txr_...).');
|
||||
}
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{id: string, url: string}|null
|
||||
*/
|
||||
private function reusableSession(Order $order): ?array
|
||||
{
|
||||
$payment = $order->payments()->where('provider', 'stripe')->where('status', 'offen')->latest('id')->first();
|
||||
|
||||
if ($payment === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
|
||||
} catch (ConnectionException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($response->successful() && $response->json('status') === 'open' && filled($response->json('url'))) {
|
||||
return ['id' => (string) $payment->provider_reference, 'url' => (string) $response->json('url')];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function request(): PendingRequest
|
||||
{
|
||||
return Http::baseUrl(rtrim((string) config('services.stripe.api_base'), '/'))
|
||||
->withToken((string) config('services.stripe.secret'))
|
||||
->asForm()
|
||||
->acceptJson()
|
||||
->timeout(15);
|
||||
}
|
||||
|
||||
private function assertOk(Response $response, string $what): void
|
||||
{
|
||||
if ($response->successful()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Statuscode, Fehlertyp, Code, betroffener Parameter und Begründung von Stripe, damit die Ursache lesbar ist.
|
||||
// Nie Schlüssel oder Kundendaten; die Begründung wird gekürzt.
|
||||
Log::warning('Stripe-Anfrage fehlgeschlagen', [
|
||||
'status' => $response->status(),
|
||||
'type' => $response->json('error.type'),
|
||||
'code' => $response->json('error.code'),
|
||||
'param' => $response->json('error.param'),
|
||||
'message' => mb_substr((string) $response->json('error.message'), 0, 300),
|
||||
]);
|
||||
|
||||
throw new DomainRuleException('Die Zahlung konnte bei Stripe nicht '.$what.' werden. Bitte versuche es später noch einmal.');
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Stripe;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
|
||||
/**
|
||||
* Prüft die Signatur einer Stripe-Meldung (Header „Stripe-Signature“: t=Zeit, v1=HMAC-SHA256 über „t.Nutzlast“).
|
||||
* Eine Meldung ohne gültige Signatur oder außerhalb der Zeittoleranz wird abgewiesen.
|
||||
*/
|
||||
class StripeSignature
|
||||
{
|
||||
public const TOLERANCE_SECONDS = 300;
|
||||
|
||||
public function verify(string $payload, ?string $header, ?int $now = null): void
|
||||
{
|
||||
$secret = (string) config('services.stripe.webhook_secret');
|
||||
|
||||
if ($secret === '') {
|
||||
throw new DomainRuleException('Das Webhook-Geheimnis ist nicht eingerichtet.');
|
||||
}
|
||||
|
||||
if ($header === null || trim($header) === '') {
|
||||
throw new DomainRuleException('Die Signatur fehlt.');
|
||||
}
|
||||
|
||||
$timestamp = null;
|
||||
$signatures = [];
|
||||
|
||||
foreach (explode(',', $header) as $part) {
|
||||
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
|
||||
|
||||
if ($key === 't') {
|
||||
$timestamp = ctype_digit($value) ? (int) $value : null;
|
||||
} elseif ($key === 'v1' && $value !== '') {
|
||||
$signatures[] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if ($timestamp === null || $signatures === []) {
|
||||
throw new DomainRuleException('Die Signatur ist unvollständig.');
|
||||
}
|
||||
|
||||
$expected = hash_hmac('sha256', $timestamp.'.'.$payload, $secret);
|
||||
$valid = false;
|
||||
|
||||
foreach ($signatures as $signature) {
|
||||
$valid = hash_equals($expected, $signature) || $valid;
|
||||
}
|
||||
|
||||
if (! $valid) {
|
||||
throw new DomainRuleException('Die Signatur stimmt nicht.');
|
||||
}
|
||||
|
||||
if (abs(($now ?? now()->getTimestamp()) - $timestamp) > self::TOLERANCE_SECONDS) {
|
||||
throw new DomainRuleException('Die Meldung ist zu alt.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Design;
|
||||
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
/**
|
||||
* Basiswerte der Größenskala des gemeinsamen Designsystems (ADR-44). Es sind bewusst nur zehn Werte; alles Weitere
|
||||
* (Überschrift 3, Einleitung, kleine Schrift, Abschnitts- und Widget-Abstände, Kopfzeile kompakt, Mindesthöhen der
|
||||
* Varianten …) leitet resources/css/tokens.css daraus ab. Die Ableitungsregeln stehen nur dort.
|
||||
*
|
||||
* Die Werte sind Pixel als ganze Zahl. Im Stylesheet werden sie in rem umgerechnet, damit die Textgröße des Browsers
|
||||
* wirkt. Die Standardwerte stehen ebenfalls in tokens.css (Block „Basiswerte“); ein Test hält beide gleich.
|
||||
* Trefferflächen (44 px) und die Untergrenze der Schrift auf Smartphones (16 px) sind nicht einstellbar.
|
||||
*/
|
||||
final class DesignScale
|
||||
{
|
||||
/**
|
||||
* @var array<string, array{label: string, default: int, min: int, max: int, unit: string, group: string, hint: string, effect: string}>
|
||||
*/
|
||||
public const PARAMETERS = [
|
||||
'body' => ['label' => 'Fließtext', 'default' => 17, 'min' => 16, 'max' => 20, 'unit' => 'px', 'group' => 'Schrift',
|
||||
'hint' => 'Schriftgröße auf Desktop; auf kleinen Bildschirmen etwa 1 px weniger, nie unter 16 px.',
|
||||
'effect' => 'Auch Einleitung, Überschrift 3, kleine Schrift und Schaltflächen folgen daraus.'],
|
||||
'h1' => ['label' => 'Überschrift 1', 'default' => 40, 'min' => 30, 'max' => 56, 'unit' => 'px', 'group' => 'Schrift',
|
||||
'hint' => 'Seitentitel auf Desktop; schrumpft auf Smartphones auf etwa 70 %.',
|
||||
'effect' => 'Muss mindestens 4 px größer sein als Überschrift 2.'],
|
||||
'h2' => ['label' => 'Überschrift 2', 'default' => 28, 'min' => 22, 'max' => 40, 'unit' => 'px', 'group' => 'Schrift',
|
||||
'hint' => 'Abschnittstitel auf Desktop; auch Titel in Bild und Text, Handlungsaufruf und breiten Karten.',
|
||||
'effect' => 'Muss mindestens 6 px größer sein als der Fließtext. Überschrift 3 bleibt darunter.'],
|
||||
'display' => ['label' => 'Display-Überschrift (Höchstwert)', 'default' => 52, 'min' => 36, 'max' => 80, 'unit' => 'px', 'group' => 'Schrift',
|
||||
'hint' => 'Größter Titel (Einstieg). Wächst mit der Breite des Platzes bis zu diesem Wert.',
|
||||
'effect' => 'Mindestens so groß wie Überschrift 1.'],
|
||||
'space' => ['label' => 'Basisabstand', 'default' => 8, 'min' => 6, 'max' => 12, 'unit' => 'px', 'group' => 'Abstände',
|
||||
'hint' => 'Grundmaß des Abstandsrasters (halber, einfacher, anderthalbfacher bis zwölffacher Wert).',
|
||||
'effect' => 'Alle Abstandsstufen der Komponenten und die Abstände zwischen Plätzen im Raster.'],
|
||||
'section' => ['label' => 'Abschnittsabstand (Desktop)', 'default' => 48, 'min' => 24, 'max' => 96, 'unit' => 'px', 'group' => 'Abstände',
|
||||
'hint' => 'Stufe „Normal“ auf Desktop. „Kompakt“ ist zwei Drittel davon, „Großzügig“ das Anderthalbfache.',
|
||||
'effect' => 'Auf Smartphones werden alle Stufen kleiner.'],
|
||||
'card_pad' => ['label' => 'Karten-Innenabstand', 'default' => 20, 'min' => 12, 'max' => 32, 'unit' => 'px', 'group' => 'Abstände',
|
||||
'hint' => 'Innenabstand von Karten auf Desktop.',
|
||||
'effect' => 'Große Flächen (Einstieg, Bild und Text, Handlungsaufruf) verwenden das Ein- bis Zweifache.'],
|
||||
'header' => ['label' => 'Höhe der Kopfzeile', 'default' => 80, 'min' => 56, 'max' => 112, 'unit' => 'px', 'group' => 'Rahmen',
|
||||
'hint' => 'Kopfzeile im Ausgangszustand auf Desktop. Beim Scrollen und auf Smartphones gilt 80 % davon.',
|
||||
'effect' => 'Die Anzeigegröße der Wortmarke folgt daraus; die Wortmarke selbst bleibt unverändert.'],
|
||||
'width' => ['label' => 'Maximale Inhaltsbreite', 'default' => 1312, 'min' => 960, 'max' => 1600, 'unit' => 'px', 'group' => 'Rahmen',
|
||||
'hint' => 'Breite des Standardrasters; Kopfzeile, Inhalt und Fußbereich fluchten hier. „Breit“ ist etwa 17 % mehr.',
|
||||
'effect' => 'Der Lesebereich (44 rem) ist davon unabhängig.'],
|
||||
'media' => ['label' => 'Bildhöhe in Bild und Text (Desktop)', 'default' => 320, 'min' => 200, 'max' => 480, 'unit' => 'px', 'group' => 'Medien',
|
||||
'hint' => 'Höhe des Bildes neben dem Text in der Variante „Standard“. Kompakt: 75 %, Großzügig: 130 %.',
|
||||
'effect' => 'Bestimmt zugleich die Mindesthöhe des Einstiegs (das 1,2-Fache; kompakt und großzügig wie bei Bild und Text).'],
|
||||
];
|
||||
|
||||
/** Gruppen in fester Reihenfolge. */
|
||||
public const GROUPS = ['Schrift', 'Abstände', 'Rahmen', 'Medien'];
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public static function defaults(): array
|
||||
{
|
||||
return array_map(static fn (array $p): int => $p['default'], self::PARAMETERS);
|
||||
}
|
||||
|
||||
/** Name der CSS-Variable, zum Beispiel card_pad → --ds-card-pad. */
|
||||
public static function variable(string $key): string
|
||||
{
|
||||
return '--ds-'.str_replace('_', '-', $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft vollständige Eingaben (Zeichenketten aus dem Formular oder Zahlen). Gibt Fehlermeldungen je Schlüssel zurück;
|
||||
* leer, wenn alles zulässig ist.
|
||||
*
|
||||
* @param array<string, mixed> $input
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function errors(array $input): array
|
||||
{
|
||||
$rules = [];
|
||||
$messages = [];
|
||||
$names = [];
|
||||
|
||||
foreach (self::PARAMETERS as $key => $p) {
|
||||
$rules[$key] = ['required', 'integer', 'min:'.$p['min'], 'max:'.$p['max']];
|
||||
$names[$key] = $p['label'];
|
||||
$messages["$key.required"] = $p['label'].': Bitte einen Wert eintragen.';
|
||||
$messages["$key.integer"] = $p['label'].': Bitte eine ganze Zahl in Pixeln eintragen.';
|
||||
$messages["$key.min"] = $p['label'].': Der Wert muss mindestens '.$p['min'].' px betragen.';
|
||||
$messages["$key.max"] = $p['label'].': Der Wert darf höchstens '.$p['max'].' px betragen.';
|
||||
}
|
||||
|
||||
$validator = Validator::make(array_intersect_key($input, self::PARAMETERS), $rules, $messages, $names);
|
||||
$errors = [];
|
||||
|
||||
foreach ($validator->errors()->messages() as $key => $list) {
|
||||
$errors[$key] = $list[0];
|
||||
}
|
||||
|
||||
if ($errors !== []) {
|
||||
return $errors;
|
||||
}
|
||||
|
||||
$v = array_map('intval', array_intersect_key($input, self::PARAMETERS));
|
||||
|
||||
if ($v['h2'] < $v['body'] + 6) {
|
||||
$errors['h2'] = 'Überschrift 2 muss mindestens 6 px größer sein als der Fließtext ('.($v['body'] + 6).' px).';
|
||||
}
|
||||
|
||||
if ($v['h1'] < $v['h2'] + 4) {
|
||||
$errors['h1'] = 'Überschrift 1 muss mindestens 4 px größer sein als Überschrift 2 ('.($v['h2'] + 4).' px).';
|
||||
}
|
||||
|
||||
if ($v['display'] < $v['h1']) {
|
||||
$errors['display'] = 'Die Display-Überschrift darf nicht kleiner sein als Überschrift 1 ('.$v['h1'].' px).';
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gespeicherte Werte lesen: nur bekannte Schlüssel, ganze Zahlen im zulässigen Bereich und stimmige Reihenfolge.
|
||||
* Alles andere (fehlende Schlüssel, Fremdes, beschädigte Daten) ergibt die Standardwerte, nie einen Fehler.
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public static function read(mixed $stored): array
|
||||
{
|
||||
if (! is_array($stored)) {
|
||||
return self::defaults();
|
||||
}
|
||||
|
||||
$merged = self::defaults();
|
||||
|
||||
foreach (array_keys(self::PARAMETERS) as $key) {
|
||||
if (array_key_exists($key, $stored) && (is_int($stored[$key]) || (is_string($stored[$key]) && ctype_digit($stored[$key])))) {
|
||||
$merged[$key] = (int) $stored[$key];
|
||||
}
|
||||
}
|
||||
|
||||
return self::errors($merged) === [] ? $merged : self::defaults();
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline-Stylesheet mit den abweichenden Basiswerten. Ausgegeben werden ausschließlich geprüfte ganze Zahlen zu
|
||||
* bekannten Schlüsseln. Ohne Abweichung leer: dann gelten die Standardwerte aus tokens.css.
|
||||
*
|
||||
* @param array<string, int> $values
|
||||
*/
|
||||
public static function css(array $values): string
|
||||
{
|
||||
$declarations = '';
|
||||
|
||||
foreach (self::PARAMETERS as $key => $p) {
|
||||
$value = $values[$key] ?? $p['default'];
|
||||
|
||||
if ($value !== $p['default'] && $value >= $p['min'] && $value <= $p['max']) {
|
||||
$declarations .= sprintf('%s:%d;', self::variable($key), $value);
|
||||
}
|
||||
}
|
||||
|
||||
return $declarations === '' ? '' : ':root{'.$declarations.'}';
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Design;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\HtmlString;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Lesen und Schreiben der Größenskala (Schlüssel „design.scale“ in site_settings).
|
||||
*
|
||||
* Die öffentliche Ausgabe hängt nie am Erfolg dieser Klasse: Fehlt die Tabelle (Code vor Migration), ist die Datenbank
|
||||
* nicht erreichbar oder sind die Daten beschädigt, gelten die Standardwerte aus tokens.css, ohne Fehlerseite.
|
||||
* Änderungen wirken sofort (Zwischenspeicher wird beim Speichern geleert), ohne Deployment.
|
||||
*/
|
||||
final class DesignSettings
|
||||
{
|
||||
public const KEY = 'design.scale';
|
||||
|
||||
private const CACHE_KEY = 'design.scale.v1';
|
||||
|
||||
/** @var array<string, int>|null */
|
||||
private static ?array $memo = null;
|
||||
|
||||
/**
|
||||
* Wirksame Werte (gespeichert oder Standard).
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
if (self::$memo !== null) {
|
||||
return self::$memo;
|
||||
}
|
||||
|
||||
try {
|
||||
$stored = Cache::rememberForever(self::CACHE_KEY, static function (): array {
|
||||
$row = SiteSetting::query()->find(self::KEY);
|
||||
|
||||
return $row === null ? [] : (array) $row->value;
|
||||
});
|
||||
|
||||
return self::$memo = $stored === [] ? DesignScale::defaults() : DesignScale::read($stored);
|
||||
} catch (Throwable) {
|
||||
return self::$memo = DesignScale::defaults();
|
||||
}
|
||||
}
|
||||
|
||||
/** Ob abweichende Werte wirksam sind. */
|
||||
public static function isCustomised(): bool
|
||||
{
|
||||
return self::values() !== DesignScale::defaults();
|
||||
}
|
||||
|
||||
/**
|
||||
* Speichert vollständige, geprüfte Werte.
|
||||
*
|
||||
* @param array<string, mixed> $input
|
||||
* @return array<string, string> Fehlermeldungen je Schlüssel; leer bei Erfolg
|
||||
*/
|
||||
public static function save(array $input, ?User $by = null): array
|
||||
{
|
||||
$errors = DesignScale::errors($input);
|
||||
|
||||
if ($errors !== []) {
|
||||
return $errors;
|
||||
}
|
||||
|
||||
$ordered = [];
|
||||
|
||||
foreach (array_keys(DesignScale::PARAMETERS) as $key) {
|
||||
$ordered[$key] = (int) $input[$key];
|
||||
}
|
||||
|
||||
SiteSetting::query()->updateOrCreate(['key' => self::KEY], ['value' => $ordered, 'updated_by' => $by?->getKey()]);
|
||||
self::flush();
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Standardwerte wiederherstellen: die Zeile entfällt, es gelten wieder die Werte aus tokens.css. */
|
||||
public static function reset(): void
|
||||
{
|
||||
SiteSetting::query()->whereKey(self::KEY)->delete();
|
||||
self::flush();
|
||||
}
|
||||
|
||||
/** Zeitpunkt der letzten Speicherung, falls vorhanden. */
|
||||
public static function updatedAt(): ?Carbon
|
||||
{
|
||||
try {
|
||||
return SiteSetting::query()->find(self::KEY)?->updated_at;
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static function flush(): void
|
||||
{
|
||||
self::$memo = null;
|
||||
|
||||
try {
|
||||
Cache::forget(self::CACHE_KEY);
|
||||
} catch (Throwable) {
|
||||
// Der Zwischenspeicher ist nur Beschleunigung.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stylesheet-Block für Layouts und Vorschauen; nach dem Stylesheet der Website einzufügen, damit er gewinnt.
|
||||
* Leer, solange keine abweichenden Werte gespeichert sind.
|
||||
*/
|
||||
public static function styleTag(): HtmlString
|
||||
{
|
||||
$css = DesignScale::css(self::values());
|
||||
|
||||
return new HtmlString($css === '' ? '' : '<style id="lf-design-scale">'.$css.'</style>');
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Design;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Eine Einstellung der Website (Schlüssel-Wert, Wert als JSON). Lesen und Schreiben der Größenskala
|
||||
* läuft über DesignSettings.
|
||||
*
|
||||
* @property string $key
|
||||
* @property array<string, mixed> $value
|
||||
* @property int|null $updated_by
|
||||
*/
|
||||
class SiteSetting extends Model
|
||||
{
|
||||
protected $table = 'site_settings';
|
||||
|
||||
protected $primaryKey = 'key';
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['value' => 'array'];
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@ class Acquisition extends Model
|
||||
'reference_type',
|
||||
'reference_id',
|
||||
'conditions',
|
||||
'acting_user_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
|
||||
@@ -47,7 +47,7 @@ public function __invoke(
|
||||
$candidates = Grant::query()
|
||||
->where('license_article_id', $article->id)
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->usableBy($user)
|
||||
->whereHas('acquisition', fn ($query) => $query->where('party_id', $user->party_id))
|
||||
->get()
|
||||
->filter(function (Grant $grant) use ($now): bool {
|
||||
if ($grant->valid_from !== null && $grant->valid_from->greaterThan($now)) {
|
||||
|
||||
@@ -5,9 +5,6 @@
|
||||
use App\Domain\Catalog\ArticleRelease;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\RightsProfileVersion;
|
||||
use App\Domain\Identity\Membership;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
@@ -35,32 +32,6 @@ protected function casts(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Berechtigungen, die ein Konto nutzen darf (zentrale Regel für Entscheidung, Bibliothek und Vorschaubilder):
|
||||
* - persönliche Erwerbe: Inhaber ist die Person des Kontos;
|
||||
* - Erwerbe einer Organisation: nur das auslösende Konto und nur, solange seine Mitgliedschaft mit
|
||||
* Bestellberechtigung besteht (Etappe 1, Domänenmodell 04; Sitzpools folgen mit A4).
|
||||
*
|
||||
* @param Builder<Grant> $query
|
||||
* @return Builder<Grant>
|
||||
*/
|
||||
public function scopeUsableBy(Builder $query, User $user): Builder
|
||||
{
|
||||
return $query->whereHas('acquisition', function (Builder $acquisition) use ($user): void {
|
||||
$acquisition->where(function (Builder $either) use ($user): void {
|
||||
$either->where('party_id', $user->party_id)
|
||||
->orWhere(function (Builder $organisation) use ($user): void {
|
||||
$organisation->where('acting_user_id', $user->id)
|
||||
->whereIn('party_id', Membership::query()
|
||||
->active()
|
||||
->where('user_id', $user->id)
|
||||
->where('may_order', true)
|
||||
->select('party_id'));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public function acquisition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Acquisition::class);
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferStatus;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\OrderLine;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
@@ -71,60 +69,6 @@ public function grantManually(User $user, Offer $offer, User $actor, string $rea
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Freischaltung einer bezahlten Bestellposition aus deren festgehaltenem Umfang (Umfangskopie und Bedingungen der
|
||||
* Position, nicht aus der Angebotsfassung). Inhaber ist der Lizenzinhaber der Position, das auslösende Konto wird
|
||||
* am Erwerb festgehalten. Wiederholsicher: je Bestellposition genau ein Erwerb.
|
||||
*/
|
||||
public function issueFromOrderLine(OrderLine $line, Party $holder, User $actor): Acquisition
|
||||
{
|
||||
return DB::transaction(function () use ($line, $holder, $actor): Acquisition {
|
||||
$existing = Acquisition::query()->where([
|
||||
'party_id' => $holder->id,
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
])->first();
|
||||
|
||||
if ($existing !== null) {
|
||||
return $existing->load('grants');
|
||||
}
|
||||
|
||||
$acquisition = Acquisition::query()->create([
|
||||
'party_id' => $holder->id,
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
'acting_user_id' => $actor->id,
|
||||
'conditions' => [
|
||||
'term_rule' => $line->term_rule,
|
||||
'update_promise' => $line->update_promise,
|
||||
'holder_kind' => $line->holder_kind,
|
||||
'offer_version_id' => $line->offer_version_id,
|
||||
'licence_scope' => $line->licence_scope,
|
||||
'trainer_count' => $line->trainer_count,
|
||||
'price_cents' => (int) $line->price_cents,
|
||||
'discount_cents' => (int) $line->discount_cents,
|
||||
],
|
||||
]);
|
||||
|
||||
$line->loadMissing('scopeItems.article');
|
||||
|
||||
foreach ($line->scopeItems as $item) {
|
||||
$acquisition->grants()->create([
|
||||
'license_article_id' => $item->license_article_id,
|
||||
'rights_profile_version_id' => $item->rights_profile_version_id,
|
||||
'rights_snapshot' => $item->rights_snapshot,
|
||||
'release_at_grant_id' => $item->article?->current_release_id,
|
||||
'status' => GrantStatus::Aktiv,
|
||||
'valid_from' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
return $acquisition->load('grants');
|
||||
});
|
||||
}
|
||||
|
||||
public function issue(
|
||||
User $user,
|
||||
OfferVersion $version,
|
||||
@@ -154,8 +98,6 @@ public function issue(
|
||||
'update_promise' => $version->update_promise,
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'offer_version_id' => $version->id,
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
],
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Identity;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Rechnungsadresse eines Lizenzinhabers (Person oder Organisation). Eine je Inhaber. Sie wird nur gepflegt;
|
||||
* eine Bestellung kopiert sie erst, wenn die Rechnungsstellung sie braucht.
|
||||
*/
|
||||
class BillingAddress extends Model
|
||||
{
|
||||
/** Auswählbare Länder (ISO 3166-1 Alpha-2). */
|
||||
public const COUNTRIES = [
|
||||
'DE' => 'Deutschland',
|
||||
'AT' => 'Österreich',
|
||||
'CH' => 'Schweiz',
|
||||
'LI' => 'Liechtenstein',
|
||||
'LU' => 'Luxemburg',
|
||||
'BE' => 'Belgien',
|
||||
'NL' => 'Niederlande',
|
||||
'FR' => 'Frankreich',
|
||||
'IT' => 'Italien',
|
||||
'DK' => 'Dänemark',
|
||||
'PL' => 'Polen',
|
||||
'CZ' => 'Tschechien',
|
||||
];
|
||||
|
||||
protected $fillable = [
|
||||
'party_id',
|
||||
'recipient',
|
||||
'line2',
|
||||
'street',
|
||||
'postal_code',
|
||||
'city',
|
||||
'country',
|
||||
];
|
||||
|
||||
public function party(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Party::class);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Identity;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Mitgliedschaft eines Kontos in einer Organisation (Domänenmodell 04, MEMBERSHIP). Etappe 1 nutzt sie für die
|
||||
* Bestellberechtigung: Ein Konto bestellt nur für eine Organisation, bei der eine aktive Mitgliedschaft mit
|
||||
* `may_order` besteht. Sitzpools und Selbstverwaltung folgen mit A4.
|
||||
*/
|
||||
class Membership extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'party_id',
|
||||
'role',
|
||||
'may_order',
|
||||
'valid_from',
|
||||
'valid_until',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'may_order' => 'boolean',
|
||||
'valid_from' => 'date',
|
||||
'valid_until' => 'date',
|
||||
];
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function organisation(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Party::class, 'party_id');
|
||||
}
|
||||
|
||||
/** Mitgliedschaften, die heute gelten. */
|
||||
public function scopeActive(Builder $query): Builder
|
||||
{
|
||||
return $query
|
||||
->where(fn (Builder $inner) => $inner->whereNull('valid_from')->orWhereDate('valid_from', '<=', now()))
|
||||
->where(fn (Builder $inner) => $inner->whereNull('valid_until')->orWhereDate('valid_until', '>=', now()));
|
||||
}
|
||||
}
|
||||
@@ -25,11 +25,6 @@ public function user(): HasOne
|
||||
return $this->hasOne(User::class);
|
||||
}
|
||||
|
||||
public function billingAddress(): HasOne
|
||||
{
|
||||
return $this->hasOne(BillingAddress::class);
|
||||
}
|
||||
|
||||
public function profile(): HasOne
|
||||
{
|
||||
return $this->hasOne(Profile::class);
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Übernimmt das Vorschaubild eines Programms oder Moduls als gewöhnliches Bild-Medium im Medienmanager
|
||||
* (Programm- und Modulkarte), nach demselben Prinzip wie FilmStill.
|
||||
*
|
||||
* - Ausdrückliche Handlung der Redaktion. Das Vorschaubild ist ein geschütztes Bibliotheksbild; erst die Übernahme
|
||||
* legt ein Medium an, das für die Website freigegeben werden kann (WebsiteIntake, Warteschlange).
|
||||
* - Die Datei wird einmal kopiert. Dieselbe Vorschaudatei ergibt dasselbe Medium (composition_still_sources).
|
||||
* - Es entsteht keine Fassung, keine Berechtigung, kein Lizenzartikel.
|
||||
*/
|
||||
class CompositionStill
|
||||
{
|
||||
/** Wahr, wenn der letzte Aufruf ein schon vorhandenes Bild geliefert hat. */
|
||||
public bool $reused = false;
|
||||
|
||||
public function __construct(private readonly WebsiteIntake $intake) {}
|
||||
|
||||
public function refusal(Composition $composition): ?string
|
||||
{
|
||||
if ($composition->archived_at !== null) {
|
||||
return 'Das Programm oder Modul ist archiviert.';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function hasThumbnail(Composition $composition): bool
|
||||
{
|
||||
$path = $composition->thumbnail_path;
|
||||
|
||||
return is_string($path) && str_starts_with($path, 'vorschau/') && ! str_contains($path, '..')
|
||||
&& Storage::disk('media_derived')->exists($path);
|
||||
}
|
||||
|
||||
public function fromThumbnail(Composition $composition, ?User $actor = null): ContentElement
|
||||
{
|
||||
$this->reused = false;
|
||||
$refusal = $this->refusal($composition);
|
||||
|
||||
if ($refusal !== null) {
|
||||
throw new DomainRuleException($refusal);
|
||||
}
|
||||
|
||||
if (! $this->hasThumbnail($composition)) {
|
||||
throw new DomainRuleException('Dieses Programm oder Modul hat noch kein Vorschaubild. Setzen Sie es im Redaktionsmanager.');
|
||||
}
|
||||
|
||||
$bytes = Storage::disk('media_derived')->get((string) $composition->thumbnail_path);
|
||||
|
||||
if (! is_string($bytes) || $bytes === '') {
|
||||
throw new DomainRuleException('Das Vorschaubild ließ sich nicht lesen.');
|
||||
}
|
||||
|
||||
$key = 'file:'.hash('sha256', $bytes);
|
||||
$existing = $this->existing($composition, $key);
|
||||
|
||||
if ($existing instanceof ContentElement) {
|
||||
$this->reused = true;
|
||||
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$title = (string) ($composition->display_title ?: $composition->designation);
|
||||
$path = 'cms/titelbild-'.$composition->id.'-'.Str::lower(Str::random(8)).'.jpg';
|
||||
Storage::disk('cms_incoming')->put($path, $bytes);
|
||||
|
||||
$still = $this->intake->acceptImage($path, 'Titelbild: '.$title, null, 'Titelbild zu „'.$title.'“', $actor);
|
||||
|
||||
try {
|
||||
CompositionStillSource::query()->updateOrCreate(
|
||||
['composition_id' => $composition->id, 'source_key' => $key],
|
||||
['still_element_id' => $still->id, 'actor_id' => $actor?->id],
|
||||
);
|
||||
} catch (QueryException) {
|
||||
return $this->existing($composition, $key) ?? $still;
|
||||
}
|
||||
|
||||
return $still;
|
||||
}
|
||||
|
||||
private function existing(Composition $composition, string $key): ?ContentElement
|
||||
{
|
||||
$source = CompositionStillSource::query()->with('still')->where('composition_id', $composition->id)->where('source_key', $key)->first();
|
||||
$still = $source?->still;
|
||||
|
||||
// Ein archiviertes oder bei der Verarbeitung gescheitertes Bild wird nicht wiederverwendet.
|
||||
return $still instanceof ContentElement && $still->archived_at === null && ! filled($still->thumbnail_error) ? $still : null;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Herkunft eines Bild-Mediums aus dem Vorschaubild eines Programms oder Moduls (source_key file:{SHA-256}).
|
||||
*/
|
||||
class CompositionStillSource extends Model
|
||||
{
|
||||
protected $fillable = ['composition_id', 'still_element_id', 'source_key', 'actor_id'];
|
||||
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
public function still(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContentElement::class, 'still_element_id');
|
||||
}
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Legt ein Bild aus einem Film als gewöhnliches Bild-Medium im Medienmanager ab (Medien- und Materialkarte).
|
||||
*
|
||||
* - Die Stelle kommt aus der bereitgestellten Fassung, bei einem Film ohne solche Fassung (zum Beispiel ein Teaser nur
|
||||
* mit Website-Datei) aus der Website-Datei (`teaser/`, Herkunft `frame:0@Sekunde`).
|
||||
* - Zwei Wege: das Vorschaubild des Films übernehmen oder eine Stelle (Sekunde) wählen. Beides ist eine
|
||||
* ausdrückliche Handlung der Redaktion; erst dadurch entsteht ein Bild, das für die Website freigegeben werden kann.
|
||||
* - Das Bild wird einmal gezogen und gespeichert (WebsiteIntake legt es an, die Warteschlange leitet es ab und gibt
|
||||
* es frei). Seitenaufrufe lesen nur die gespeicherte Datei und starten nie ffmpeg.
|
||||
* - Dieselbe Stelle (oder dieselbe Vorschaudatei) ergibt dasselbe Medium (film_still_sources).
|
||||
* - Es wird nie der Film selbst, nur ein Einzelbild bis 1600 px Breite abgelegt. Traineranleitungen und
|
||||
* archivierte oder gesperrte Filme sind ausgeschlossen. Eine Rechte- oder Lizenzentscheidung entsteht nicht.
|
||||
*/
|
||||
class FilmStill
|
||||
{
|
||||
/** Breite eines übernommenen Standbilds; die kleine Filmstufe (640 px) wäre auf der Website sichtbar unscharf. */
|
||||
public const WIDTH = 1600;
|
||||
|
||||
/** Wahr, wenn der letzte Aufruf ein schon vorhandenes Bild geliefert hat (keine neue Extraktion). */
|
||||
public bool $reused = false;
|
||||
|
||||
public function __construct(
|
||||
private readonly ThumbnailDeriver $deriver,
|
||||
private readonly WebsiteIntake $intake,
|
||||
) {}
|
||||
|
||||
/** Grund, warum aus diesem Medium kein Standbild übernommen wird, sonst null. */
|
||||
public function refusal(ContentElement $film): ?string
|
||||
{
|
||||
if ($film->output_class !== 'film') {
|
||||
return 'Nur aus einem Film lässt sich ein Bild übernehmen.';
|
||||
}
|
||||
|
||||
if ($film->archived_at !== null) {
|
||||
return 'Der Film ist archiviert.';
|
||||
}
|
||||
|
||||
$slug = $film->editorialContentKind?->slug;
|
||||
|
||||
if (in_array($slug, PublicMaterialReader::CONFIDENTIAL_KINDS, true)) {
|
||||
return 'Aus Traineranleitungen werden keine Bilder für die Website übernommen.';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Die bereitgestellte Fassung, aus der Stellen gezogen werden (die höchste). */
|
||||
public function version(ContentElement $film): ?ContentElementVersion
|
||||
{
|
||||
return $film->versions()
|
||||
->where('status', ContentVersionStatus::Bereit->value)
|
||||
->orderByDesc('number')
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Website-Datei, aus der Stellen gezogen werden, wenn es keine bereitgestellte Fassung gibt (Film nur mit
|
||||
* Website-Datei). Sonst null.
|
||||
*/
|
||||
public function websiteFile(ContentElement $film): ?string
|
||||
{
|
||||
$path = $film->preview_path;
|
||||
|
||||
if ($this->version($film) instanceof ContentElementVersion
|
||||
|| ! is_string($path) || $path === '' || str_contains($path, '..') || ! str_starts_with($path, 'teaser/')
|
||||
|| ! Storage::disk('media_derived')->exists($path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/** Sekunde der Stelle, aus der das aktuelle Vorschaubild des Films stammt, sonst null. */
|
||||
public function thumbnailSecond(ContentElement $film): ?string
|
||||
{
|
||||
$source = $film->thumbnail_source;
|
||||
|
||||
return is_string($source) && preg_match('/^frame:\d+@([\d.]+)$/', $source, $match) === 1 ? $match[1] : null;
|
||||
}
|
||||
|
||||
public function fromSecond(ContentElement $film, float $seconds, ?User $actor = null): ContentElement
|
||||
{
|
||||
$this->reused = false;
|
||||
$this->guard($film);
|
||||
|
||||
if ($seconds < 0 || $seconds > 7200) {
|
||||
throw new DomainRuleException('Die Zeitposition liegt außerhalb des Films.');
|
||||
}
|
||||
|
||||
$version = $this->version($film);
|
||||
|
||||
if (! $version instanceof ContentElementVersion) {
|
||||
if ($this->websiteFile($film) !== null) {
|
||||
return $this->fromWebsiteFrame($film, $seconds, $actor);
|
||||
}
|
||||
|
||||
throw new DomainRuleException('Der Film hat weder eine bereitgestellte Fassung noch eine Website-Datei.');
|
||||
}
|
||||
|
||||
return $this->fromFrame($film, $version, $seconds, $actor);
|
||||
}
|
||||
|
||||
public function fromThumbnail(ContentElement $film, ?User $actor = null): ContentElement
|
||||
{
|
||||
$this->reused = false;
|
||||
$this->guard($film);
|
||||
|
||||
// Stammt das Vorschaubild aus einer Filmstelle, wird dieselbe Stelle in voller Auflösung gezogen.
|
||||
$second = $this->thumbnailSecond($film);
|
||||
|
||||
if ($second !== null && preg_match('/^frame:(\d+)@/', (string) $film->thumbnail_source, $match) === 1) {
|
||||
$version = ContentElementVersion::query()->find((int) $match[1]);
|
||||
|
||||
if ($version instanceof ContentElementVersion
|
||||
&& (int) $version->content_element_id === (int) $film->id
|
||||
&& $version->status !== ContentVersionStatus::Gesperrt) {
|
||||
try {
|
||||
return $this->fromFrame($film, $version, (float) $second, $actor);
|
||||
} catch (DomainRuleException) {
|
||||
// Die Stelle lässt sich nicht mehr ziehen: das gespeicherte Vorschaubild selbst übernehmen.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$path = $film->thumbnail_path;
|
||||
|
||||
if (! is_string($path) || ! str_starts_with($path, 'vorschau/') || str_contains($path, '..') || ! Storage::disk('media_derived')->exists($path)) {
|
||||
throw new DomainRuleException('Dieser Film hat noch kein Vorschaubild. Setzen Sie es im Medienmanager oder wählen Sie eine Stelle.');
|
||||
}
|
||||
|
||||
$bytes = Storage::disk('media_derived')->get($path);
|
||||
|
||||
if (! is_string($bytes) || $bytes === '') {
|
||||
throw new DomainRuleException('Das Vorschaubild ließ sich nicht lesen.');
|
||||
}
|
||||
|
||||
$key = 'file:'.hash('sha256', $bytes);
|
||||
$existing = $this->existing($film, $key);
|
||||
|
||||
if ($existing instanceof ContentElement) {
|
||||
$this->reused = true;
|
||||
|
||||
return $existing;
|
||||
}
|
||||
|
||||
return $this->store($film, $key, $bytes, 'Vorschaubild', $actor);
|
||||
}
|
||||
|
||||
private function fromFrame(ContentElement $film, ContentElementVersion $version, float $seconds, ?User $actor): ContentElement
|
||||
{
|
||||
$second = $this->secondText($seconds);
|
||||
$key = 'frame:'.$version->id.'@'.$second;
|
||||
$existing = $this->existing($film, $key);
|
||||
|
||||
if ($existing instanceof ContentElement) {
|
||||
$this->reused = true;
|
||||
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$bytes = $this->deriver->frameJpeg($version, (float) $second, self::WIDTH, original: true);
|
||||
|
||||
if (! is_string($bytes)) {
|
||||
throw new DomainRuleException('Aus dieser Filmstelle ließ sich kein Bild erzeugen.');
|
||||
}
|
||||
|
||||
return $this->store($film, $key, $bytes, 'Fassung '.$version->number.', '.str_replace('.', ',', $second).' s', $actor);
|
||||
}
|
||||
|
||||
private function fromWebsiteFrame(ContentElement $film, float $seconds, ?User $actor): ContentElement
|
||||
{
|
||||
$second = $this->secondText($seconds);
|
||||
$key = 'frame:0@'.$second;
|
||||
$existing = $this->existing($film, $key);
|
||||
|
||||
if ($existing instanceof ContentElement) {
|
||||
$this->reused = true;
|
||||
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$bytes = $this->deriver->websiteFileJpeg($film, (float) $second, self::WIDTH);
|
||||
|
||||
if (! is_string($bytes)) {
|
||||
throw new DomainRuleException('Aus dieser Stelle der Website-Datei ließ sich kein Bild erzeugen.');
|
||||
}
|
||||
|
||||
return $this->store($film, $key, $bytes, 'Website-Datei, '.str_replace('.', ',', $second).' s', $actor);
|
||||
}
|
||||
|
||||
private function guard(ContentElement $film): void
|
||||
{
|
||||
$refusal = $this->refusal($film);
|
||||
|
||||
if ($refusal !== null) {
|
||||
throw new DomainRuleException($refusal);
|
||||
}
|
||||
}
|
||||
|
||||
private function existing(ContentElement $film, string $key): ?ContentElement
|
||||
{
|
||||
$source = FilmStillSource::query()->with('still')->where('film_element_id', $film->id)->where('source_key', $key)->first();
|
||||
$still = $source?->still;
|
||||
|
||||
// Ein archiviertes oder an der Verarbeitung gescheitertes Bild wird nicht wiederverwendet; die Stelle kann neu
|
||||
// übernommen werden (store() ordnet dann das neue Bild zu).
|
||||
return $still instanceof ContentElement && $still->archived_at === null && ! filled($still->thumbnail_error) ? $still : null;
|
||||
}
|
||||
|
||||
private function store(ContentElement $film, string $key, string $bytes, string $label, ?User $actor): ContentElement
|
||||
{
|
||||
$title = (string) ($film->display_title ?: $film->working_title);
|
||||
$path = 'cms/standbild-'.$film->id.'-'.Str::lower(Str::random(8)).'.jpg';
|
||||
Storage::disk('cms_incoming')->put($path, $bytes);
|
||||
|
||||
$still = $this->intake->acceptImage(
|
||||
$path,
|
||||
'Standbild: '.$title.' ('.$label.')',
|
||||
filled($film->website_credit) ? (string) $film->website_credit : null,
|
||||
'Szene aus dem Film „'.$title.'“',
|
||||
$actor,
|
||||
);
|
||||
|
||||
try {
|
||||
FilmStillSource::query()->updateOrCreate(
|
||||
['film_element_id' => $film->id, 'source_key' => $key],
|
||||
['still_element_id' => $still->id, 'actor_id' => $actor?->id],
|
||||
);
|
||||
} catch (QueryException) {
|
||||
// Gleichzeitige Übernahme derselben Stelle: das zuerst angelegte Bild gilt.
|
||||
return $this->existing($film, $key) ?? $still;
|
||||
}
|
||||
|
||||
return $still;
|
||||
}
|
||||
|
||||
private function secondText(float $seconds): string
|
||||
{
|
||||
$text = number_format(max(0, min(7200, $seconds)), 3, '.', '');
|
||||
|
||||
return rtrim(rtrim($text, '0'), '.') ?: '0';
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Herkunft eines Standbilds: aus welchem Film und welcher Stelle (frame:{Fassung}@{Sekunde}) oder aus welcher Datei
|
||||
* (file:{SHA-256}) das Bild-Medium stammt.
|
||||
*/
|
||||
class FilmStillSource extends Model
|
||||
{
|
||||
protected $fillable = ['film_element_id', 'still_element_id', 'source_key', 'actor_id'];
|
||||
|
||||
public function film(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContentElement::class, 'film_element_id');
|
||||
}
|
||||
|
||||
public function still(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContentElement::class, 'still_element_id');
|
||||
}
|
||||
}
|
||||
@@ -4,72 +4,39 @@
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Jobs\StorePresentationFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Legt die technische Ableitung eines Präsentationsmediums (Website-Datei) an der Medienidentität ab.
|
||||
* Es entsteht keine Inhaltsfassung, keine Freigabe und keine Berechtigung. Eine vorhandene Inhaltsfassung bleibt
|
||||
* unverändert und geschützt; die Website-Datei ist eine eigene, bewusst gewählte Datei daneben.
|
||||
*
|
||||
* Der Web-Prozess hat `derived/` nur lesend. Er prüft deshalb nur und gibt das Kopieren an die Warteschlange
|
||||
* (`StorePresentationFile`, ruft `place()` auf).
|
||||
* Legt die technische Ableitung eines Präsentationsmediums an der Medienidentität ab.
|
||||
* Es entsteht keine Inhaltsfassung, keine Freigabe und keine Berechtigung.
|
||||
*/
|
||||
class PresentationFile
|
||||
{
|
||||
/**
|
||||
* Dateiendungen, die ein Browser auf der Website abspielen kann.
|
||||
*
|
||||
* @var array<string, list<string>>
|
||||
*/
|
||||
public const EXTENSIONS = [
|
||||
'bild' => ['jpg', 'jpeg', 'png', 'webp', 'gif'],
|
||||
'audio' => ['mp3', 'm4a', 'ogg'],
|
||||
'film' => ['mp4', 'webm'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Prüft die Datei im Eingang, ohne etwas zu verändern. Wirft eine verständliche Regelverletzung.
|
||||
*/
|
||||
public function validate(string $outputClass, string $incoming): void
|
||||
public function store(ContentElement $element, string $incoming): void
|
||||
{
|
||||
if (! isset(self::EXTENSIONS[$outputClass])) {
|
||||
if (! in_array($element->output_class, ['bild', 'film', 'audio'], true)) {
|
||||
throw new DomainRuleException('Eine Präsentationsdatei ist ein Bild, ein Film oder ein Hörstück.');
|
||||
}
|
||||
|
||||
$extension = strtolower(pathinfo($incoming, PATHINFO_EXTENSION));
|
||||
|
||||
if (! in_array($extension, self::EXTENSIONS[$outputClass], true)) {
|
||||
throw new DomainRuleException(sprintf(
|
||||
'Für die Website geht nur %s. Eine %s-Datei kann der Browser nicht direkt abspielen; wandle sie vorher um oder lade sie ohne „Eigenständiges Präsentationsmedium“ hoch.',
|
||||
$this->formats($outputClass),
|
||||
$extension === '' ? 'Datei ohne Endung' : '.'.$extension,
|
||||
));
|
||||
if ($element->versions()->exists()) {
|
||||
throw new DomainRuleException('Dieses Medium hat bereits eine Inhaltsfassung. Die Präsentationsdatei ersetzt sie nicht.');
|
||||
}
|
||||
|
||||
if (! $this->readable($incoming)) {
|
||||
throw new DomainRuleException('Die Datei liegt nicht im Eingang.');
|
||||
}
|
||||
}
|
||||
|
||||
public function store(ContentElement $element, string $incoming): void
|
||||
{
|
||||
$this->validate((string) $element->output_class, $incoming);
|
||||
|
||||
$element->thumbnail_error = null;
|
||||
$element->save();
|
||||
|
||||
StorePresentationFile::dispatch($element->id, $incoming);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kopiert die Datei nach `derived/`. Läuft nur in der Warteschlange, die dort schreiben darf.
|
||||
*/
|
||||
public function place(ContentElement $element, string $incoming): void
|
||||
{
|
||||
$this->validate((string) $element->output_class, $incoming);
|
||||
|
||||
$extension = strtolower(pathinfo($incoming, PATHINFO_EXTENSION));
|
||||
$allowed = match ($element->output_class) {
|
||||
'bild' => ['jpg', 'jpeg', 'png', 'webp', 'gif'],
|
||||
'audio' => ['mp3', 'm4a', 'ogg'],
|
||||
default => ['mp4', 'webm'],
|
||||
};
|
||||
|
||||
if (! in_array($extension, $allowed, true)) {
|
||||
throw new DomainRuleException('Diese Datei ist keine freigebbare Ableitung. Es wird keine Inhaltsfassung angelegt.');
|
||||
}
|
||||
|
||||
$prefix = $element->output_class === 'bild' ? 'vorschau' : 'teaser';
|
||||
$target = $prefix.'/'.$element->id.'/datei.'.$extension;
|
||||
$stream = Storage::disk('cms_incoming')->readStream($incoming);
|
||||
@@ -79,15 +46,11 @@ public function place(ContentElement $element, string $incoming): void
|
||||
}
|
||||
|
||||
try {
|
||||
$written = Storage::disk('media_derived')->writeStream($target, $stream);
|
||||
Storage::disk('media_derived')->writeStream($target, $stream);
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
|
||||
if ($written === false) {
|
||||
throw new DomainRuleException('Die Datei ließ sich nicht ablegen.');
|
||||
}
|
||||
|
||||
if ($element->output_class === 'bild') {
|
||||
$element->thumbnail_path = $target;
|
||||
$element->thumbnail_source = 'eigen';
|
||||
@@ -95,18 +58,7 @@ public function place(ContentElement $element, string $incoming): void
|
||||
$element->preview_path = $target;
|
||||
}
|
||||
|
||||
$element->thumbnail_error = null;
|
||||
$element->save();
|
||||
Storage::disk('cms_incoming')->delete($incoming);
|
||||
}
|
||||
|
||||
public function formats(string $outputClass): string
|
||||
{
|
||||
return match ($outputClass) {
|
||||
'bild' => 'JPG, PNG, WebP oder GIF',
|
||||
'audio' => 'MP3, M4A oder OGG',
|
||||
default => 'MP4 (H.264) oder WebM',
|
||||
};
|
||||
}
|
||||
|
||||
private function readable(string $path): bool
|
||||
|
||||
@@ -87,27 +87,6 @@ public function forElementFrame(ContentElement $element, ContentElementVersion $
|
||||
$this->rememberElement($element, 'frame:'.$version->id.'@'.$this->secondText($seconds));
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschaubild aus einer Stelle der Website-Datei. Die Herkunft steht als `frame:0@{Sekunde}`; die 0 steht für die
|
||||
* Website-Datei (es gibt keine Fassung), alle Leser der Herkunft kommen damit zurecht.
|
||||
*/
|
||||
public function forElementWebsiteFrame(ContentElement $element, float $seconds): void
|
||||
{
|
||||
$bytes = $this->jpegAtWebsiteFile($element, $seconds);
|
||||
|
||||
if (! is_string($bytes)) {
|
||||
$this->fail($element, 'Aus dieser Filmstelle ließ sich kein Vorschaubild erzeugen.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$name = 'element-'.$element->id;
|
||||
$path = 'vorschau/'.$name.'.jpg';
|
||||
Storage::disk('media_derived')->put($path, $bytes);
|
||||
$this->still($element, Storage::disk('media_derived'), $path, $name);
|
||||
$this->rememberElement($element, 'frame:0@'.$this->secondText($seconds));
|
||||
}
|
||||
|
||||
public function forCompositionUpload(Composition $composition, string $incoming): void
|
||||
{
|
||||
if (! str_starts_with($incoming, 'vorschau/') || str_contains($incoming, '..')) {
|
||||
@@ -159,20 +138,8 @@ public function forCompositionFrame(Composition $composition, ContentElementVers
|
||||
$this->rememberChoice($composition, 'frame:'.$version->id.'@'.$this->secondText($seconds));
|
||||
}
|
||||
|
||||
/**
|
||||
* Datei, aus der ein Bild gezogen wird. Vorgabe: die kleine Filmstufe (schnell, für die Vorschau). Mit $original
|
||||
* zuerst die Mediendatei selbst, damit ein übernommenes Standbild nicht aus der kleinen Stufe hochgerechnet wird.
|
||||
*/
|
||||
public function frameInput(ContentElementVersion $version, bool $original = false): ?string
|
||||
public function frameInput(ContentElementVersion $version): ?string
|
||||
{
|
||||
if ($original) {
|
||||
$master = is_array($version->metadata) ? ($version->metadata['file'] ?? null) : null;
|
||||
|
||||
if ($this->readableDerived($master, 'inhalte/')) {
|
||||
return $master;
|
||||
}
|
||||
}
|
||||
|
||||
$proxy = MediaRendition::query()
|
||||
->where('content_element_version_id', $version->id)
|
||||
->where('role', 'variant')
|
||||
@@ -188,55 +155,15 @@ public function frameInput(ContentElementVersion $version, bool $original = fals
|
||||
return $this->readableDerived($file, 'inhalte/') ? $file : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Einzelbild einer Filmstelle als JPEG, 640 px breit aus der kleinen Stufe (Vorschau im Editor und Vorschaubild).
|
||||
*/
|
||||
public function jpegAtVersion(ContentElementVersion $version, float $seconds): ?string
|
||||
{
|
||||
return $this->frameJpeg($version, $seconds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Einzelbild einer Filmstelle als JPEG. Ein übernommenes Standbild (FilmStill) wird mit $width und $original aus der
|
||||
* Mediendatei gezogen statt aus der kleinen Stufe und dabei nie über die Breite der Quelle hinaus vergrößert.
|
||||
*/
|
||||
public function frameJpeg(ContentElementVersion $version, float $seconds, int $width = 640, bool $original = false): ?string
|
||||
{
|
||||
if ($seconds < 0 || $seconds > 7200) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$file = $this->frameInput($version, $original);
|
||||
$file = $this->frameInput($version);
|
||||
|
||||
return $file === null ? null : $this->jpegFromFile($file, $seconds, $width);
|
||||
}
|
||||
|
||||
/**
|
||||
* Einzelbild aus der Website-Datei eines Films (`teaser/`), für Medien ohne Inhaltsfassung.
|
||||
*/
|
||||
public function jpegAtWebsiteFile(ContentElement $element, float $seconds): ?string
|
||||
{
|
||||
return $this->websiteFileJpeg($element, $seconds, 640);
|
||||
}
|
||||
|
||||
/**
|
||||
* Einzelbild aus der Website-Datei in der gewünschten Breite, nie über die Breite der Datei hinaus (Standbild für
|
||||
* die Medienkarte, FilmStill).
|
||||
*/
|
||||
public function websiteFileJpeg(ContentElement $element, float $seconds, int $width): ?string
|
||||
{
|
||||
$file = $element->preview_path;
|
||||
|
||||
if ($element->output_class !== 'film' || ! $this->readableDerived($file, 'teaser/')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->jpegFromFile($file, $seconds, $width);
|
||||
}
|
||||
|
||||
private function jpegFromFile(string $file, float $seconds, int $width): ?string
|
||||
{
|
||||
if ($seconds < 0 || $seconds > 7200) {
|
||||
if ($file === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -259,7 +186,7 @@ private function jpegFromFile(string $file, float $seconds, int $width): ?string
|
||||
'-frames:v',
|
||||
'1',
|
||||
'-vf',
|
||||
$width === 640 ? 'scale=640:-2' : 'scale=min('.max(160, min(2400, $width)).'\,iw):-2',
|
||||
'scale=640:-2',
|
||||
'-f',
|
||||
'image2pipe',
|
||||
'-vcodec',
|
||||
|
||||
@@ -37,16 +37,6 @@ public static function effectiveFor(mixed $path): ?self
|
||||
return $alias instanceof self && $alias->everReleased() ? $alias : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Früherer Pfad, dessen übernommenes Medium inzwischen gelöscht wurde. Die Datei unter cms/ bleibt liegen, wird aber
|
||||
* weder ausgeliefert noch als Bild gezeigt: Das Löschen des Mediums gilt auch für die frühere Adresse.
|
||||
*/
|
||||
public static function isRetired(mixed $path): bool
|
||||
{
|
||||
return is_string($path) && $path !== ''
|
||||
&& self::query()->where('legacy_path', $path)->whereNull('content_element_id')->exists();
|
||||
}
|
||||
|
||||
public function everReleased(): bool
|
||||
{
|
||||
$element = $this->element;
|
||||
|
||||
@@ -44,7 +44,7 @@ public function refusal(ContentElement $element): ?string
|
||||
}
|
||||
|
||||
if ($this->derivedPath($element) === null) {
|
||||
return 'Für die Website fehlt eine freigebbare Datei. Beim Bild ist das das Vorschaubild. Bei Film und Hörstück lädst du unter „Website-Freigabe“ eine Website-Datei hoch (Film als MP4 oder WebM); die geschützte Originaldatei bleibt unberührt.';
|
||||
return 'Für die Website fehlt eine freigebbare Ableitung. Beim Bild ist das das Vorschaubild. Film und Hörstück ohne Inhaltsfassung nutzen die Datei am Medium unter teaser/. Ein Film mit Inhaltsfassung nutzt die Teaserfassung seiner bereitgestellten Fassung. Die Originaldatei bleibt geschützt.';
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Domain\Design\DesignScale;
|
||||
use App\Domain\Design\DesignSettings;
|
||||
use App\Domain\Identity\StaffRole;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
/**
|
||||
* Website → Design → Größen (ADR-44): die zehn Basiswerte der Größenskala einsehen, ändern, speichern und auf die
|
||||
* Standardwerte zurücksetzen. Gespeichert wird erst mit „Größen speichern“; offene Eingaben bleiben beim Wechseln
|
||||
* der Ansicht erhalten. Die Werte wirken sofort auf die öffentliche Website und alle CMS-Vorschauen, ohne Deployment.
|
||||
* Zugriff nur für den Systemverwalter.
|
||||
*/
|
||||
class DesignGroessen extends Page
|
||||
{
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Design';
|
||||
|
||||
protected static ?string $navigationLabel = 'Größen';
|
||||
|
||||
protected static ?int $navigationSort = 30;
|
||||
|
||||
protected static ?string $slug = 'design/groessen';
|
||||
|
||||
protected static ?string $title = 'Größen';
|
||||
|
||||
protected string $view = 'filament.design.groessen';
|
||||
|
||||
/** Eingaben je Basiswert (Zeichenketten aus dem Formular). @var array<string, int|string> */
|
||||
public array $werte = [];
|
||||
|
||||
/** Fehlermeldungen je Basiswert nach dem letzten Speichern. @var array<string, string> */
|
||||
public array $fehler = [];
|
||||
|
||||
/** @var array{aktion: string, argument: int|string|null, titel: string, text: string, label: string, gefahr: bool}|null */
|
||||
public ?array $bestaetigung = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return auth()->user()?->hasStaffRole(StaffRole::Systemverwalter) === true;
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->ladeGespeicherte();
|
||||
}
|
||||
|
||||
/** Die Überschrift steht im gemeinsamen Objektkopf (filament.verwaltung.kopf), nicht doppelt im Seitenkopf. */
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::SevenExtraLarge;
|
||||
}
|
||||
|
||||
/** Wirksame Werte der Website (gespeichert oder Standard). @return array<string, int> */
|
||||
public function gespeichert(): array
|
||||
{
|
||||
return DesignSettings::values();
|
||||
}
|
||||
|
||||
/** Ob die Eingaben vom wirksamen Stand abweichen. */
|
||||
public function geaendert(): bool
|
||||
{
|
||||
$aktuell = [];
|
||||
|
||||
foreach (array_keys(DesignScale::PARAMETERS) as $key) {
|
||||
$wert = $this->werte[$key] ?? '';
|
||||
$aktuell[$key] = is_string($wert) && ctype_digit($wert) ? (int) $wert : $wert;
|
||||
}
|
||||
|
||||
return $aktuell !== $this->gespeichert();
|
||||
}
|
||||
|
||||
/** Eine Eingabe wurde geändert: ihre Fehlermeldung vom letzten Speichern entfällt. */
|
||||
public function updatedWerte(mixed $value, string $key): void
|
||||
{
|
||||
unset($this->fehler[$key]);
|
||||
}
|
||||
|
||||
public function speichern(): void
|
||||
{
|
||||
$this->fehler = DesignSettings::save($this->werte, auth()->user());
|
||||
|
||||
if ($this->fehler !== []) {
|
||||
Notification::make()->danger()->title('Nicht gespeichert')->body('Bitte die markierten Werte korrigieren.')->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->ladeGespeicherte();
|
||||
Notification::make()->success()->title('Größen gespeichert')->body('Die Werte gelten jetzt auf der Website und in den CMS-Vorschauen.')->send();
|
||||
}
|
||||
|
||||
public function askConfirmation(string $aktion, int|string|null $argument = null): void
|
||||
{
|
||||
$this->bestaetigung = match ($aktion) {
|
||||
'standard' => ['aktion' => 'standard', 'argument' => null, 'titel' => 'Standardwerte wiederherstellen?', 'text' => 'Die gespeicherten Größen werden entfernt. Website und Vorschauen verwenden sofort wieder die Standardwerte aus dem Designsystem. Offene Eingaben gehen dabei verloren.', 'label' => 'Standardwerte wiederherstellen', 'gefahr' => true],
|
||||
'verwerfen' => ['aktion' => 'verwerfen', 'argument' => null, 'titel' => 'Änderungen verwerfen?', 'text' => 'Die Eingaben kehren zum wirksamen Stand zurück. Gespeichert wird dabei nichts.', 'label' => 'Verwerfen', 'gefahr' => true],
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
public function confirmConfirmation(): void
|
||||
{
|
||||
$frage = $this->bestaetigung;
|
||||
$this->bestaetigung = null;
|
||||
|
||||
match ($frage['aktion'] ?? null) {
|
||||
'standard' => $this->standardWiederherstellen(),
|
||||
'verwerfen' => $this->ladeGespeicherte(),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
public function cancelConfirmation(): void
|
||||
{
|
||||
$this->bestaetigung = null;
|
||||
}
|
||||
|
||||
private function standardWiederherstellen(): void
|
||||
{
|
||||
DesignSettings::reset();
|
||||
$this->ladeGespeicherte();
|
||||
Notification::make()->success()->title('Standardwerte wiederhergestellt')->body('Website und Vorschauen verwenden wieder die Standardwerte.')->send();
|
||||
}
|
||||
|
||||
private function ladeGespeicherte(): void
|
||||
{
|
||||
$this->werte = $this->gespeichert();
|
||||
$this->fehler = [];
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Domain\Commerce\SalesTerms;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Verkaufsstart: Was ist bereit, was fehlt noch? Die Seite liest nur. Sie nennt die fehlenden Rechtstexte, den
|
||||
* Zustand der Zahlungseinrichtung und der Produktivfreigabe, ohne Schlüssel oder Werte zu zeigen. Die Produktivfreigabe
|
||||
* ist eine Entscheidung von Lars und wird nicht hier, sondern in der Umgebungsdatei des Servers gesetzt.
|
||||
*/
|
||||
class Verkaufsstart extends Page
|
||||
{
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||
|
||||
protected static ?string $navigationLabel = 'Verkaufsstart';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
protected static ?string $slug = 'verkaufsstart';
|
||||
|
||||
protected static ?string $title = 'Verkaufsstart';
|
||||
|
||||
protected string $view = 'filament.pages.verkaufsstart';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return ShopAccess::allowed();
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function daten(): array
|
||||
{
|
||||
$legal = [];
|
||||
|
||||
foreach (SalesTerms::pages() as $key => $definition) {
|
||||
$page = SalesTerms::page($key);
|
||||
$legal[] = [
|
||||
'text' => $definition['label'],
|
||||
'neben' => $page === null
|
||||
? 'Fehlt: Es gibt keine veröffentlichte Seite unter '.implode(' oder ', $definition['paths']).'. Die Seite pflegst du in der Webpräsenz; den Text liefert die Rechtsberatung.'
|
||||
: 'Veröffentlicht unter '.$page->path.'. Inhalt und Vollständigkeit prüft die Rechtsberatung.',
|
||||
'zustand' => $page === null ? ['label' => 'Fehlt', 'ton' => 'offen'] : ['label' => 'Veröffentlicht', 'ton' => 'gut'],
|
||||
];
|
||||
}
|
||||
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
$mode = match (true) {
|
||||
$secret === '' => 'nicht eingerichtet',
|
||||
str_starts_with($secret, 'sk_test_'), str_starts_with($secret, 'rk_test_') => 'Testmodus',
|
||||
str_starts_with($secret, 'sk_live_'), str_starts_with($secret, 'rk_live_') => 'Live-Schlüssel',
|
||||
default => 'unbekanntes Format',
|
||||
};
|
||||
$withoutScope = DB::table('offer_versions')->where('status', 'aktiv')->where('grant_kind', 'kauf')->whereNull('licence_scope')->count();
|
||||
|
||||
$zahlung = [
|
||||
['text' => 'Zahlungsweg: '.Shop::driver(), 'neben' => 'Test: Testzahlung ohne Anbieter. Stripe: Kasse bei Stripe.', 'zustand' => Shop::driver() === 'stripe' ? ['label' => 'Stripe', 'ton' => 'gut'] : ['label' => 'Test', 'ton' => 'neutral']],
|
||||
['text' => 'Stripe-Schlüssel: '.$mode, 'neben' => 'Der Schlüssel steht nur in der Umgebungsdatei des Servers und wird hier nie angezeigt.', 'zustand' => $mode === 'nicht eingerichtet' ? ['label' => 'Fehlt', 'ton' => 'offen'] : ['label' => $mode, 'ton' => 'neutral']],
|
||||
['text' => 'Signaturschlüssel für Stripe-Meldungen: '.(filled(config('services.stripe.webhook_secret')) ? 'gesetzt' : 'fehlt'), 'neben' => 'Ohne ihn weist die Anwendung jede Meldung von Stripe ab; Zahlungen schalten dann nichts frei.', 'zustand' => filled(config('services.stripe.webhook_secret')) ? ['label' => 'Gesetzt', 'ton' => 'gut'] : ['label' => 'Fehlt', 'ton' => 'offen']],
|
||||
['text' => 'Steuersatz bei Stripe: '.(filled(config('services.stripe.tax_rate')) ? 'hinterlegt' : 'nicht hinterlegt'), 'neben' => 'Steuerstatus und Belegangaben sind noch nicht entschieden (OPEN-06). Ohne sie gibt es keinen Steuerausweis auf der Stripe-Kasse und keine Rechnungsvorlage.', 'zustand' => filled(config('services.stripe.tax_rate')) ? ['label' => 'Hinterlegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
|
||||
['text' => 'Aussteller auf dem Zahlungsbeleg: '.(filled(config('shop.receipt.issuer')) ? 'gepflegt' : 'nicht gepflegt'), 'neben' => 'Mitglieder laden zu jeder Zahlung einen Beleg (PDF) herunter. Er nennt den Aussteller nur, wenn er mit SHOP_RECEIPT_ISSUER gepflegt ist (Zeilen durch „|“ getrennt). Name und Anschrift des Verkäufers, Steuerangaben und eine Rechnungsnummer hängen an der rechtlichen Klärung (OPEN-06); bis dahin trägt der Beleg keine steuerlichen Angaben.', 'zustand' => filled(config('shop.receipt.issuer')) ? ['label' => 'Gepflegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
|
||||
['text' => 'Kauf auf Rechnung für Vereine: '.(Shop::invoice() ? 'angeboten' : 'aus'), 'neben' => Shop::invoice()
|
||||
? 'Die Rechnung erstellt der Betreiber manuell; den Zahlungseingang bestätigst du in der Bestellverwaltung. Vereine sehen die Möglichkeit im Checkout.'
|
||||
: 'Mitglieder sehen die Möglichkeit nicht. Sie wird erst angeboten, wenn der Prozess vollständig ist: Rechnungserstellung mit Nummernkreis, Benachrichtigung des Betreibers bei neuer Rechnungsbestellung und die rechtliche Klärung (OPEN-06). Die Umsetzung ist vorbereitet; schaltest du sie mit SHOP_INVOICE=true in der Umgebungsdatei ein, erscheint sie im Checkout. Bereits angelegte Rechnungsbestellungen bleiben in der Bestellverwaltung bearbeitbar.',
|
||||
'zustand' => Shop::invoice() ? ['label' => 'Angeboten', 'ton' => 'neutral'] : ['label' => 'Aus', 'ton' => 'neutral']],
|
||||
];
|
||||
|
||||
$freigabe = [
|
||||
['text' => 'Produktivfreigabe (SHOP_LIVE_RELEASE): '.(config('shop.live_release') === true ? 'gesetzt' : 'nicht gesetzt'), 'neben' => 'Standardmäßig aus. Setzt Lars in der Umgebungsdatei des Servers, wenn er den Verkauf freigibt. Ohne sie bleibt der Shop in Produktion abgeschaltet und Stripe nimmt dort keine Zahlung an.', 'zustand' => config('shop.live_release') === true ? ['label' => 'Gesetzt', 'ton' => 'gut'] : ['label' => 'Aus', 'ton' => 'neutral']],
|
||||
['text' => 'Umgebung: '.(app()->isProduction() ? 'Produktion' : 'Test oder lokal'), 'neben' => app()->isProduction() ? 'Der Shop ist hier '.(Shop::enabled() ? 'aktiv.' : 'abgeschaltet.') : 'Hier läuft der Shop mit Test- oder Sandbox-Zahlung.', 'zustand' => app()->isProduction() ? (Shop::enabled() ? ['label' => 'Live', 'ton' => 'gut'] : ['label' => 'Abgeschaltet', 'ton' => 'neutral']) : ['label' => 'Test', 'ton' => 'neutral']],
|
||||
];
|
||||
|
||||
$angebote = [
|
||||
['text' => $withoutScope === 0 ? 'Alle aktiven Käufe haben einen Nutzerkreis.' : $withoutScope.' aktive Kaufangebote ohne festgelegten Nutzerkreis', 'neben' => $withoutScope === 0 ? null : 'Käufer sähen „Nutzerkreis nicht festgelegt“. Lege Einzel- oder Mehrfachlizenz mit „Geänderte Fassung aktivieren“ am Angebot fest.', 'zustand' => $withoutScope === 0 ? ['label' => 'Vollständig', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
|
||||
];
|
||||
|
||||
return [
|
||||
'kopf' => [
|
||||
'titel' => 'Verkaufsstart',
|
||||
'typ' => 'Bereitschaft für den Verkauf in Deutschland',
|
||||
'status' => ['text' => SalesTerms::missingPages() === [] ? 'Alle Rechtstexte sind veröffentlicht. Die rechtliche Freigabe der Inhalte steht aus, bis die Rechtsberatung sie bestätigt.' : 'Es fehlen veröffentlichte Rechtstexte. Ohne sie bleibt der Shop in Produktion abgeschaltet.', 'ton' => SalesTerms::missingPages() === [] ? 'gut' : 'offen'],
|
||||
],
|
||||
'haupt' => [
|
||||
['titel' => 'Rechtstexte im Bestellablauf', 'hilfe' => 'Der Checkout verlinkt diese Seiten und hält mit jeder Bestellung fest, welche Fassung galt. Den Wortlaut der Zustimmungen im Checkout hat der Betreiber noch rechtlich zu prüfen (Entwurf '.SalesTerms::VERSION.').', 'zeilen' => $legal],
|
||||
['titel' => 'Zahlung und Belege', 'zeilen' => $zahlung],
|
||||
],
|
||||
'seite' => [
|
||||
['titel' => 'Freigabe', 'zeilen' => $freigabe, 'hilfe' => 'Die Produktivfreigabe liegt bei Lars. Sie wird nicht über diese Oberfläche gesetzt.'],
|
||||
['titel' => 'Angebote', 'zeilen' => $angebote],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
<?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']);
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@
|
||||
use App\Filament\Resources\Bundles\BundleResource;
|
||||
use App\Filament\Support\CatalogOptions;
|
||||
use App\Filament\Support\CatalogReading;
|
||||
use App\Filament\Support\PublicationReadiness;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\CheckboxList;
|
||||
@@ -91,8 +90,7 @@ public function publishAction(): Action
|
||||
->modalSubmitActionLabel(fn (): string => 'Fassung '.$this->nextNumber().' veröffentlichen')
|
||||
->fillForm(fn (): array => $this->formFromPublished())
|
||||
->schema([
|
||||
CheckboxList::make('articles')->label('Lizenzartikel')->options(fn (): array => app(PublicationReadiness::class)->articleOptions())
|
||||
->helperText('Artikel ohne Stand lassen sich aufnehmen, aber erst verkaufen, wenn sie einen Inhalt haben.'),
|
||||
CheckboxList::make('articles')->label('Lizenzartikel')->options(fn (): array => CatalogOptions::articles()),
|
||||
CheckboxList::make('bundles')->label('Enthaltene Pakete')
|
||||
->options(function (): array {
|
||||
$options = CatalogOptions::bundles();
|
||||
@@ -117,12 +115,7 @@ public function publishAction(): Action
|
||||
|
||||
$version = app(BundleService::class)->publish($bundle, $items);
|
||||
|
||||
$bundle->unsetRelations();
|
||||
$readiness = app(PublicationReadiness::class)->forBundle($bundle->refresh());
|
||||
|
||||
return 'Fassung '.$version->number.' ist veröffentlicht.'.($readiness['naechster'] !== null
|
||||
? ' Nächster Schritt: '.$readiness['naechster']['titel'].'.'
|
||||
: '');
|
||||
return 'Fassung '.$version->number.' ist veröffentlicht.';
|
||||
}, 'Die Paketfassung ist veröffentlicht.');
|
||||
$this->getRecord()->unsetRelations();
|
||||
$this->getRecord()->refresh();
|
||||
@@ -171,7 +164,6 @@ private function paketDaten(): array
|
||||
'art' => 'primary',
|
||||
]],
|
||||
],
|
||||
'voraussetzungen' => app(PublicationReadiness::class)->forBundle($bundle),
|
||||
'haupt' => [
|
||||
[
|
||||
'titel' => 'Bestandteile',
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Support\AssignsPillars;
|
||||
use App\Filament\Support\EditorialCatalog;
|
||||
use App\Filament\Support\ManagesEditorialSurface;
|
||||
use App\Filament\Support\MediumForm;
|
||||
@@ -44,7 +43,6 @@
|
||||
|
||||
abstract class EditComposition extends EditRecord
|
||||
{
|
||||
use AssignsPillars;
|
||||
use ManagesEditorialSurface;
|
||||
use WithFileUploads;
|
||||
|
||||
@@ -400,15 +398,11 @@ public function redaktionTexteHinweis(): string
|
||||
*/
|
||||
public function einordnungGruppen(): array
|
||||
{
|
||||
$groups = array_map(fn (array $group): array => [
|
||||
return array_map(fn (array $group): array => [
|
||||
'legend' => $group['label'],
|
||||
'model' => 'dimensionIds',
|
||||
'values' => $group['values'],
|
||||
], $this->dimensionGroups());
|
||||
|
||||
$pillars = $this->pillarGroup();
|
||||
|
||||
return $pillars === null ? $groups : [$pillars, ...$groups];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -472,7 +466,7 @@ public function einordnungUnsaved(): bool
|
||||
sort($stored);
|
||||
sort($current);
|
||||
|
||||
return $stored !== $current || $this->pillarsUnsaved($record);
|
||||
return $stored !== $current;
|
||||
}
|
||||
|
||||
public function openText(): void
|
||||
@@ -1660,7 +1654,6 @@ protected function fillRedaktion(): void
|
||||
->pluck('editorial_dimension_value_id')
|
||||
->map(fn (mixed $id): string => (string) (int) $id)
|
||||
->all();
|
||||
$this->loadPillarIds($composition);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1920,7 +1913,6 @@ protected function persistRedaktion(): bool
|
||||
'description' => $this->description,
|
||||
], $this->actor());
|
||||
$this->syncDimensions($record, array_map(intval(...), $this->dimensionIds));
|
||||
$this->persistPillarIds($record);
|
||||
$record->refresh();
|
||||
$this->getRecord()->setRawAttributes($record->getAttributes());
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
namespace App\Filament\Resources\ContentElements\Pages;
|
||||
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\PillarFilterCompat;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Support\Bestand;
|
||||
use App\Filament\Support\MediaLibrary;
|
||||
@@ -40,9 +39,6 @@ class ListContentElements extends ListRecords
|
||||
#[Url(as: 'freigabe', except: '')]
|
||||
public string $freigabe = '';
|
||||
|
||||
#[Url(as: 'schutz', except: '')]
|
||||
public string $schutz = '';
|
||||
|
||||
#[Url(as: 'entwurf', except: '')]
|
||||
public string $entwurf = '';
|
||||
|
||||
@@ -88,7 +84,7 @@ public function content(Schema $schema): Schema
|
||||
|
||||
protected function bestandFilterEigenschaften(): array
|
||||
{
|
||||
return ['suche', 'art', 'schutz', 'freigabe', 'entwurf', 'fassung', 'nutzung', 'saeule', 'inhaltsart', 'einordnung', 'verarbeitung', 'archiv'];
|
||||
return ['suche', 'art', 'freigabe', 'entwurf', 'fassung', 'nutzung', 'saeule', 'inhaltsart', 'einordnung', 'verarbeitung', 'archiv'];
|
||||
}
|
||||
|
||||
public function showingList(): bool
|
||||
@@ -141,7 +137,6 @@ public function filtersActive(): bool
|
||||
return trim($this->suche) !== ''
|
||||
|| $this->art !== ''
|
||||
|| $this->freigabe !== ''
|
||||
|| $this->schutz !== ''
|
||||
|| $this->entwurf !== ''
|
||||
|| $this->fassung !== ''
|
||||
|| $this->nutzung !== ''
|
||||
@@ -157,7 +152,6 @@ public function resetFilters(): void
|
||||
$this->suche = '';
|
||||
$this->art = '';
|
||||
$this->freigabe = '';
|
||||
$this->schutz = '';
|
||||
$this->entwurf = '';
|
||||
$this->fassung = '';
|
||||
$this->nutzung = '';
|
||||
@@ -176,11 +170,6 @@ public function resetFilters(): void
|
||||
*/
|
||||
public function bestand(): array
|
||||
{
|
||||
// Alte Adressen mit einem Säulenwert der Einordnung gelten für die zentrale Säule.
|
||||
if (ctype_digit($this->einordnung) && $this->saeule === '' && is_int($pillar = PillarFilterCompat::pillarOfLegacyValue((int) $this->einordnung))) {
|
||||
[$this->saeule, $this->einordnung] = [(string) $pillar, ''];
|
||||
}
|
||||
|
||||
$optionen = fn (array $liste, string $wert, string $label): array => collect($liste)
|
||||
->mapWithKeys(fn (array $eintrag): array => [(string) $eintrag[$wert] => $eintrag[$label]])
|
||||
->all();
|
||||
@@ -205,12 +194,11 @@ public function bestand(): array
|
||||
'suche' => ['eigenschaft' => 'suche', 'label' => 'Suche', 'platzhalter' => 'Titel, Beschreibung oder Suchbegriff'],
|
||||
'filter' => [
|
||||
['eigenschaft' => 'art', 'label' => 'Technische Art', 'vorgabe' => '', 'alle' => 'Alle Arten', 'optionen' => $optionen($this->typeOptions(), 'value', 'label')],
|
||||
['eigenschaft' => 'schutz', 'label' => 'Schutz', 'vorgabe' => '', 'alle' => 'Alle Medien', 'optionen' => ['geschuetzt' => 'Geschützte Medien', 'oeffentlich' => 'Öffentliche Medien', 'website' => 'Auf der Website frei']],
|
||||
['eigenschaft' => 'freigabe', 'label' => 'Freigabe', 'vorgabe' => '', 'alle' => 'Alle Freigaben', 'optionen' => ['freigegeben' => 'Freigegebene Fassung', 'entwurf' => 'Nur offener Entwurf', 'ohne' => 'Keine freigegebene Fassung']],
|
||||
['eigenschaft' => 'nutzung', 'label' => 'Verwendung', 'vorgabe' => '', 'alle' => 'Verwendung egal', 'optionen' => ['verwendet' => 'Verwendet', 'unbenutzt' => 'Nicht verwendet']],
|
||||
],
|
||||
'weitere' => $weitere,
|
||||
'hinweis' => 'Freigabe meint die Fassung des Mediums, nicht die Website und keinen Zugriff. Geschützte Medien haben eine Inhaltsfassung und laufen über Lizenzen. Öffentliche Medien sind eigenständige Präsentationsmedien ohne Fassung für die Website; ob sie freigegeben sind, zeigt die Kennzeichnung an der Zeile. Materialart und Einordnung sind die redaktionelle Klassifikation; Verwendung zeigt, wo das Medium tatsächlich eingebunden ist. Deaktivierte und archivierte Medien bleiben über „Weitere Filter“ auffindbar.',
|
||||
'hinweis' => 'Freigabe meint die Fassung des Mediums, nicht die Website und keinen Zugriff. Materialart und Einordnung sind die redaktionelle Klassifikation; Verwendung zeigt, wo das Medium tatsächlich eingebunden ist. Deaktivierte und archivierte Medien bleiben über „Weitere Filter“ auffindbar.',
|
||||
'zeilen' => array_map($this->zeile(...), $this->cards()),
|
||||
'einheit' => ['Medium', 'Medien'],
|
||||
'leer' => ['titel' => 'Noch keine Medien', 'text' => 'Mit „Medium anlegen“ oben lädst du eine Datei hoch oder schreibst einen Text.'],
|
||||
@@ -224,19 +212,13 @@ public function bestand(): array
|
||||
*/
|
||||
private function zeile(array $card): array
|
||||
{
|
||||
$chips = [['label' => $card['presentation'] ? 'Präsentationsmedium, ohne Inhaltsfassung' : $card['stand'], 'ton' => match ($card['standTone']) {
|
||||
$chips = [['label' => $card['stand'], 'ton' => match ($card['standTone']) {
|
||||
'ready' => 'gut',
|
||||
'draft' => 'offen',
|
||||
'blocked' => 'achtung',
|
||||
default => 'leise',
|
||||
}]];
|
||||
|
||||
if ($card['websiteReleased']) {
|
||||
$chips[] = ['label' => 'Für die Website freigegeben', 'ton' => 'gut'];
|
||||
} elseif ($card['presentation']) {
|
||||
$chips[] = ['label' => 'Nicht für die Website freigegeben', 'ton' => 'offen'];
|
||||
}
|
||||
|
||||
foreach ([['draftNote', 'offen'], ['blockedNote', 'achtung'], ['processing', 'offen'], ['versionLabel', 'leise']] as [$feld, $ton]) {
|
||||
if (filled($card[$feld] ?? null)) {
|
||||
$chips[] = ['label' => (string) $card[$feld], 'ton' => $ton];
|
||||
@@ -284,7 +266,6 @@ private function libraryFilters(): array
|
||||
'suche' => $this->suche,
|
||||
'art' => $this->art,
|
||||
'freigabe' => $this->freigabe,
|
||||
'schutz' => $this->schutz,
|
||||
'entwurf' => $this->entwurf,
|
||||
'fassung' => $this->fassung,
|
||||
'nutzung' => $this->nutzung,
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Domain\Cms\WebsiteImageUsage;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Media\PresentationFile;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
use App\Domain\Media\WebsiteRelease;
|
||||
@@ -38,7 +37,6 @@
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||
use Livewire\WithFileUploads;
|
||||
|
||||
@@ -94,9 +92,6 @@ class ViewContentElement extends ViewRecord
|
||||
|
||||
public string $websiteFeedback = '';
|
||||
|
||||
/** Gewählte Website-Datei für Film oder Hörstück (ungeschützt, getrennt von der Inhaltsfassung). */
|
||||
public mixed $websiteUpload = null;
|
||||
|
||||
public int|string|null $kindId = null;
|
||||
|
||||
/** @var list<int|string> */
|
||||
@@ -267,9 +262,8 @@ public function adoptFrame(): void
|
||||
/** @var ContentElement $element */
|
||||
$element = $this->getRecord();
|
||||
$shown = $this->shownVersion();
|
||||
$fromWebsiteFile = ! $shown instanceof ContentElementVersion && $this->hasWebsiteFilm($element);
|
||||
|
||||
if ((! $shown instanceof ContentElementVersion && ! $fromWebsiteFile) || $element->output_class !== 'film') {
|
||||
if (! $shown instanceof ContentElementVersion || $element->output_class !== 'film') {
|
||||
$this->pictureFeedback = 'Für dieses Medium gibt es keine Filmstelle.';
|
||||
|
||||
return;
|
||||
@@ -292,9 +286,7 @@ public function adoptFrame(): void
|
||||
$this->keepAlt($element);
|
||||
$element->thumbnail_error = null;
|
||||
$element->save();
|
||||
$fromWebsiteFile
|
||||
? DeriveThumbnail::dispatch('element', $element->id, null, null, null, $seconds, true)
|
||||
: DeriveThumbnail::dispatch('element', $element->id, null, null, $shown->id, $seconds);
|
||||
DeriveThumbnail::dispatch('element', $element->id, null, null, $shown->id, $seconds);
|
||||
$element->refresh();
|
||||
$this->pictureFeedback = $element->thumbnail_error
|
||||
?: 'Das Vorschaubild ist gespeichert. Die Fassung bleibt unverändert.';
|
||||
@@ -369,24 +361,10 @@ public function useOwnImage(): void
|
||||
?: 'Das Vorschaubild ist gespeichert. Die Fassung bleibt unverändert.';
|
||||
}
|
||||
|
||||
/** Ein Film ohne Inhaltsfassung, aber mit Website-Datei: die Filmstelle kommt aus dieser Datei. */
|
||||
public function hasWebsiteFilm(?ContentElement $element = null): bool
|
||||
{
|
||||
$element ??= $this->getRecord();
|
||||
|
||||
return $element->output_class === 'film'
|
||||
&& filled($element->preview_path)
|
||||
&& ! $element->versions()->exists();
|
||||
}
|
||||
|
||||
public function framePreviewUrl(): ?string
|
||||
{
|
||||
$shown = $this->shownVersion();
|
||||
|
||||
if (! $shown instanceof ContentElementVersion && $this->hasWebsiteFilm() && is_numeric($this->frameSecond) && trim($this->frameSecond) !== '') {
|
||||
return route('content.website-frame', ['element' => $this->getRecord(), 'sekunde' => $this->frameSecond]);
|
||||
}
|
||||
|
||||
if (! $shown instanceof ContentElementVersion || ! is_numeric($this->frameSecond) || trim($this->frameSecond) === '') {
|
||||
return null;
|
||||
}
|
||||
@@ -866,61 +844,6 @@ public function releaseForWebsite(): void
|
||||
$element->refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt die Datei ab, die auf der Website laufen soll (zum Beispiel ein Trailer). Die geschützte Inhaltsfassung
|
||||
* bleibt unberührt; öffentlich wird die Datei erst mit der Website-Freigabe.
|
||||
*/
|
||||
public function storeWebsiteFile(): void
|
||||
{
|
||||
abort_unless(ContentElementResource::editor(), 403);
|
||||
|
||||
/** @var ContentElement $element */
|
||||
$element = $this->getRecord();
|
||||
|
||||
if (! in_array($element->output_class, ['film', 'audio'], true)) {
|
||||
$this->websiteFeedback = 'Eine Website-Datei gibt es nur für Filme und Hörstücke.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $this->websiteUpload instanceof TemporaryUploadedFile) {
|
||||
$this->websiteFeedback = 'Wähle zuerst eine Datei.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$files = app(PresentationFile::class);
|
||||
$extension = strtolower($this->websiteUpload->getClientOriginalExtension());
|
||||
|
||||
if (! in_array($extension, PresentationFile::EXTENSIONS[$element->output_class], true)) {
|
||||
$this->websiteFeedback = 'Für die Website geht nur '.$files->formats($element->output_class).'. Eine .'.$extension.'-Datei kann der Browser nicht direkt abspielen.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$path = $this->websiteUpload->storeAs('inhalte', 'web-'.bin2hex(random_bytes(6)).'.'.$extension, 'cms_incoming');
|
||||
$this->websiteUpload = null;
|
||||
|
||||
if (! is_string($path)) {
|
||||
$this->websiteFeedback = 'Die Datei wurde nicht übernommen.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$files->store($element, $path);
|
||||
} catch (DomainRuleException $e) {
|
||||
$this->websiteFeedback = $e->getMessage();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$element->refresh();
|
||||
$this->websiteFeedback = filled($element->thumbnail_error)
|
||||
? (string) $element->thumbnail_error
|
||||
: 'Die Website-Datei ist übernommen. Sie ist erst nach „Für die Website freigeben“ öffentlich. Ein bereits freigegebenes Medium zeigt danach die neue Datei.';
|
||||
}
|
||||
|
||||
public function withdrawWebsite(): void
|
||||
{
|
||||
abort_unless(ContentElementResource::editor(), 403);
|
||||
@@ -1047,20 +970,18 @@ public function previewHtml(): string
|
||||
if ($this->previewSurface === 'bibliothek') {
|
||||
$title = trim($this->displayTitle) !== '' ? trim($this->displayTitle) : trim($this->workingTitle);
|
||||
|
||||
// Dieselbe Karte wie im Mitgliederbereich (<x-member.card>), ohne Verfügbarkeit: Die entscheidet die Lizenz.
|
||||
return Blade::render('<x-member.card :card="$card" />', [
|
||||
return view('member.partials.card', [
|
||||
'href' => '#vorschau',
|
||||
'card' => [
|
||||
'type' => $element->output_class === 'film' ? 'film' : 'material',
|
||||
'url' => '#vorschau',
|
||||
'title' => $title !== '' ? $title : $element->working_title,
|
||||
'summary' => trim($this->summary) !== '' ? trim($this->summary) : null,
|
||||
'kind' => PublicMaterialReader::outputLabel((string) $element->output_class),
|
||||
'hide_status' => true,
|
||||
'coverage' => 'offen',
|
||||
'image' => trim($this->thumbnailAlt) !== '' ? trim($this->thumbnailAlt) : $title,
|
||||
'image_url' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
|
||||
'error' => 'Vorschau der Kartenform. Ob jemand sie öffnen darf, entscheidet die Lizenz.',
|
||||
],
|
||||
]);
|
||||
])->render();
|
||||
}
|
||||
|
||||
$subject = app(PublicMaterialReader::class)->subject($element->id, true, $draft);
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\DiscountCodes;
|
||||
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Filament\Resources\DiscountCodes\Pages\ListDiscountCodes;
|
||||
use App\Filament\Resources\DiscountCodes\Pages\ViewDiscountCode;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Auth\Access\Response;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Rabattcodes (FACH-14): anlegen, bearbeiten, zeitlich begrenzen, deaktivieren und einzelne Konten freischalten.
|
||||
* Die Seiten nutzen die gemeinsamen Bausteine (Bestandsliste, Objektseite, Dialoge) wie die übrigen Kataloglisten.
|
||||
*/
|
||||
class DiscountCodeResource extends Resource
|
||||
{
|
||||
protected static ?string $model = DiscountCode::class;
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||
|
||||
protected static ?string $navigationLabel = 'Rabattcodes';
|
||||
|
||||
protected static ?string $modelLabel = 'Rabattcode';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Rabattcodes';
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'code';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
return ShopAccess::allowed();
|
||||
}
|
||||
|
||||
public static function getViewAuthorizationResponse(Model $record): Response
|
||||
{
|
||||
return ShopAccess::allowed() ? Response::allow() : Response::deny();
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema;
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table->columns([
|
||||
TextColumn::make('code')->label('Code')->searchable(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListDiscountCodes::route('/'),
|
||||
'view' => ViewDiscountCode::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\DiscountCodes\Pages;
|
||||
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Discount\DiscountService;
|
||||
use App\Filament\Resources\DiscountCodes\DiscountCodeResource;
|
||||
use App\Filament\Support\DiscountCodeForm;
|
||||
use App\Filament\Support\ListsCatalog;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
class ListDiscountCodes extends ListRecords
|
||||
{
|
||||
use ListsCatalog;
|
||||
use ReportsDomainRules;
|
||||
|
||||
protected static string $resource = DiscountCodeResource::class;
|
||||
|
||||
public function getSubheading(): string|Htmlable|null
|
||||
{
|
||||
return 'Ein Code gilt für den ganzen Warenkorb oder nur für ausgewählte Ziele, und er ist allgemein einlösbar oder nur für freigeschaltete Konten. Beides stellst du unabhängig voneinander ein. Pro Bestellung gilt höchstens ein Code.';
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('create')->label('Code anlegen')
|
||||
->modalHeading('Neuer Rabattcode')
|
||||
->modalDescription('Dieselbe Maske öffnet sich später beim Bearbeiten. Freigaben für einzelne Konten verwaltest du danach auf der Seite des Codes.')
|
||||
->modalSubmitActionLabel('Code anlegen')
|
||||
->modalWidth('3xl')
|
||||
->fillForm(['kind' => DiscountCode::PERCENT, 'scope' => DiscountCode::SCOPE_CART, 'eligibility' => DiscountCode::OPEN, 'active' => true])
|
||||
->schema(DiscountCodeForm::schema())
|
||||
->action(function (array $data): void {
|
||||
$code = null;
|
||||
$this->report(function () use ($data, &$code): void {
|
||||
[$fields, $targets] = DiscountCodeForm::fromForm($data);
|
||||
$code = app(DiscountService::class)->save($fields, $targets);
|
||||
}, 'Der Rabattcode ist angelegt.');
|
||||
|
||||
if ($code instanceof DiscountCode) {
|
||||
$this->redirect(DiscountCodeResource::getUrl('view', ['record' => $code]));
|
||||
}
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
protected function catalogRows(): array
|
||||
{
|
||||
$rows = [];
|
||||
$now = now();
|
||||
|
||||
foreach (DiscountCode::query()->with('targets')->withCount(['releases as active_releases_count' => fn ($query) => $query->whereNull('revoked_at')])->orderByDesc('id')->get() as $code) {
|
||||
$state = $code->stateAt($now);
|
||||
$url = DiscountCodeResource::getUrl('view', ['record' => $code]);
|
||||
$rows[] = [
|
||||
'schluessel' => 'c'.$code->id,
|
||||
'titel' => $code->code,
|
||||
'meta' => 'Rabattcode · '.$code->label,
|
||||
'text' => $code->valueLabel().' · '.($code->forSelection() ? 'ausgewählte Ziele ('.$code->targets->count().')' : 'gesamter Warenkorb').' · '.($code->restricted() ? 'nur freigeschaltete Konten' : 'allgemein einlösbar'),
|
||||
'symbol' => 'etikett',
|
||||
'url' => $url,
|
||||
'chips' => [
|
||||
match ($state) {
|
||||
'aktiv' => ['label' => 'Gültig', 'ton' => 'gut'],
|
||||
'abgelaufen' => ['label' => 'Abgelaufen', 'ton' => 'leise'],
|
||||
'noch_nicht' => ['label' => 'Noch nicht gültig', 'ton' => 'offen'],
|
||||
default => ['label' => 'Deaktiviert', 'ton' => 'leise'],
|
||||
},
|
||||
['label' => $code->valueLabel(), 'ton' => 'neutral'],
|
||||
['label' => $code->restricted() ? $code->active_releases_count.' freigeschaltet' : 'Allgemein', 'ton' => 'neutral'],
|
||||
],
|
||||
'zustand' => [$state === 'aktiv' ? 'aktiv' : 'inaktiv'],
|
||||
'aktionen' => [['label' => 'Öffnen', 'href' => $url]],
|
||||
];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
protected function zustandOptionen(): array
|
||||
{
|
||||
return ['alle' => 'Jeder Zustand', 'aktiv' => 'Gerade gültig', 'inaktiv' => 'Abgelaufen, deaktiviert oder noch nicht gültig'];
|
||||
}
|
||||
|
||||
protected function suchPlatzhalter(): string
|
||||
{
|
||||
return 'Code oder Name';
|
||||
}
|
||||
|
||||
protected function einheit(): array
|
||||
{
|
||||
return ['Rabattcode', 'Rabattcodes'];
|
||||
}
|
||||
|
||||
protected function leer(): array
|
||||
{
|
||||
return ['titel' => 'Noch keine Rabattcodes', 'text' => 'Mit „Code anlegen“ oben entsteht der erste Rabattcode, zum Beispiel der gemeinsame Zertifizierungscode.'];
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\DiscountCodes\Pages;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Discount\DiscountRelease;
|
||||
use App\Domain\Commerce\Discount\DiscountService;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Filament\Resources\DiscountCodes\DiscountCodeResource;
|
||||
use App\Filament\Support\DiscountCodeForm;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use App\Models\User;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\View;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Rabattcode im gemeinsamen Rahmen. Bearbeiten nutzt dieselbe Maske wie Anlegen. Konten werden für genau diesen Code
|
||||
* freigeschaltet und die Freigabe wird mit Begründung entzogen; der Verlauf bleibt stehen.
|
||||
*/
|
||||
class ViewDiscountCode extends ViewRecord
|
||||
{
|
||||
use ReportsDomainRules;
|
||||
|
||||
protected static string $resource = DiscountCodeResource::class;
|
||||
|
||||
public function getTitle(): string|Htmlable
|
||||
{
|
||||
return (string) $this->getRecord()->code;
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function getBreadcrumbs(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function infolist(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
View::make('filament.catalog.objekt')->viewData(fn (): array => $this->codeDaten())->columnSpanFull(),
|
||||
])->columns(1);
|
||||
}
|
||||
|
||||
private function code(): DiscountCode
|
||||
{
|
||||
/** @var DiscountCode $code */
|
||||
$code = $this->getRecord();
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
public function editAction(): Action
|
||||
{
|
||||
return Action::make('edit')
|
||||
->label('Code bearbeiten')
|
||||
->modalHeading(fn (): string => 'Rabattcode „'.$this->code()->code.'“ bearbeiten')
|
||||
->modalDescription('Bestellungen, die schon aufgegeben sind, behalten ihren gespeicherten Rabatt. Eine Änderung wirkt auf künftige Einlösungen und auf offene Warenkörbe. „Abbrechen“ verwirft die Eingaben.')
|
||||
->modalSubmitActionLabel('Änderungen speichern')
|
||||
->modalWidth('3xl')
|
||||
->fillForm(fn (): array => DiscountCodeForm::fill($this->code()))
|
||||
->schema(DiscountCodeForm::schema())
|
||||
->action(function (array $data): void {
|
||||
$this->report(function () use ($data): void {
|
||||
[$fields, $targets] = DiscountCodeForm::fromForm($data);
|
||||
app(DiscountService::class)->save($fields, $targets, $this->code());
|
||||
}, 'Der Rabattcode ist gespeichert.');
|
||||
$this->refreshRecord();
|
||||
});
|
||||
}
|
||||
|
||||
public function toggleAction(): Action
|
||||
{
|
||||
return Action::make('toggle')
|
||||
->label(fn (): string => $this->code()->active ? 'Code deaktivieren' : 'Code aktivieren')
|
||||
->color(fn (): string => $this->code()->active ? 'danger' : 'success')
|
||||
->requiresConfirmation()
|
||||
->modalHeading(fn (): string => $this->code()->active ? 'Code „'.$this->code()->code.'“ deaktivieren?' : 'Code „'.$this->code()->code.'“ aktivieren?')
|
||||
->modalDescription(fn (): string => $this->code()->active
|
||||
? 'Der Code lässt sich danach nicht mehr einlösen. In offenen Warenkörben zeigt die Bestellübersicht den Grund; bereits aufgegebene Bestellungen bleiben unverändert. Freigaben und Einstellungen bleiben erhalten.'
|
||||
: 'Der Code lässt sich danach wieder einlösen, soweit sein Gültigkeitszeitraum und die Freigaben es zulassen.')
|
||||
->modalSubmitActionLabel(fn (): string => $this->code()->active ? 'Deaktivieren' : 'Aktivieren')
|
||||
->action(function (): void {
|
||||
$code = $this->code();
|
||||
$this->report(function () use ($code): string {
|
||||
app(DiscountService::class)->setActive($code, ! $code->active);
|
||||
|
||||
return $code->active ? 'Der Code ist aktiviert.' : 'Der Code ist deaktiviert.';
|
||||
}, 'Gespeichert.');
|
||||
$this->refreshRecord();
|
||||
});
|
||||
}
|
||||
|
||||
public function releaseAction(): Action
|
||||
{
|
||||
return Action::make('release')
|
||||
->label('Konto freischalten')
|
||||
->modalHeading(fn (): string => 'Konto für den Code „'.$this->code()->code.'“ freischalten')
|
||||
->modalDescription('Das Konto darf genau diesen Code einlösen, solange Code und Freigabe gültig sind, auch bei späteren Bestellungen. Die Freigabe gilt nicht für andere Codes. Prüfe vorher die Zertifizierung des Kontos.')
|
||||
->modalSubmitActionLabel('Konto freischalten')
|
||||
->schema([
|
||||
Select::make('user_id')->label('Mitgliedskonto')->required()->searchable()
|
||||
->getSearchResultsUsing(fn (string $search): array => $this->searchMembers($search))
|
||||
->getOptionLabelUsing(fn ($value): ?string => ($user = User::query()->find($value)) === null ? null : $user->name.' ('.$user->email.')')
|
||||
->helperText('Suche nach Name oder E-Mail-Adresse. Nur Konten mit Mitgliedsprofil.'),
|
||||
DatePicker::make('valid_until')->label('Freigabe gültig bis einschließlich')->native(false)->displayFormat('d.m.Y')
|
||||
->helperText('Leer: ohne Ende. Danach gilt der Code für dieses Konto nicht mehr.'),
|
||||
Textarea::make('reason')->label('Grundlage der Freigabe')->rows(2)->maxLength(500)
|
||||
->helperText('Zum Beispiel „Zertifikat vom 12.11.2026 geprüft“. Bleibt im Verlauf stehen.'),
|
||||
])
|
||||
->visible(fn (): bool => $this->code()->restricted())
|
||||
->action(function (array $data): void {
|
||||
$this->report(function () use ($data): string {
|
||||
$member = User::query()->findOrFail($data['user_id']);
|
||||
$until = filled($data['valid_until'] ?? null) ? Carbon::parse((string) $data['valid_until'], config('app.timezone'))->endOfDay() : null;
|
||||
app(DiscountService::class)->release($this->code(), $member, auth('staff')->user() ?? auth()->user(), $until, $data['reason'] ?? null);
|
||||
|
||||
return 'Das Konto von '.$member->name.' ist für den Code freigeschaltet.';
|
||||
}, 'Das Konto ist freigeschaltet.');
|
||||
$this->refreshRecord();
|
||||
});
|
||||
}
|
||||
|
||||
public function revokeAction(): Action
|
||||
{
|
||||
return Action::make('revoke')
|
||||
->label('Freigabe entziehen')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Freigabe entziehen?')
|
||||
->modalDescription('Das Konto kann diesen Code danach nicht mehr einlösen. Offene Warenkörbe des Kontos zeigen den Grund und lassen sich erst ohne Code bestellen. Aufgegebene Bestellungen bleiben unverändert; die Freigabe bleibt mit dem Entzug im Verlauf stehen.')
|
||||
->modalSubmitActionLabel('Freigabe entziehen')
|
||||
->schema([
|
||||
Textarea::make('reason')->label('Grund')->rows(2)->maxLength(500),
|
||||
])
|
||||
->action(function (array $data, array $arguments): void {
|
||||
$this->report(function () use ($data, $arguments): string {
|
||||
$release = DiscountRelease::query()->where('discount_code_id', $this->code()->id)->findOrFail((int) ($arguments['release'] ?? 0));
|
||||
app(DiscountService::class)->revoke($release, auth('staff')->user() ?? auth()->user(), $data['reason'] ?? null);
|
||||
|
||||
return 'Die Freigabe ist entzogen.';
|
||||
}, 'Die Freigabe ist entzogen.');
|
||||
$this->refreshRecord();
|
||||
});
|
||||
}
|
||||
|
||||
private function refreshRecord(): void
|
||||
{
|
||||
$this->getRecord()->unsetRelations();
|
||||
$this->getRecord()->refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function searchMembers(string $search): array
|
||||
{
|
||||
$like = '%'.mb_strtolower(trim($search)).'%';
|
||||
|
||||
return User::query()
|
||||
->whereNotNull('party_id')
|
||||
->where(fn ($query) => $query->whereRaw('LOWER(name) LIKE ?', [$like])->orWhereRaw('LOWER(email) LIKE ?', [$like]))
|
||||
->orderBy('name')
|
||||
->limit(20)
|
||||
->get()
|
||||
->mapWithKeys(fn (User $user): array => [$user->id => $user->name.' ('.$user->email.')'])
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function codeDaten(): array
|
||||
{
|
||||
$code = $this->code();
|
||||
$code->loadMissing('targets');
|
||||
$state = $code->stateAt(now());
|
||||
$date = fn (?Carbon $value): string => $value === null ? '' : $value->timezone(config('app.timezone'))->format('d.m.Y');
|
||||
$targets = [];
|
||||
|
||||
foreach ($code->targets as $target) {
|
||||
$targets[] = match ($target->target_type) {
|
||||
DiscountCode::TARGET_OFFER => 'Angebot „'.(Offer::query()->find($target->target_id)?->name ?? 'gelöscht').'“',
|
||||
DiscountCode::TARGET_ARTICLE => 'Lizenzartikel '.(LicenseArticle::query()->find($target->target_id)?->code ?? 'gelöscht'),
|
||||
DiscountCode::TARGET_BUNDLE => 'Paket „'.(Bundle::query()->find($target->target_id)?->name ?? 'gelöscht').'“',
|
||||
default => 'Ziel',
|
||||
};
|
||||
}
|
||||
|
||||
$releases = $code->releases()->with(['user', 'grantor'])->get();
|
||||
$active = $releases->filter(fn (DiscountRelease $release): bool => $release->revoked_at === null);
|
||||
$past = $releases->filter(fn (DiscountRelease $release): bool => $release->revoked_at !== null);
|
||||
$orders = Order::query()->where('discount_code_id', $code->id)->with('user')->latest('id')->limit(10)->get();
|
||||
$paid = Order::query()->where('discount_code_id', $code->id)->where('status', 'bezahlt')->count();
|
||||
|
||||
return [
|
||||
'kopf' => [
|
||||
'brot' => [['label' => 'Rabattcodes', 'href' => DiscountCodeResource::getUrl('index')], $code->code],
|
||||
'titel' => $code->code,
|
||||
'typ' => 'Rabattcode · '.$code->label,
|
||||
'status' => match ($state) {
|
||||
'aktiv' => ['text' => 'Gerade gültig'.($code->valid_until ? ' bis einschließlich '.$date($code->valid_until) : ''), 'ton' => 'gut'],
|
||||
'abgelaufen' => ['text' => 'Abgelaufen am '.$date($code->valid_until).'. Der Code lässt sich nicht mehr einlösen.', 'ton' => 'offen'],
|
||||
'noch_nicht' => ['text' => 'Gilt erst ab dem '.$date($code->valid_from).'.', 'ton' => 'offen'],
|
||||
default => ['text' => 'Deaktiviert. Der Code lässt sich nicht einlösen.', 'ton' => 'offen'],
|
||||
},
|
||||
'aktionen' => [
|
||||
['label' => 'Code bearbeiten', 'wire' => "mountAction('edit')", 'art' => 'primary'],
|
||||
...($code->restricted() ? [['label' => 'Konto freischalten', 'wire' => "mountAction('release')", 'art' => 'line']] : []),
|
||||
['label' => $code->active ? 'Code deaktivieren' : 'Code aktivieren', 'wire' => "mountAction('toggle')", 'art' => 'line'],
|
||||
],
|
||||
],
|
||||
'haupt' => [
|
||||
[
|
||||
'titel' => 'Der Code auf einen Blick',
|
||||
'hilfe' => 'Geltungsbereich und Einlösungsberechtigung sind zwei getrennte Einstellungen. Der Rabatt ändert den Preis, nie den Nutzungsumfang.',
|
||||
'zeilen' => [
|
||||
['text' => 'Rabatt: '.$code->valueLabel(), 'neben' => $code->kind === DiscountCode::PERCENT ? 'Je Position gerundet.' : 'Je Bestellung, anteilig auf die betroffenen Positionen verteilt.'],
|
||||
['text' => 'Geltungsbereich: '.($code->forSelection() ? 'nur ausgewählte Ziele' : 'gesamter Warenkorb'), 'neben' => $code->forSelection() ? 'Ein Paket ist ein eigenes Ziel und folgt nicht aus einem enthaltenen Artikel.' : null],
|
||||
...array_map(fn (string $target): array => ['text' => '· '.$target, 'neben' => null], $targets),
|
||||
['text' => 'Einlösung: '.($code->restricted() ? 'nur freigeschaltete Konten' : 'allgemein, für alle angemeldeten Käufer'), 'neben' => 'Pro Bestellung gilt höchstens ein Code.'],
|
||||
['text' => 'Gültigkeit: '.($code->valid_from ? 'ab '.$date($code->valid_from) : 'sofort').($code->valid_until ? ' bis einschließlich '.$date($code->valid_until) : ', unbegrenzt'), 'neben' => $code->active ? 'Aktiv' : 'Deaktiviert'],
|
||||
...(filled($code->note) ? [['text' => 'Notiz: '.$code->note, 'neben' => null]] : []),
|
||||
],
|
||||
],
|
||||
[
|
||||
'titel' => $code->restricted() ? 'Freigeschaltete Konten' : 'Freigaben',
|
||||
'zusatz' => $code->restricted() ? $active->count().' aktiv' : null,
|
||||
'hilfe' => $code->restricted()
|
||||
? 'Nur diese Konten können den Code einlösen. Die Freigabe gilt nur für diesen Code und wiederholt, solange Code und Freigabe gültig sind.'
|
||||
: 'Der Code ist allgemein einlösbar. Freigaben sind nicht nötig. Stelle „Einlösung“ auf freigeschaltete Konten, um den Code zu beschränken.',
|
||||
'zeilen' => $code->restricted() ? $active->map(fn (DiscountRelease $release): array => [
|
||||
'text' => ($release->user?->name ?? 'Konto').' ('.($release->user?->email ?? '').')',
|
||||
'neben' => 'freigeschaltet am '.$date($release->granted_at).($release->grantor ? ' von '.$release->grantor->name : '').($release->valid_until ? ', gültig bis einschließlich '.$date($release->valid_until) : '').(filled($release->reason) ? ' · '.$release->reason : ''),
|
||||
'aktion' => ['label' => 'Entziehen', 'wire' => "mountAction('revoke', { release: ".$release->id.' })'],
|
||||
])->values()->all() : [],
|
||||
'leer' => ['titel' => $code->restricted() ? 'Noch kein Konto freigeschaltet' : 'Keine Freigaben nötig', 'text' => $code->restricted() ? 'Mit „Konto freischalten“ oben gibst du ein Konto für diesen Code frei, zum Beispiel nach der Prüfung eines Zertifikats.' : 'Jeder angemeldete Käufer kann den Code einlösen.'],
|
||||
],
|
||||
],
|
||||
'seite' => [
|
||||
[
|
||||
'titel' => 'Verwendung',
|
||||
'zeilen' => $orders->map(fn (Order $order): array => [
|
||||
'text' => 'Bestellung '.$order->id.' · −'.Money::format((int) $order->discount_cents),
|
||||
'zustand' => ['label' => match ($order->status) {
|
||||
'bezahlt' => 'Bezahlt', 'erstattet' => 'Erstattet', 'fehlgeschlagen' => 'Fehlgeschlagen', default => 'Offen'
|
||||
}, 'ton' => $order->status === 'bezahlt' ? 'gut' : 'leise'],
|
||||
'neben' => ($order->user?->name ?? '').' · '.$date($order->created_at),
|
||||
])->all(),
|
||||
'leer' => 'Der Code wurde noch in keiner Bestellung verwendet.',
|
||||
'hilfe' => $orders->isEmpty() ? null : $paid.' bezahlte Bestellung'.($paid === 1 ? '' : 'en').' mit diesem Code. Gezeigt werden die letzten zehn.',
|
||||
],
|
||||
[
|
||||
'titel' => 'Entzogene Freigaben',
|
||||
'zeilen' => $past->map(fn (DiscountRelease $release): array => [
|
||||
'text' => ($release->user?->name ?? 'Konto'),
|
||||
'neben' => 'entzogen am '.$date($release->revoked_at).(filled($release->reason) ? ' · '.$release->reason : ''),
|
||||
])->values()->all(),
|
||||
'leer' => 'Keine Freigabe wurde entzogen.',
|
||||
'hilfe' => 'Der Verlauf bleibt erhalten.',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@
|
||||
use App\Filament\Resources\LicenseArticles\Pages\ListLicenseArticles;
|
||||
use App\Filament\Resources\LicenseArticles\Pages\ViewLicenseArticle;
|
||||
use App\Filament\Support\CatalogReading;
|
||||
use App\Filament\Support\PublicationReadiness;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Resources\Resource;
|
||||
@@ -58,7 +57,6 @@ public static function infolist(Schema $schema): Schema
|
||||
->viewData(fn (LicenseArticle $record): array => [
|
||||
'stand' => app(CatalogReading::class)->articleStand($record),
|
||||
'kontext' => app(CatalogReading::class)->articleContext($record),
|
||||
'voraussetzungen' => app(PublicationReadiness::class)->forArticle($record),
|
||||
])
|
||||
->columnSpanFull(),
|
||||
]);
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Resources\LicenseArticles\LicenseArticleResource;
|
||||
use App\Filament\Support\AssignsPillars;
|
||||
use App\Filament\Support\CatalogOptions;
|
||||
use App\Filament\Support\EditorialCatalog;
|
||||
use App\Filament\Support\ManagesEditorialSurface;
|
||||
@@ -31,7 +30,6 @@
|
||||
|
||||
class ViewLicenseArticle extends ViewRecord
|
||||
{
|
||||
use AssignsPillars;
|
||||
use ManagesEditorialSurface;
|
||||
use ReportsDomainRules;
|
||||
|
||||
@@ -117,7 +115,6 @@ protected function saveRedaktionTexte(): bool
|
||||
], auth()->user());
|
||||
|
||||
app(IdentityDimension::class)->replaceOffered($article, array_map(intval(...), $this->dimensionIds));
|
||||
$this->persistPillarIds($article);
|
||||
|
||||
$article->refresh();
|
||||
$this->fillLicenseEditorial();
|
||||
@@ -162,7 +159,7 @@ public function einordnungUnsaved(): bool
|
||||
sort($stored);
|
||||
sort($current);
|
||||
|
||||
return $stored !== $current || $this->pillarsUnsaved($article);
|
||||
return $stored !== $current;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -273,15 +270,11 @@ public function einordnungArt(): array
|
||||
*/
|
||||
public function einordnungGruppen(): array
|
||||
{
|
||||
$groups = array_map(fn (array $group): array => [
|
||||
return array_map(fn (array $group): array => [
|
||||
'legend' => $group['label'],
|
||||
'model' => 'dimensionIds',
|
||||
'values' => $group['values'],
|
||||
], $this->licenseDimensionGroups());
|
||||
|
||||
$pillars = $this->pillarGroup();
|
||||
|
||||
return $pillars === null ? $groups : [$pillars, ...$groups];
|
||||
}
|
||||
|
||||
private function sourceTitle(Model $source): string
|
||||
@@ -319,7 +312,6 @@ private function fillLicenseEditorial(): void
|
||||
->where('origin', 'direkt')
|
||||
->pluck('editorial_dimension_value_id')
|
||||
->all();
|
||||
$this->loadPillarIds($article);
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
@@ -330,28 +322,12 @@ protected function getHeaderActions(): array
|
||||
public function releaseAction(): Action
|
||||
{
|
||||
return Action::make('release')
|
||||
->label(fn (): string => $this->isFirstStand() ? 'Inhalt festlegen' : 'Neuen Stand veröffentlichen')
|
||||
->modalHeading(fn (): string => $this->isFirstStand() ? 'Inhalt festlegen: ersten Stand veröffentlichen' : 'Neuen Stand veröffentlichen')
|
||||
->modalDescription(fn (): string => $this->isFirstStand()
|
||||
? 'Der Stand legt fest, welche Inhalte dieser Lizenzartikel lizenziert: der gewählte Inhalt samt allem, was er enthält. Er ist danach unveränderlich. Pakete und Angebote können den Artikel danach verwenden; verkauft wird er erst über ein Angebot.'
|
||||
: 'Ein neuer Stand ersetzt den aktuellen für künftige Ausgaben. Bestehende Käufer erhalten ihn im Rahmen ihrer Lizenz; frühere Stände bleiben gespeichert.')
|
||||
->modalSubmitActionLabel('Stand veröffentlichen')
|
||||
->fillForm(fn (): array => $this->isFirstStand() ? ['classification' => 'Erster Stand dieses Lizenzartikels.'] : [])
|
||||
->label('Stand veröffentlichen')
|
||||
->schema([
|
||||
Select::make('root')->label('Freigegebener Inhalt')
|
||||
->options(fn (): array => CatalogOptions::assignmentTargets())
|
||||
->searchable()
|
||||
->required()
|
||||
->helperText(fn (): string => CatalogOptions::assignmentTargets() === []
|
||||
? 'Es gibt noch keinen freigegebenen Inhalt. Gib zuerst ein Medium, Modul oder Programm frei.'
|
||||
: 'Medien, Module und Programme mit freigegebener Fassung. Bei Modulen und Programmen gehört alles Enthaltene zum Stand.'),
|
||||
Textarea::make('classification')->label('Einordnung')
|
||||
->required(fn (): bool => ! $this->isFirstStand())
|
||||
->helperText(fn (): string => $this->isFirstStand()
|
||||
? 'Beim ersten Stand genügt der vorgegebene Text.'
|
||||
: 'Warum dies derselbe Lizenzartikel bleibt und kein neues Produkt ist.'),
|
||||
TextInput::make('change_note')->label('Änderungshinweis')
|
||||
->visible(fn (): bool => ! $this->isFirstStand()),
|
||||
Select::make('root')->label('Wurzel')->options(fn (): array => CatalogOptions::readyTargets())->required(),
|
||||
Textarea::make('classification')->label('Einordnung')->required()
|
||||
->helperText('Warum dies derselbe Lizenzartikel bleibt und kein neues Produkt ist.'),
|
||||
TextInput::make('change_note')->label('Änderungshinweis'),
|
||||
])
|
||||
->action(function (array $data): void {
|
||||
$this->report(function () use ($data): string {
|
||||
@@ -364,7 +340,7 @@ public function releaseAction(): Action
|
||||
$release = app(ArticleService::class)->publishRelease(
|
||||
$article,
|
||||
$root,
|
||||
(string) ($data['classification'] ?? 'Erster Stand dieses Lizenzartikels.'),
|
||||
$data['classification'],
|
||||
$data['change_note'] ?? null,
|
||||
);
|
||||
$report = $release->impact_report ?? [];
|
||||
@@ -399,11 +375,6 @@ public function withdrawAction(): Action
|
||||
});
|
||||
}
|
||||
|
||||
private function isFirstStand(): bool
|
||||
{
|
||||
return ! $this->getRecord()->releases()->exists();
|
||||
}
|
||||
|
||||
private function refreshRecord(): void
|
||||
{
|
||||
$this->getRecord()->unsetRelations();
|
||||
|
||||
@@ -64,7 +64,6 @@ protected function catalogRows(): array
|
||||
if ($active !== null) {
|
||||
$chips[] = ['label' => 'Fassung '.$active->number.' aktiv', 'ton' => 'gut'];
|
||||
$chips[] = ['label' => CatalogLabels::vergabe($active), 'ton' => 'neutral'];
|
||||
$chips[] = ['label' => $active->holder_kind === 'organisation' ? 'Für Organisationen' : 'Für Privatpersonen', 'ton' => 'neutral'];
|
||||
$zustand[] = 'aktiv';
|
||||
$text = $active->lines->map(fn ($line): string => ($line->article !== null
|
||||
? 'Lizenzartikel '.$line->article->code
|
||||
|
||||
@@ -2,12 +2,8 @@
|
||||
|
||||
namespace App\Filament\Resources\Offers\Pages;
|
||||
|
||||
use App\Domain\Catalog\BundleService;
|
||||
use App\Domain\Catalog\BundleVersion;
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\CompositionVersion;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
@@ -15,16 +11,10 @@
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Catalog\RightsProfileVersion;
|
||||
use App\Domain\Catalog\StatusValue;
|
||||
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;
|
||||
@@ -35,7 +25,6 @@
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Angebot im gemeinsamen Rahmen. Anlegen und Ändern nutzen dieselbe Maske (FACH-20): „Fassung aktivieren“ legt die
|
||||
@@ -48,9 +37,6 @@ class ViewOffer extends ViewRecord
|
||||
|
||||
protected static string $resource = OfferResource::class;
|
||||
|
||||
/** Wert der Auswahl „Produktseite“ für ein Paket mit eigener Seite. */
|
||||
private const OWN_BUNDLE_PAGE = '__paket';
|
||||
|
||||
public function getTitle(): string|Htmlable
|
||||
{
|
||||
return (string) $this->getRecord()->name;
|
||||
@@ -105,44 +91,22 @@ public function activateAction(): Action
|
||||
return Action::make('activate')
|
||||
->label(fn (): string => $this->activeVersion() !== null ? 'Geänderte Fassung aktivieren' : 'Fassung aktivieren')
|
||||
->modalHeading(fn (): string => $this->activeVersion() !== null
|
||||
? 'Option „'.$this->getRecord()->optionName().'“ ändern: Fassung '.$this->nextNumber().' aktivieren'
|
||||
: 'Option „'.$this->getRecord()->optionName().'“: erste Fassung aktivieren')
|
||||
? 'Angebot ändern: Fassung '.$this->nextNumber().' aktivieren'
|
||||
: 'Erste Fassung aktivieren')
|
||||
->modalDescription(fn (): string => ($active = $this->activeVersion()) !== null
|
||||
? 'Betroffen ist nur die Option „'.$this->getRecord()->optionName().'“'.$this->productPageSuffix().'. Die Maske ist mit Fassung '.$active->number.' vorbelegt. Erst „Fassung '.$this->nextNumber().' aktivieren“ schaltet die Änderung öffentlich (auch Bezeichnung und Produktseite, sie erzeugen ebenfalls eine neue Fassung und zeigen offenen Warenkörben „Bedingungen aktualisiert“): Fassung '.$active->number.' wird beendet und bleibt gespeichert, neue Käufe nutzen Fassung '.$this->nextNumber().'. Bereits begründete Berechtigungen und Bestellungen ändern sich nicht. Andere Optionen derselben Produktseite bleiben unverändert kaufbar. „Abbrechen“ verwirft die Eingaben.'
|
||||
: 'Positionen, Vergabe, Eignung und Preis bilden die erste Fassung dieser Option. Erst das Aktivieren macht sie öffentlich; danach ist sie unveränderlich, Änderungen ergeben eine weitere Fassung.')
|
||||
? 'Die Maske ist mit Fassung '.$active->number.' vorbelegt; Inhaberart, Laufzeitregel und Steuerklasse werden übernommen. Beim Aktivieren wird Fassung '.$active->number.' beendet und bleibt unverändert gespeichert; neue Erwerbe nutzen Fassung '.$this->nextNumber().'. Bereits begründete Berechtigungen ändern sich dadurch nicht.'
|
||||
: 'Positionen, Vergabe und Preis bilden die erste Fassung. Nach dem Aktivieren ist sie unveränderlich; Änderungen ergeben eine weitere Fassung.')
|
||||
->modalSubmitActionLabel(fn (): string => 'Fassung '.$this->nextNumber().' aktivieren')
|
||||
->modalWidth('4xl')
|
||||
->fillForm(fn (): array => $this->formFromActive())
|
||||
->schema([
|
||||
TextInput::make('option_label')->label('Bezeichnung der Option')
|
||||
->helperText('So heißt die Option auf der Produktseite, zum Beispiel „Einzellizenz für Privatpersonen“. Sie ist keine bindende Bedingung, wird aber wie die übrigen Angaben erst mit „Fassung aktivieren“ übernommen.')
|
||||
->maxLength(120),
|
||||
Select::make('composition_id')->label('Produktseite')
|
||||
->options(fn (): array => $this->productPages())
|
||||
->searchable()
|
||||
->helperText('Optionen derselben Produktseite sind Alternativen; im Warenkorb liegt nur eine davon. Die Beschreibung der Seite wird zentral an der Komposition gepflegt. Die Zuordnung wird mit „Fassung aktivieren“ übernommen.'),
|
||||
Select::make('holder_kind')->label('Geeignet für')->options([
|
||||
'person' => 'Privatpersonen',
|
||||
'organisation' => 'Organisationen und Vereine',
|
||||
])->required()
|
||||
->helperText('Wähle die Eignung passend zu den Rechten: Organisationslizenzen brauchen institutionelle Rechte. Das System erzwingt diese Kopplung nicht.'),
|
||||
Select::make('licence_scope')->label('Nutzerkreis')
|
||||
->options(LicenceScope::options())
|
||||
->required()
|
||||
->live()
|
||||
->helperText('Wie viele Trainer die Inhalte einsetzen dürfen. Das ist unabhängig vom Lizenzinhaber (Person oder Verein), vom Nutzungszweck der Rechte und vom Preis; es wird aus keinem davon abgeleitet. Der Download bleibt zum Start beim bestellenden Konto. Der Wert wird mit der Bestellung festgehalten.'),
|
||||
TextInput::make('trainer_count')->label('Anzahl Trainer')
|
||||
->numeric()->minValue(2)->maxValue(LicenceScope::MAX_TRAINERS)->integer()
|
||||
->required(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
|
||||
->visible(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
|
||||
->helperText('Höchstzahl der Trainer, die die Inhalte einsetzen dürfen, mindestens 2. Eine Einzellizenz gilt immer für genau einen Trainer.'),
|
||||
Select::make('grant_kind')->label('Vergabe')->options([
|
||||
'kauf' => 'Kauf',
|
||||
'auf_abruf' => 'Auf Abruf',
|
||||
'bei_registrierung' => 'Bei Registrierung',
|
||||
])->required(),
|
||||
TextInput::make('price_euro')->label('Preis in Euro')->suffix('€')
|
||||
->helperText('Nur bei einem Kauf, zum Beispiel 49,00.'),
|
||||
TextInput::make('price_cents')->label('Preis in Cent')->numeric()
|
||||
->helperText('Nur bei einem Kauf. 500 bedeutet 5,00 €.'),
|
||||
Select::make('composition_version_id')->label('Programmfassung, die abgedeckt sein muss')
|
||||
->options(function (): array {
|
||||
return CompositionVersion::query()
|
||||
@@ -160,12 +124,9 @@ public function activateAction(): Action
|
||||
'article' => 'Lizenzartikel',
|
||||
'bundle' => 'Paketfassung',
|
||||
])->required()->live(),
|
||||
Select::make('article_id')->label('Artikel')->options(fn (): array => app(PublicationReadiness::class)->articleOptions())
|
||||
->searchable()
|
||||
->helperText('Nur Artikel mit veröffentlichtem Stand lassen sich verkaufen. Artikel ohne Stand sind gekennzeichnet.')
|
||||
Select::make('article_id')->label('Artikel')->options(fn (): array => CatalogOptions::articles())
|
||||
->visible(fn (Get $get): bool => $get('kind') === 'article'),
|
||||
Select::make('bundle_version_id')->label('Paketfassung')->options(fn (): array => app(PublicationReadiness::class)->bundleVersionOptions())
|
||||
->searchable()
|
||||
Select::make('bundle_version_id')->label('Paketfassung')->options(fn (): array => CatalogOptions::bundleVersions())
|
||||
->visible(fn (Get $get): bool => $get('kind') === 'bundle'),
|
||||
Select::make('rights_id')->label('Rechte')->options(fn (): array => CatalogOptions::rights())->required(),
|
||||
])->minItems(1)->addActionLabel('Position hinzufügen'),
|
||||
@@ -186,120 +147,29 @@ public function activateAction(): Action
|
||||
];
|
||||
}
|
||||
|
||||
// Voraussetzung: Jeder Artikel der Positionen hat einen veröffentlichten Stand, sonst erhielten Käufer nichts.
|
||||
$articleIds = [];
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$target = $line['target'];
|
||||
array_push($articleIds, ...($target instanceof BundleVersion ? app(BundleService::class)->articleIds($target) : [$target->id]));
|
||||
}
|
||||
|
||||
$unusable = app(PublicationReadiness::class)->unusableArticles($articleIds);
|
||||
|
||||
if ($unusable !== []) {
|
||||
throw new DomainRuleException(app(PublicationReadiness::class)->unusableMessage($unusable, 'das Angebot aktivierst'));
|
||||
}
|
||||
|
||||
// Bedingungen, die die Maske nicht zeigt, bleiben bei einer Änderung die der aktiven Fassung.
|
||||
// Bedingungen, die die Maske nicht zeigt, bleiben bei einer Änderung die der aktiven Fassung; ohne
|
||||
// aktive Fassung gilt wie bisher die Vorgabe (Personen, dauerhaft).
|
||||
$active = $this->activeVersion();
|
||||
$kept = $active === null ? [] : [
|
||||
$kept = $active === null ? ['holder_kind' => 'person'] : [
|
||||
'holder_kind' => $active->holder_kind,
|
||||
'term_rule' => $active->term_rule,
|
||||
'tax_class' => $active->tax_class,
|
||||
'dynamic' => (bool) $active->dynamic,
|
||||
];
|
||||
$price = Money::parse($data['price_euro'] ?? null);
|
||||
$version = app(OfferService::class)->activate($offer, $lines, [
|
||||
...$kept,
|
||||
'grant_kind' => $data['grant_kind'],
|
||||
'price_cents' => $data['price_cents'] === null || $data['price_cents'] === '' ? null : (int) $data['price_cents'],
|
||||
'composition_version_id' => filled($data['composition_version_id'] ?? null) ? (int) $data['composition_version_id'] : null,
|
||||
]);
|
||||
|
||||
if ($data['grant_kind'] === 'kauf' && ($price === null || $price <= 0)) {
|
||||
throw new DomainRuleException('Ein Kauf braucht einen Preis über 0,00 €.');
|
||||
}
|
||||
|
||||
$service = app(OfferService::class);
|
||||
$version = DB::transaction(function () use ($service, $offer, $data, $lines, $kept, $price) {
|
||||
$service->assignProduct(
|
||||
$offer,
|
||||
filled($data['composition_id'] ?? null) && $data['composition_id'] !== self::OWN_BUNDLE_PAGE ? (int) $data['composition_id'] : null,
|
||||
$data['option_label'] ?? null,
|
||||
($data['composition_id'] ?? null) === self::OWN_BUNDLE_PAGE,
|
||||
);
|
||||
|
||||
return $service->activate($offer, $lines, [
|
||||
...$kept,
|
||||
'holder_kind' => $data['holder_kind'],
|
||||
'licence_scope' => $data['licence_scope'] ?? null,
|
||||
'trainer_count' => $data['trainer_count'] ?? null,
|
||||
'grant_kind' => $data['grant_kind'],
|
||||
'price_cents' => $price,
|
||||
'composition_version_id' => filled($data['composition_version_id'] ?? null) ? (int) $data['composition_version_id'] : null,
|
||||
]);
|
||||
});
|
||||
|
||||
$offer->unsetRelations();
|
||||
$readiness = app(PublicationReadiness::class)->forOffer($offer->refresh());
|
||||
|
||||
return 'Fassung '.$version->number.' ist aktiv.'.($readiness['bereit']
|
||||
? ' Die Option ist öffentlich kaufbar und im Shop auffindbar.'
|
||||
: ' Noch nicht im Shop kaufbar. Nächster Schritt: '.$readiness['naechster']['titel'].'.');
|
||||
return 'Fassung '.$version->number.' ist aktiv.';
|
||||
}, 'Die Angebotsfassung ist aktiv.');
|
||||
$this->getRecord()->unsetRelations();
|
||||
$this->getRecord()->refresh();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Option aus dem Verkauf nehmen: nur die aktive Fassung dieser Option wird beendet.
|
||||
*/
|
||||
public function endAction(): Action
|
||||
{
|
||||
return Action::make('end')
|
||||
->label('Aus dem Verkauf nehmen')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalHeading(fn (): string => 'Option „'.$this->getRecord()->optionName().'“ aus dem Verkauf nehmen?')
|
||||
->modalDescription(fn (): string => 'Betroffen ist nur die Option „'.$this->getRecord()->optionName().'“'.$this->productPageSuffix().'. Die aktive Fassung wird beendet und bleibt gespeichert. Die Option ist danach nicht mehr kaufbar; in vorhandenen Warenkörben bleibt sie mit Hinweis sichtbar und blockiert den Abschluss, bis der Käufer sie entfernt. Bestehende Berechtigungen und Bestellungen ändern sich nicht. Andere Optionen derselben Produktseite bleiben kaufbar.')
|
||||
->modalSubmitActionLabel('Aus dem Verkauf nehmen')
|
||||
->visible(fn (): bool => $this->activeVersion() !== null)
|
||||
->action(function (): void {
|
||||
$this->report(function (): string {
|
||||
$version = app(OfferService::class)->end($this->getRecord());
|
||||
|
||||
return 'Fassung '.$version->number.' ist beendet. Die Option ist nicht mehr kaufbar.';
|
||||
}, 'Die Option ist aus dem Verkauf genommen.');
|
||||
$this->getRecord()->unsetRelations();
|
||||
$this->getRecord()->refresh();
|
||||
});
|
||||
}
|
||||
|
||||
/** „ der Produktseite „Titel““ oder leer, wenn die Option noch keiner Produktseite zugeordnet ist. */
|
||||
private function productPageSuffix(): string
|
||||
{
|
||||
$page = $this->getRecord()->composition;
|
||||
|
||||
return $page === null ? '' : ' der Produktseite „'.($page->display_title ?: $page->designation).'“';
|
||||
}
|
||||
|
||||
/**
|
||||
* Produktseiten, die als Ziel wählbar sind: Kompositionen mit Bezeichnung und Art.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function productPages(): array
|
||||
{
|
||||
$catalog = app(PublicCatalogReader::class);
|
||||
|
||||
return [self::OWN_BUNDLE_PAGE => 'Eigene Paketseite · zeigt den Umfang des Pakets (nur für ein Angebot aus genau einer Paketfassung)'] + Composition::query()
|
||||
->with('editorialContentKind')
|
||||
->whereNull('archived_at')
|
||||
->orderBy('designation')
|
||||
->get()
|
||||
->sortBy(fn (Composition $composition): int => $catalog->shownVersion($composition) !== null ? 0 : 1)
|
||||
->mapWithKeys(fn (Composition $composition): array => [
|
||||
$composition->id => ($composition->display_title ?: $composition->designation)
|
||||
.' ('.($composition->editorialContentKind?->label ?? 'Zusammenstellung').')'
|
||||
.($catalog->shownVersion($composition) !== null ? ' · im Shop auffindbar' : ' · nicht öffentlich, im Shop nicht auffindbar'),
|
||||
])
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorbelegung aus der aktiven Fassung; ohne aktive Fassung eine leere Position.
|
||||
*
|
||||
@@ -308,21 +178,14 @@ private function productPages(): array
|
||||
private function formFromActive(): array
|
||||
{
|
||||
$active = $this->activeVersion();
|
||||
/** @var Offer $offer */
|
||||
$offer = $this->getRecord();
|
||||
$option = ['option_label' => $offer->option_label, 'composition_id' => $offer->standalone_bundle ? self::OWN_BUNDLE_PAGE : $offer->composition_id];
|
||||
|
||||
if ($active === null) {
|
||||
return [...$option, 'holder_kind' => 'person', 'licence_scope' => LicenceScope::SINGLE, 'grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]];
|
||||
return ['grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]];
|
||||
}
|
||||
|
||||
return [
|
||||
...$option,
|
||||
'holder_kind' => $active->holder_kind,
|
||||
'licence_scope' => $active->licence_scope,
|
||||
'trainer_count' => $active->trainer_count,
|
||||
'grant_kind' => $active->grant_kind,
|
||||
'price_euro' => $active->price_cents === null ? null : number_format($active->price_cents / 100, 2, ',', ''),
|
||||
'price_cents' => $active->price_cents,
|
||||
'lines' => $active->lines->sortBy('position')->map(fn ($line): array => [
|
||||
'kind' => $line->license_article_id !== null ? 'article' : 'bundle',
|
||||
'article_id' => $line->license_article_id,
|
||||
@@ -357,27 +220,13 @@ private function angebotDaten(): array
|
||||
'status' => $active !== null
|
||||
? ['text' => 'Fassung '.$active->number.' aktiv · '.$vergabe, 'ton' => 'gut']
|
||||
: ['text' => 'Noch keine aktive Fassung. Ein Angebot ohne aktive Fassung kann niemand erwerben.', 'ton' => 'offen'],
|
||||
'aktionen' => [
|
||||
[
|
||||
'label' => $active !== null ? 'Geänderte Fassung aktivieren' : 'Fassung aktivieren',
|
||||
'wire' => "mountAction('activate')",
|
||||
'art' => 'primary',
|
||||
],
|
||||
...($active !== null ? [[
|
||||
'label' => 'Aus dem Verkauf nehmen',
|
||||
'wire' => "mountAction('end')",
|
||||
'art' => 'line',
|
||||
]] : []),
|
||||
...(ShopAccess::allowed() ? [[
|
||||
'label' => 'Zahlungen zu diesem Angebot',
|
||||
'href' => Zahlungsjournal::getUrl(['angebot' => $offer->id, 'zeitraum' => 'jahr', 'betrieb' => 'alle']),
|
||||
'art' => 'quiet',
|
||||
]] : []),
|
||||
],
|
||||
'aktionen' => [[
|
||||
'label' => $active !== null ? 'Geänderte Fassung aktivieren' : 'Fassung aktivieren',
|
||||
'wire' => "mountAction('activate')",
|
||||
'art' => 'primary',
|
||||
]],
|
||||
],
|
||||
'voraussetzungen' => app(PublicationReadiness::class)->forOffer($offer),
|
||||
'haupt' => [
|
||||
...($active !== null ? [$this->optionAbschnitt($offer, $active)] : []),
|
||||
[
|
||||
'titel' => 'Positionen',
|
||||
'zusatz' => $active !== null ? 'Fassung '.$active->number : null,
|
||||
@@ -412,39 +261,6 @@ private function angebotDaten(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Option auf einen Blick: Preis in Euro, Eignung, Rechte, zugrunde liegender Inhalt, Status und Produktseite.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function optionAbschnitt(Offer $offer, OfferVersion $active): array
|
||||
{
|
||||
$option = app(ProductOptions::class)->describe($offer, $active);
|
||||
$inhalt = collect($option['scope'])->pluck('article')->unique()->implode(', ');
|
||||
$rechte = collect($option['scope'])
|
||||
->map(fn (array $item): string => $item['purpose'].($item['rights'] === [] ? '' : ': '.implode(', ', $item['rights'])))
|
||||
->unique()
|
||||
->implode('; ');
|
||||
$seite = $offer->composition;
|
||||
$eigeneSeite = $offer->standalone_bundle;
|
||||
$kaufbar = app(OfferService::class)->purchasableVersion($offer) !== null;
|
||||
|
||||
return [
|
||||
'titel' => 'Die Option auf einen Blick',
|
||||
'zusatz' => 'Fassung '.$active->number,
|
||||
'hilfe' => 'So erscheint die Option auf der öffentlichen Produktseite und im Warenkorb. Die Angaben dieser Fassung sind unveränderlich.',
|
||||
'zeilen' => [
|
||||
['text' => 'Preis: '.$option['price'], 'neben' => $active->grant_kind === 'kauf' ? 'Kauf mit Testzahlung' : CatalogLabels::vergabe($active)],
|
||||
['text' => 'Geeignet für: '.$option['for'], 'neben' => $option['term']],
|
||||
['text' => 'Nutzerkreis: '.$option['licence'], 'neben' => $option['licence_scope'] === null ? 'Mit „Geänderte Fassung aktivieren“ festlegen.' : 'Lizenzinhaber, Nutzerkreis und Downloadkonto sind getrennte Angaben.'],
|
||||
['text' => 'Rechte: '.($rechte !== '' ? $rechte : 'keine'), 'neben' => null],
|
||||
['text' => 'Zugrunde liegender Inhalt: '.($inhalt !== '' ? $inhalt : '–'), 'neben' => null],
|
||||
['text' => 'Status: '.($kaufbar ? 'Öffentlich kaufbar' : 'Nicht als Kauf angeboten'), 'neben' => $kaufbar ? 'Aktive Fassung '.$active->number : null],
|
||||
['text' => 'Produktseite: '.($eigeneSeite ? 'eigene Paketseite mit dem Umfang des Pakets' : ($seite !== null ? ($seite->display_title ?: $seite->designation) : 'noch nicht zugeordnet')), 'neben' => $eigeneSeite || $seite !== null ? 'Option „'.$offer->optionName().'“' : 'Mit „Geänderte Fassung aktivieren“ zuordnen.'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Aufgelöster Leistungsumfang in lesbaren Fähigkeiten (dieselben Bezeichnungen wie beim Rechteprofil).
|
||||
*
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Orders;
|
||||
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Filament\Resources\Orders\Pages\ListOrders;
|
||||
use App\Filament\Resources\Orders\Pages\ViewOrder;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Auth\Access\Response;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Bestellverwaltung (PAY-006): Bestellungen lesen, bei Kauf auf Rechnung den Zahlungseingang bestätigen und
|
||||
* bezahlte Bestellungen vollständig erstatten. Es gibt keine Bearbeitung der gespeicherten Konditionen.
|
||||
*/
|
||||
class OrderResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Order::class;
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||
|
||||
protected static ?string $navigationLabel = 'Bestellungen';
|
||||
|
||||
protected static ?string $modelLabel = 'Bestellung';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Bestellungen';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
return ShopAccess::allowed();
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getViewAuthorizationResponse(Model $record): Response
|
||||
{
|
||||
return ShopAccess::allowed() ? Response::allow() : Response::deny();
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema;
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table->columns([
|
||||
TextColumn::make('id')->label('Bestellung'),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListOrders::route('/'),
|
||||
'view' => ViewOrder::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Orders\Pages;
|
||||
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Filament\Resources\Orders\OrderResource;
|
||||
use App\Filament\Support\ListsCatalog;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
class ListOrders extends ListRecords
|
||||
{
|
||||
use ListsCatalog;
|
||||
|
||||
protected static string $resource = OrderResource::class;
|
||||
|
||||
public function getSubheading(): string|Htmlable|null
|
||||
{
|
||||
return 'Bestellungen mit Lizenzinhaber, Zahlungsweg und Zahlbetrag. Bei Kauf auf Rechnung bestätigst du hier den Zahlungseingang; bezahlte Bestellungen erstattest du vollständig.';
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
protected function catalogRows(): array
|
||||
{
|
||||
$rows = [];
|
||||
|
||||
foreach (Order::query()->with(['lines', 'user', 'party'])->orderByDesc('id')->limit(300)->get() as $order) {
|
||||
$url = OrderResource::getUrl('view', ['record' => $order]);
|
||||
$zustand = [$order->status];
|
||||
$chips = [
|
||||
match ($order->status) {
|
||||
'bezahlt' => ['label' => 'Bezahlt', 'ton' => 'gut'],
|
||||
'erstattet' => ['label' => 'Erstattet', 'ton' => 'leise'],
|
||||
'fehlgeschlagen' => ['label' => 'Fehlgeschlagen', 'ton' => 'leise'],
|
||||
default => ['label' => $order->payment_method === 'rechnung' ? 'Offen: wartet auf Zahlungseingang' : 'Offen', 'ton' => 'offen'],
|
||||
},
|
||||
['label' => match ($order->payment_method) {
|
||||
'rechnung' => 'Rechnung', 'stripe' => 'Stripe', default => 'Testzahlung'
|
||||
}, 'ton' => 'neutral'],
|
||||
['label' => Money::format($order->payable()), 'ton' => 'neutral'],
|
||||
];
|
||||
|
||||
if ($order->discount_cents > 0) {
|
||||
$chips[] = ['label' => 'Rabatt '.($order->discount_snapshot['code'] ?? ''), 'ton' => 'neutral'];
|
||||
}
|
||||
|
||||
if ($order->withdrawal_requested_at !== null) {
|
||||
$chips[] = ['label' => 'Widerruf erklärt', 'ton' => 'offen'];
|
||||
$zustand[] = 'widerruf';
|
||||
}
|
||||
|
||||
if ($order->payment_method === 'rechnung' && $order->status === 'offen') {
|
||||
$zustand[] = 'rechnung_offen';
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'schluessel' => 'o'.$order->id,
|
||||
'titel' => 'Bestellung '.$order->id,
|
||||
'meta' => ($order->party?->display_name ?? '–').' · bestellt von '.($order->user?->name ?? '–'),
|
||||
'text' => $order->lines->pluck('offer_name')->implode('; '),
|
||||
'suchtext' => (string) ($order->user?->email ?? ''),
|
||||
'symbol' => 'etikett',
|
||||
'url' => $url,
|
||||
'chips' => $chips,
|
||||
'zustand' => $zustand,
|
||||
'aktionen' => [['label' => 'Öffnen', 'href' => $url]],
|
||||
];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
protected function zustandOptionen(): array
|
||||
{
|
||||
return [
|
||||
'alle' => 'Jeder Zustand',
|
||||
'rechnung_offen' => 'Rechnung: wartet auf Zahlungseingang',
|
||||
'widerruf' => 'Widerruf erklärt',
|
||||
'offen' => 'Offen',
|
||||
'bezahlt' => 'Bezahlt',
|
||||
'erstattet' => 'Erstattet',
|
||||
];
|
||||
}
|
||||
|
||||
protected function suchPlatzhalter(): string
|
||||
{
|
||||
return 'Nummer, Name, E-Mail oder Angebot';
|
||||
}
|
||||
|
||||
protected function einheit(): array
|
||||
{
|
||||
return ['Bestellung', 'Bestellungen'];
|
||||
}
|
||||
|
||||
protected function leer(): array
|
||||
{
|
||||
return ['titel' => 'Noch keine Bestellungen', 'text' => 'Sobald im Shop bestellt wird, erscheinen die Bestellungen hier.'];
|
||||
}
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Orders\Pages;
|
||||
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Commerce\Checkout;
|
||||
use App\Domain\Commerce\LedgerEntry;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\OrderLine;
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\PaymentJournal;
|
||||
use App\Filament\Resources\Orders\OrderResource;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\View;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Bestellung im gemeinsamen Rahmen. Die gespeicherten Konditionen sind unveränderlich; der Betreiber bestätigt bei
|
||||
* Kauf auf Rechnung den Zahlungseingang und erstattet bezahlte Bestellungen vollständig (Bundles als Einheit).
|
||||
*/
|
||||
class ViewOrder extends ViewRecord
|
||||
{
|
||||
use ReportsDomainRules;
|
||||
|
||||
protected static string $resource = OrderResource::class;
|
||||
|
||||
public function getTitle(): string|Htmlable
|
||||
{
|
||||
return 'Bestellung '.$this->order()->id;
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function getBreadcrumbs(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function infolist(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
View::make('filament.catalog.objekt')->viewData(fn (): array => $this->bestellDaten())->columnSpanFull(),
|
||||
])->columns(1);
|
||||
}
|
||||
|
||||
private function hasStripePayment(): bool
|
||||
{
|
||||
return $this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists();
|
||||
}
|
||||
|
||||
private function order(): Order
|
||||
{
|
||||
/** @var Order $order */
|
||||
$order = $this->getRecord();
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
public function confirmInvoiceAction(): Action
|
||||
{
|
||||
return Action::make('confirmInvoice')
|
||||
->label('Zahlungseingang bestätigen')
|
||||
->modalHeading(fn (): string => 'Zahlungseingang für Bestellung '.$this->order()->id.' bestätigen')
|
||||
->modalDescription(fn (): string => 'Du bestätigst, dass '.Money::format($this->order()->payable()).' für die Rechnung eingegangen sind. Die Inhalte werden sofort für das bestellende Konto freigeschaltet; Lizenzinhaber bleibt '.($this->order()->party?->display_name ?? 'der Käufer').'. Die Bestätigung lässt sich nicht zurücknehmen, nur die Bestellung erstatten.')
|
||||
->modalSubmitActionLabel('Zahlungseingang bestätigen')
|
||||
->schema([
|
||||
TextInput::make('reference')->label('Rechnungsnummer oder Buchungsreferenz')->required()->maxLength(120)
|
||||
->helperText('Bleibt an der Zahlung gespeichert, zum Beispiel „RE-2026-014“.'),
|
||||
DatePicker::make('received_on')->label('Zahlungseingang am')->required()->native(false)->displayFormat('d.m.Y')
|
||||
->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||
->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||
->helperText('Der Tag, an dem das Geld auf dem Konto einging. Er bestimmt, in welchen Zeitraum die Einnahme im Zahlungsjournal fällt.'),
|
||||
])
|
||||
->visible(fn (): bool => $this->order()->payment_method === 'rechnung' && $this->order()->status === 'offen')
|
||||
->action(function (array $data): void {
|
||||
$this->report(function () use ($data): string {
|
||||
app(Checkout::class)->confirmInvoicePayment($this->order(), (string) $data['reference'], Filament::auth()->user(), (string) $data['received_on']);
|
||||
|
||||
return 'Der Zahlungseingang ist bestätigt. Die Inhalte sind freigeschaltet.';
|
||||
}, 'Bestätigt.');
|
||||
$this->order()->unsetRelations();
|
||||
$this->order()->refresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function refundAction(): Action
|
||||
{
|
||||
return Action::make('refund')
|
||||
->label('Bestellung erstatten')
|
||||
->color('danger')
|
||||
->modalHeading(fn (): string => 'Bestellung '.$this->order()->id.' vollständig erstatten?')
|
||||
->modalDescription(fn (): string => 'Alle Positionen dieser Bestellung werden zurückgegeben: Die Berechtigungen daraus werden widerrufen, andere Erwerbsquellen (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Pakete sind eine Einheit; Teilerstattungen gibt es zum Start nicht. '.(
|
||||
$this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists()
|
||||
? 'Die Rückzahlung von '.Money::format($this->order()->payable()).' wird bei Stripe veranlasst; nur wenn Stripe sie annimmt, werden die Rechte entzogen.'
|
||||
: 'Die Rückzahlung selbst veranlasst du außerhalb dieser Anwendung, zum Beispiel per Überweisung.'
|
||||
))
|
||||
->modalSubmitActionLabel('Vollständig erstatten')
|
||||
->schema([
|
||||
Textarea::make('reason')->label('Begründung')->required()->rows(2)->maxLength(500)
|
||||
->helperText('Bleibt am Widerruf der Berechtigungen und im Zahlungsjournal stehen, zum Beispiel „Widerruf geprüft, Frist gewahrt“.'),
|
||||
DatePicker::make('refunded_on')->label('Rückzahlung am')->native(false)->displayFormat('d.m.Y')
|
||||
->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||
->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||
->visible(fn (): bool => ! $this->hasStripePayment())
|
||||
->helperText('Der Tag, an dem du das Geld zurücküberwiesen hast. Bei Stripe gilt der Zeitpunkt von Stripe.'),
|
||||
TextInput::make('refund_reference')->label('Referenz der Rückzahlung')->maxLength(120)
|
||||
->visible(fn (): bool => ! $this->hasStripePayment())
|
||||
->helperText('Optional, zum Beispiel Buchungstext oder Gutschriftnummer.'),
|
||||
])
|
||||
->visible(fn (): bool => $this->order()->status === 'bezahlt')
|
||||
->action(function (array $data): void {
|
||||
$this->report(function () use ($data): string {
|
||||
app(Checkout::class)->refund(
|
||||
$this->order(),
|
||||
(string) $data['reason'],
|
||||
null,
|
||||
Filament::auth()->user(),
|
||||
$this->hasStripePayment() ? null : ($data['refunded_on'] ?? null),
|
||||
$this->hasStripePayment() ? null : ($data['refund_reference'] ?? null),
|
||||
);
|
||||
|
||||
return 'Die Bestellung ist erstattet. Die Berechtigungen sind widerrufen.';
|
||||
}, 'Erstattet.');
|
||||
$this->order()->unsetRelations();
|
||||
$this->order()->refresh();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function bestellDaten(): array
|
||||
{
|
||||
$order = $this->order();
|
||||
$order->loadMissing(['lines', 'user', 'party', 'payments']);
|
||||
$date = fn (?Carbon $value): string => $value === null ? '' : $value->timezone(config('app.timezone'))->format('d.m.Y H:i');
|
||||
$method = match ($order->payment_method) {
|
||||
'rechnung' => 'Überweisung auf Rechnung (manuell)',
|
||||
'stripe' => 'Stripe',
|
||||
default => 'Testzahlung',
|
||||
};
|
||||
|
||||
return [
|
||||
'kopf' => [
|
||||
'brot' => [['label' => 'Bestellungen', 'href' => OrderResource::getUrl('index')], 'Bestellung '.$order->id],
|
||||
'titel' => 'Bestellung '.$order->id,
|
||||
'typ' => 'Lizenzinhaber: '.($order->party?->display_name ?? '–').' · bestellt von '.($order->user?->name ?? '–').' ('.($order->user?->email ?? '').')',
|
||||
'status' => [
|
||||
['text' => match ($order->status) {
|
||||
'bezahlt' => 'Bezahlt ('.$method.')',
|
||||
'erstattet' => 'Erstattet. Die Berechtigungen sind widerrufen.',
|
||||
'fehlgeschlagen' => 'Zahlung fehlgeschlagen. Es wurde nichts freigeschaltet.',
|
||||
default => $order->payment_method === 'rechnung' ? 'Offen: Rechnung erstellen und Zahlungseingang bestätigen.' : 'Offen: Zahlung steht aus.',
|
||||
}, 'ton' => $order->status === 'bezahlt' ? 'gut' : 'offen'],
|
||||
$order->withdrawal_requested_at !== null ? ['text' => 'Widerruf erklärt am '.$date($order->withdrawal_requested_at).'. Prüfen und gegebenenfalls erstatten.', 'ton' => 'offen'] : null,
|
||||
],
|
||||
'aktionen' => [
|
||||
...($order->payment_method === 'rechnung' && $order->status === 'offen' ? [['label' => 'Zahlungseingang bestätigen', 'wire' => "mountAction('confirmInvoice')", 'art' => 'primary']] : []),
|
||||
...($order->status === 'bezahlt' ? [['label' => 'Bestellung erstatten', 'wire' => "mountAction('refund')", 'art' => 'line']] : []),
|
||||
],
|
||||
],
|
||||
'haupt' => [
|
||||
[
|
||||
'titel' => 'Positionen',
|
||||
'hilfe' => 'Fassung, Preis, Rabatt, Nutzerkreis und Umfang sind beim Kauf festgehalten und ändern sich nicht.',
|
||||
'zeilen' => $order->lines->map(fn (OrderLine $line): array => [
|
||||
'text' => ($line->offer_name ?: 'Angebot').': '.Money::format((int) $line->price_cents).($line->discount_cents > 0 ? ' − Rabatt '.Money::format((int) $line->discount_cents).' = '.Money::format($line->payable()) : ''),
|
||||
'neben' => LicenceScope::label($line->licence_scope, $line->trainer_count).' · Angebotsfassung '.($line->offerVersion?->number ?? '–'),
|
||||
])->values()->all(),
|
||||
'leer' => ['titel' => 'Keine Positionen', 'text' => 'Diese Bestellung hat keine Positionen.'],
|
||||
],
|
||||
[
|
||||
'titel' => 'Beträge',
|
||||
'zeilen' => [
|
||||
['text' => 'Zwischensumme (Listenpreise): '.Money::format($order->subtotal()), 'neben' => null],
|
||||
...($order->discount_cents > 0 ? [['text' => 'Rabatt: −'.Money::format((int) $order->discount_cents), 'neben' => 'Code '.($order->discount_snapshot['code'] ?? '').' · '.($order->discount_snapshot['label'] ?? '')]] : []),
|
||||
['text' => 'Zahlbetrag: '.Money::format($order->payable()), 'neben' => 'Dieser Betrag ging an '.$method.'.'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'titel' => 'Zahlungen',
|
||||
'zeilen' => $order->payments->map(fn (Payment $payment): array => [
|
||||
'text' => match ($payment->provider) {
|
||||
'stripe' => 'Stripe', 'ueberweisung' => 'Überweisung', default => 'Testzahlung'
|
||||
}.' · '.match ($payment->status) {
|
||||
'bestaetigt' => 'bestätigt', 'erstattet' => 'erstattet', 'offen' => 'offen', 'abgelaufen' => 'abgelaufen', 'zu_pruefen' => 'zu prüfen', 'fehlgeschlagen' => 'fehlgeschlagen', default => $payment->status
|
||||
},
|
||||
'neben' => $payment->provider_reference.($payment->amount_cents !== null ? ' · '.Money::format((int) $payment->amount_cents) : ''),
|
||||
])->values()->all(),
|
||||
'leer' => ['titel' => 'Noch keine Zahlung', 'text' => 'Es gibt noch keinen Zahlungsvorgang zu dieser Bestellung.'],
|
||||
],
|
||||
[
|
||||
'titel' => 'Buchungen im Zahlungsjournal',
|
||||
'hilfe' => 'Unveränderlich festgehalten, mit Datum, Beleg beim Anbieter und Rechnungsempfänger zum Zeitpunkt der Buchung. Alle Buchungen eines Zeitraums und den Export findest du unter „Einnahmen und Erstattungen“.',
|
||||
'zeilen' => LedgerEntry::query()->where('order_id', $order->id)->orderBy('occurred_at')->orderBy('id')->get()->map(fn (LedgerEntry $entry): array => [
|
||||
'text' => PaymentJournal::local($entry->occurred_at)->format('d.m.Y').' · '.($entry->isRefund() ? 'Erstattung −' : 'Zahlungseingang ').Money::format(abs($entry->amount_cents)).($entry->live ? '' : ' (Test, kein Umsatz)').($entry->derived ? ' (nachgetragen)' : ''),
|
||||
'neben' => PaymentJournal::providerLabel($entry->provider).' · '.$entry->provider_reference.(filled($entry->actor_name) ? ' · gebucht von '.$entry->actor_name : ''),
|
||||
])->values()->all(),
|
||||
'leer' => ['titel' => 'Noch keine Buchung', 'text' => 'Zahlungseingang und Erstattung dieser Bestellung erscheinen hier.'],
|
||||
],
|
||||
],
|
||||
'seite' => [
|
||||
[
|
||||
'titel' => 'Zustimmung',
|
||||
'zeilen' => $order->terms_accepted_at === null ? [] : [
|
||||
['text' => 'Zugestimmt am '.$date($order->terms_accepted_at), 'neben' => 'Fassung der Texte: '.($order->terms_snapshot['version'] ?? '–')],
|
||||
...collect($order->terms_snapshot['consents'] ?? [])->map(fn (string $wording): array => ['text' => $wording, 'neben' => null])->values()->all(),
|
||||
],
|
||||
'leer' => 'Zu dieser Bestellung ist keine Zustimmung festgehalten (Bestellung vor dem Verkaufsstart oder über den Testweg).',
|
||||
],
|
||||
[
|
||||
'titel' => 'Widerruf',
|
||||
'zeilen' => $order->withdrawal_requested_at === null ? [] : [
|
||||
['text' => 'Erklärt am '.$date($order->withdrawal_requested_at), 'neben' => filled($order->withdrawal_note) ? $order->withdrawal_note : null],
|
||||
],
|
||||
'leer' => 'Kein Widerruf erklärt.',
|
||||
'hilfe' => 'Der Widerruf entzieht nichts. Du prüfst ihn (bei sofortiger Bereitstellung mit Zustimmung kann das Recht erloschen sein) und erstattest bei Bedarf über „Bestellung erstatten“.',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ class ListPillars extends ListRecords
|
||||
|
||||
public function getSubheading(): string|Htmlable|null
|
||||
{
|
||||
return 'Die fachlichen Säulen des Materials. Eine veröffentlichte Säule ist ein Themenbereich der Website. Medien, Module, Programme, Lizenzartikel und Seiten können mehreren Säulen zugeordnet sein. Hier ist die einzige Pflegestelle der Säulen.';
|
||||
return 'Die fachlichen Säulen des Materials. Eine veröffentlichte Säule ist ein Themenbereich der Website. Ein Medium und eine Seite können mehreren Säulen zugeordnet sein.';
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
@@ -50,28 +50,11 @@ protected function getHeaderActions(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Zuordnungen aller Objektarten; ohne Zuordnung wie bisher „0 Medien“.
|
||||
*/
|
||||
private function usageLabel(PillarService $service, Pillar $pillar): string
|
||||
{
|
||||
$usage = [
|
||||
'medien' => (int) $pillar->elements_count,
|
||||
'zusammenstellungen' => (int) $pillar->compositions_count,
|
||||
'lizenzartikel' => (int) $pillar->license_articles_count,
|
||||
'seiten' => (int) $pillar->pages_count,
|
||||
];
|
||||
|
||||
return array_sum($usage) === 0 ? '0 Medien' : $service->usageText($usage);
|
||||
}
|
||||
|
||||
protected function catalogRows(): array
|
||||
{
|
||||
$rows = [];
|
||||
|
||||
$service = app(PillarService::class);
|
||||
|
||||
foreach (Pillar::query()->withCount(['elements', 'compositions', 'licenseArticles', 'pages'])->orderBy('sort_order')->orderBy('name')->get() as $pillar) {
|
||||
foreach (Pillar::query()->withCount('elements')->orderBy('sort_order')->orderBy('name')->get() as $pillar) {
|
||||
$public = $pillar->published_at !== null;
|
||||
$url = PillarResource::getUrl('edit', ['record' => $pillar]);
|
||||
$rows[] = [
|
||||
@@ -83,7 +66,7 @@ protected function catalogRows(): array
|
||||
'url' => $url,
|
||||
'chips' => [
|
||||
$public ? ['label' => 'Auf der Website veröffentlicht', 'ton' => 'gut'] : ['label' => 'Intern', 'ton' => 'leise'],
|
||||
['label' => $this->usageLabel($service, $pillar), 'ton' => 'neutral'],
|
||||
['label' => $pillar->elements_count === 1 ? '1 Medium' : $pillar->elements_count.' Medien', 'ton' => 'neutral'],
|
||||
],
|
||||
'zustand' => [$public ? 'oeffentlich' : 'intern'],
|
||||
'aktionen' => [['label' => 'Bearbeiten', 'href' => $url, 'icon' => 'stift']],
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Pillar;
|
||||
use App\Domain\Catalog\PillarService;
|
||||
|
||||
/**
|
||||
* Fachliche Säulen im Redaktionsmanager von Modul, Programm und Lizenzartikel (wie bei Medien): Die Auswahl kommt aus
|
||||
* der zentralen Säulenverwaltung, die Zuordnung ersetzt die bisherige vollständig und bleibt beim Speichern anderer
|
||||
* Angaben erhalten, weil der gespeicherte Stand geladen und mitgeschrieben wird.
|
||||
*
|
||||
* Eine Zuordnung veröffentlicht nichts: Ob eine Säule eine Themenseite hat, entscheidet allein die Säulenverwaltung.
|
||||
*/
|
||||
trait AssignsPillars
|
||||
{
|
||||
/** @var list<int|string> */
|
||||
public array $pillarIds = [];
|
||||
|
||||
/**
|
||||
* @return array{legend: string, model: string, values: list<array{id: int, label: string}>}|null
|
||||
*/
|
||||
public function pillarGroup(): ?array
|
||||
{
|
||||
$values = Pillar::query()->orderBy('sort_order')->orderBy('name')->get(['id', 'name'])
|
||||
->map(fn (Pillar $pillar): array => ['id' => (int) $pillar->id, 'label' => (string) $pillar->name])
|
||||
->all();
|
||||
|
||||
return $values === [] ? null : ['legend' => 'Fachliche Säulen', 'model' => 'pillarIds', 'values' => $values];
|
||||
}
|
||||
|
||||
protected function loadPillarIds(Composition|LicenseArticle $subject): void
|
||||
{
|
||||
$this->pillarIds = $subject->pillars()->pluck('pillars.id')->map(fn (mixed $id): string => (string) (int) $id)->all();
|
||||
}
|
||||
|
||||
protected function persistPillarIds(Composition|LicenseArticle $subject): void
|
||||
{
|
||||
app(PillarService::class)->assign($subject, array_map(intval(...), $this->pillarIds));
|
||||
}
|
||||
|
||||
protected function pillarsUnsaved(Composition|LicenseArticle $subject): bool
|
||||
{
|
||||
$stored = $subject->pillars()->pluck('pillars.id')->map(fn (mixed $id): int => (int) $id)->all();
|
||||
$current = array_map(intval(...), $this->pillarIds);
|
||||
sort($stored);
|
||||
sort($current);
|
||||
|
||||
return $stored !== $current;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\Pillar;
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Http\Controllers\ContentPreviewController;
|
||||
@@ -28,9 +27,6 @@ trait ChoosesMedia
|
||||
|
||||
public string $pickerDimension = '';
|
||||
|
||||
/** Filter „Fachliche Säule“ (Kennung der Säule aus der zentralen Säulenverwaltung). */
|
||||
public string $pickerSaeule = '';
|
||||
|
||||
/** Filter „Fachliche Materialart“ (Kennung), gleiche Regel wie Medieneditor und Medienfilter. */
|
||||
public string $pickerMaterialart = '';
|
||||
|
||||
@@ -112,8 +108,6 @@ public function pickerResult(): array
|
||||
$this->pickerKind,
|
||||
$this->pickerDimension,
|
||||
$this->pickerExceptId(),
|
||||
false,
|
||||
ctype_digit($this->pickerSaeule) ? (int) $this->pickerSaeule : 0,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -210,7 +204,6 @@ protected function resetPicker(string $purpose): void
|
||||
$this->pickerOpen = true;
|
||||
$this->pickerQuery = '';
|
||||
$this->pickerDimension = '';
|
||||
$this->pickerSaeule = '';
|
||||
$this->pickerMaterialart = '';
|
||||
$this->pickerInspected = '';
|
||||
$this->pickerSelected = '';
|
||||
@@ -246,17 +239,6 @@ private function filterByMaterialart(array $result): array
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Säulen für den Picker-Filter, in der Reihenfolge der Säulenverwaltung.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function pickerSaeulen(): array
|
||||
{
|
||||
return Pillar::query()->orderBy('sort_order')->orderBy('name')->pluck('name', 'id')
|
||||
->mapWithKeys(fn (string $name, int|string $id): array => [(string) $id => $name])->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Einordnungsfilter des Pickers: dieselbe Filterregel wie Medien- und Kompositionslisten (verwendete inaktive Werte
|
||||
* bleiben auffindbar, ein gewählter Filter bleibt sichtbar).
|
||||
|
||||
@@ -2,14 +2,8 @@
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Media\CompositionStill;
|
||||
use App\Domain\Media\FilmStill;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use Filament\Notifications\Notification;
|
||||
|
||||
/**
|
||||
@@ -37,128 +31,6 @@ public function openWebsiteImagePicker(string $pfad): void
|
||||
$this->forceRenderForPicker();
|
||||
}
|
||||
|
||||
/**
|
||||
* Medien- und Materialkarte: das Vorschaubild des Films als Bild für die Website übernehmen. Es entsteht ein Bild
|
||||
* im Medienmanager (einmal gespeichert), das im Bildfeld ausgewählt wird. Die Datei des Films bleibt geschützt.
|
||||
*/
|
||||
public function adoptFilmThumbnail(string $pfad, int $elementId): void
|
||||
{
|
||||
$this->adoptFilmStill($pfad, $elementId, fn (FilmStill $stills, ContentElement $film): ContentElement => $stills->fromThumbnail($film, auth('staff')->user()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Medien- und Materialkarte: eine Stelle des Films wählen und als Bild für die Website übernehmen.
|
||||
*/
|
||||
public function adoptFilmFrame(string $pfad, int $elementId, string $sekunde): void
|
||||
{
|
||||
if (! is_numeric($sekunde)) {
|
||||
Notification::make()->danger()->title('Bitte eine Zeitposition in Sekunden angeben.')->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->adoptFilmStill($pfad, $elementId, fn (FilmStill $stills, ContentElement $film): ContentElement => $stills->fromSecond($film, (float) $sekunde, auth('staff')->user()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Programm- und Modulkarte: das Vorschaubild des Programms oder Moduls als Bild für die Website übernehmen
|
||||
* (Bild-Medium im Medienmanager, einmal kopiert).
|
||||
*/
|
||||
public function adoptCompositionThumbnail(string $pfad, int $compositionId): void
|
||||
{
|
||||
abort_unless(ContentElementResource::editor(), 403);
|
||||
|
||||
if ($this->imageTargetIsInvalid($pfad)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$composition = Composition::query()->find($compositionId);
|
||||
|
||||
if (! $composition instanceof Composition) {
|
||||
return;
|
||||
}
|
||||
|
||||
$stills = app(CompositionStill::class);
|
||||
|
||||
try {
|
||||
$still = $stills->fromThumbnail($composition, auth('staff')->user());
|
||||
} catch (DomainRuleException $exception) {
|
||||
Notification::make()->danger()->title($exception->getMessage())->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
data_set($this, $pfad, $still->id);
|
||||
$this->announceAdoptedStill($still, $stills->reused, 'Dieses Vorschaubild war schon übernommen.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(FilmStill, ContentElement): ContentElement $make
|
||||
*/
|
||||
private function adoptFilmStill(string $pfad, int $elementId, callable $make): void
|
||||
{
|
||||
abort_unless(ContentElementResource::editor(), 403);
|
||||
|
||||
if ($this->imageTargetIsInvalid($pfad)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$film = ContentElement::query()->with('editorialContentKind')->find($elementId);
|
||||
|
||||
if (! $film instanceof ContentElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
$stills = app(FilmStill::class);
|
||||
|
||||
try {
|
||||
$still = $make($stills, $film);
|
||||
} catch (DomainRuleException $exception) {
|
||||
Notification::make()->danger()->title($exception->getMessage())->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
data_set($this, $pfad, $still->id);
|
||||
$this->announceAdoptedStill($still, $stills->reused, 'Diese Stelle war schon übernommen.');
|
||||
}
|
||||
|
||||
/** Nur das Bildfeld eines Widgets oder Abschnitts ist ein zulässiges Ziel (…image). */
|
||||
private function imageTargetIsInvalid(string $pfad): bool
|
||||
{
|
||||
return preg_match('/^(data|mountedActions\.\d+\.data)(\.[A-Za-z0-9_-]+)+\.image$/', $pfad) !== 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Meldung nach dem tatsächlichen Stand des Bildes: neu angelegt, schon vorhanden und freigegeben, wird verarbeitet
|
||||
* oder Website-Freigabe zurückgenommen (bleibt zurückgenommen).
|
||||
*/
|
||||
private function announceAdoptedStill(ContentElement $still, bool $reused, string $reusedText): void
|
||||
{
|
||||
$title = ($still->display_title ?: $still->working_title);
|
||||
|
||||
if (! $reused) {
|
||||
Notification::make()
|
||||
->success()
|
||||
->title('Im Medienmanager angelegt: „'.$title.'“')
|
||||
->body('Das Bild ist als Kartenbild ausgewählt. Nach der Verarbeitung wird es für die Website freigegeben; dort lässt sich die Freigabe auch zurücknehmen.')
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (app(WebsiteMedia::class)->present($still) !== null) {
|
||||
Notification::make()->success()->title('Bereits im Medienmanager: „'.$title.'“')->body($reusedText.' Das Bild ist als Kartenbild ausgewählt.')->send();
|
||||
} elseif (blank($still->thumbnail_path) && blank($still->thumbnail_error)) {
|
||||
Notification::make()->success()->title('Bereits im Medienmanager: „'.$title.'“')->body('Das Bild wird noch verarbeitet und danach für die Website freigegeben.')->send();
|
||||
} else {
|
||||
Notification::make()->warning()->title('Bild ausgewählt, aber nicht für die Website freigegeben: „'.$title.'“')
|
||||
->body($reusedText.' Die Website-Freigabe wurde zurückgenommen. Das Bild erscheint öffentlich erst wieder, wenn sie im Medienmanager (Reiter „Website“) erneut gegeben wird.')
|
||||
->persistent()
|
||||
->send();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filament rendert bei offenen Aktionsdialogen nur den Dialogteil neu; der Picker liegt darüber und braucht die
|
||||
* ganze Seite.
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
|
||||
/**
|
||||
* Die eine Maske für Rabattcodes: Anlegen und Bearbeiten nutzen dieselben Felder (FACH-20). Geltungsbereich und
|
||||
* Einlösungsberechtigung sind zwei voneinander unabhängige Einstellungen.
|
||||
*/
|
||||
final class DiscountCodeForm
|
||||
{
|
||||
/**
|
||||
* @return list<mixed>
|
||||
*/
|
||||
public static function schema(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('code')->label('Code')->required()->maxLength(40)
|
||||
->helperText('So gibt ihn der Käufer ein, 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich. Groß- und Kleinschreibung spielen keine Rolle.'),
|
||||
TextInput::make('label')->label('Name für die Verwaltung')->required()->maxLength(120)
|
||||
->helperText('Nur intern, zum Beispiel „Zertifizierungscode 2026“. Der Käufer sieht ihn nicht.'),
|
||||
Select::make('kind')->label('Art des Rabatts')->options([
|
||||
DiscountCode::PERCENT => 'Prozent',
|
||||
DiscountCode::AMOUNT => 'Fester Betrag in Euro',
|
||||
])->required()->live(),
|
||||
TextInput::make('percent')->label('Prozent')->numeric()->minValue(1)->maxValue(100)->integer()->suffix('%')
|
||||
->required(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT)
|
||||
->visible(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT)
|
||||
->helperText('Je Position gerundet. Der Zahlbetrag der Bestellung darf 0,50 € nicht unterschreiten.'),
|
||||
TextInput::make('amount_euro')->label('Rabattbetrag')->suffix('€')
|
||||
->required(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT)
|
||||
->visible(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT)
|
||||
->helperText('Gilt je Bestellung und wird anteilig auf die betroffenen Positionen verteilt, zum Beispiel 5,00.'),
|
||||
Select::make('scope')->label('Geltungsbereich')->options([
|
||||
DiscountCode::SCOPE_CART => 'Gesamter Warenkorb',
|
||||
DiscountCode::SCOPE_SELECTED => 'Nur ausdrücklich ausgewählte Angebote, Lizenzartikel oder Pakete',
|
||||
])->required()->live()
|
||||
->helperText('Wofür der Rabatt gilt. Unabhängig davon legst du unten fest, wer den Code einlösen darf.'),
|
||||
Select::make('offer_ids')->label('Angebote')->multiple()->searchable()
|
||||
->options(fn (): array => Offer::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
|
||||
->helperText('Die gewählte Lizenzoption selbst (Fassung egal).'),
|
||||
Select::make('article_ids')->label('Lizenzartikel')->multiple()->searchable()
|
||||
->options(fn (): array => app(PublicationReadiness::class)->articleOptions())
|
||||
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
|
||||
->helperText('Gilt für Angebote, die diesen Artikel unmittelbar als Position führen. Ein Artikel in einem Paket macht das Paket nicht rabattfähig.'),
|
||||
Select::make('bundle_ids')->label('Pakete')->multiple()->searchable()
|
||||
->options(fn (): array => Bundle::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
|
||||
->helperText('Ein Paket wird gezielt gewählt. Es folgt nicht aus einem enthaltenen Artikel.'),
|
||||
Select::make('eligibility')->label('Wer darf den Code einlösen?')->options([
|
||||
DiscountCode::OPEN => 'Alle angemeldeten Käufer (allgemein einlösbar)',
|
||||
DiscountCode::RESTRICTED => 'Nur ausdrücklich freigeschaltete Konten',
|
||||
])->required()
|
||||
->helperText('Bei „freigeschaltete Konten“ schaltest du einzelne Konten auf der Seite des Codes frei und entziehst die Freigabe wieder. Eine Freigabe gilt nur für diesen Code.'),
|
||||
DatePicker::make('valid_from')->label('Gültig ab')->native(false)->displayFormat('d.m.Y')
|
||||
->helperText('Leer: sofort.'),
|
||||
DatePicker::make('valid_until')->label('Gültig bis einschließlich')->native(false)->displayFormat('d.m.Y')
|
||||
->helperText('Leer: unbegrenzt. Am Tag danach gilt der Code nicht mehr.'),
|
||||
Toggle::make('active')->label('Aktiv')->default(true)
|
||||
->helperText('Deaktivierte Codes lassen sich nicht einlösen; bereits aufgegebene Bestellungen bleiben unverändert.'),
|
||||
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(500)
|
||||
->helperText('Zum Beispiel, woran die Berechtigung geprüft wird.'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Formularwerte → Angaben und Ziele des Dienstes.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array{0: array<string, mixed>, 1: list<array{type: string, id: int}>}
|
||||
*/
|
||||
public static function fromForm(array $data): array
|
||||
{
|
||||
$targets = [];
|
||||
|
||||
foreach ([
|
||||
DiscountCode::TARGET_OFFER => 'offer_ids',
|
||||
DiscountCode::TARGET_ARTICLE => 'article_ids',
|
||||
DiscountCode::TARGET_BUNDLE => 'bundle_ids',
|
||||
] as $type => $key) {
|
||||
foreach ((array) ($data[$key] ?? []) as $id) {
|
||||
$targets[] = ['type' => $type, 'id' => (int) $id];
|
||||
}
|
||||
}
|
||||
|
||||
return [$data, $targets];
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorbelegung der Maske aus einem vorhandenen Code.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function fill(DiscountCode $code): array
|
||||
{
|
||||
$code->loadMissing('targets');
|
||||
$ids = fn (string $type): array => $code->targets->where('target_type', $type)->pluck('target_id')->map(fn ($id): int => (int) $id)->values()->all();
|
||||
|
||||
return [
|
||||
'code' => $code->code,
|
||||
'label' => $code->label,
|
||||
'kind' => $code->kind,
|
||||
'percent' => $code->percent,
|
||||
'amount_euro' => $code->amount_cents === null ? null : number_format($code->amount_cents / 100, 2, ',', ''),
|
||||
'scope' => $code->scope,
|
||||
'offer_ids' => $ids(DiscountCode::TARGET_OFFER),
|
||||
'article_ids' => $ids(DiscountCode::TARGET_ARTICLE),
|
||||
'bundle_ids' => $ids(DiscountCode::TARGET_BUNDLE),
|
||||
'eligibility' => $code->eligibility,
|
||||
'valid_from' => $code->valid_from?->timezone(config('app.timezone'))->toDateString(),
|
||||
'valid_until' => $code->valid_until?->timezone(config('app.timezone'))->toDateString(),
|
||||
'active' => $code->active,
|
||||
'note' => $code->note,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -272,7 +272,7 @@ public function search(string $query, string $scope, int $exceptCompositionId):
|
||||
/**
|
||||
* @return array{items: list<array<string, string|null>>, more: bool}
|
||||
*/
|
||||
public function browse(string $query, string $kind, string $dimension, int $exceptCompositionId, bool $elementsOnly = false, int $pillarId = 0): array
|
||||
public function browse(string $query, string $kind, string $dimension, int $exceptCompositionId, bool $elementsOnly = false): array
|
||||
{
|
||||
$query = trim($query);
|
||||
$like = '%'.str_replace(['%', '_'], ['', ''], $query).'%';
|
||||
@@ -284,8 +284,8 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
||||
$latestElements = ContentElementVersion::query()
|
||||
->selectRaw('MAX(id)')
|
||||
->whereIn('status', [ContentVersionStatus::Bereit, ContentVersionStatus::Entwurf])
|
||||
->whereHas('element', function ($builder) use ($query, $like, $kind, $dimensionId, $pillarId): void {
|
||||
$this->constrainElement($builder, $query, $like, $kind, $dimensionId, $pillarId);
|
||||
->whereHas('element', function ($builder) use ($query, $like, $kind, $dimensionId): void {
|
||||
$this->constrainElement($builder, $query, $like, $kind, $dimensionId);
|
||||
})
|
||||
->groupBy('content_element_id');
|
||||
$elements = ContentElementVersion::query()
|
||||
@@ -309,7 +309,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
||||
->selectRaw('MAX(id)')
|
||||
->where('status', ContentVersionStatus::Bereit)
|
||||
->where('composition_id', '!=', $exceptCompositionId)
|
||||
->whereHas('composition', function ($builder) use ($query, $like, $kind, $dimensionId, $pillarId): void {
|
||||
->whereHas('composition', function ($builder) use ($query, $like, $kind, $dimensionId): void {
|
||||
if ($kind === 'modul') {
|
||||
$builder->where('kind', CompositionKind::Uebung);
|
||||
}
|
||||
@@ -318,10 +318,6 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
||||
$builder->whereIn('id', $this->dimensionSubjectIds(Composition::class, $dimensionId));
|
||||
}
|
||||
|
||||
if ($pillarId > 0) {
|
||||
$builder->whereIn('id', $this->pillarSubjectIds(Composition::class, $pillarId));
|
||||
}
|
||||
|
||||
if ($query === '') {
|
||||
return;
|
||||
}
|
||||
@@ -374,10 +370,6 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($pillarId > 0 && ! in_array($composition->id, $this->pillarSubjectIds(Composition::class, $pillarId), true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$title = $this->compositionTitle($composition);
|
||||
|
||||
if ($query !== '' && ! str_contains(mb_strtolower($title.' '.(string) ($composition->summary ?? '')), mb_strtolower($query))) {
|
||||
@@ -572,7 +564,7 @@ private function withVisibility(array $rows): array
|
||||
/**
|
||||
* @param Builder<ContentElement> $builder
|
||||
*/
|
||||
private function constrainElement($builder, string $query, string $like, string $kind, int $dimensionId, int $pillarId = 0): void
|
||||
private function constrainElement($builder, string $query, string $like, string $kind, int $dimensionId): void
|
||||
{
|
||||
$outputs = match ($kind) {
|
||||
'film' => ['film'],
|
||||
@@ -591,10 +583,6 @@ private function constrainElement($builder, string $query, string $like, string
|
||||
$builder->whereIn('id', $this->dimensionSubjectIds(ContentElement::class, $dimensionId));
|
||||
}
|
||||
|
||||
if ($pillarId > 0) {
|
||||
$builder->whereIn('id', $this->pillarSubjectIds(ContentElement::class, $pillarId));
|
||||
}
|
||||
|
||||
if ($query === '') {
|
||||
return;
|
||||
}
|
||||
@@ -609,22 +597,6 @@ private function constrainElement($builder, string $query, string $like, string
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Direkt einer Säule zugeordnete Medien oder Module und Programme (zentrale Säulenverwaltung).
|
||||
*
|
||||
* @param class-string<Model> $class
|
||||
* @return list<int>
|
||||
*/
|
||||
private function pillarSubjectIds(string $class, int $pillarId): array
|
||||
{
|
||||
[$table, $column] = $class === Composition::class
|
||||
? ['composition_pillar', 'composition_id']
|
||||
: ['content_element_pillar', 'content_element_id'];
|
||||
|
||||
return DB::table($table)->where('pillar_id', $pillarId)->pluck($column)
|
||||
->map(fn (mixed $id): int => (int) $id)->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param class-string<Model> $class
|
||||
* @return list<int>
|
||||
|
||||
@@ -7,12 +7,9 @@
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
use App\Domain\Catalog\Pillar;
|
||||
use App\Domain\Catalog\PillarFilterCompat;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Livewire\Attributes\Url;
|
||||
|
||||
/**
|
||||
@@ -32,10 +29,6 @@ trait ListsCompositions
|
||||
#[Url]
|
||||
public string $pillar = '';
|
||||
|
||||
/** Fachliche Säule (zentrale Säulenverwaltung), direkt zugeordnet. */
|
||||
#[Url(as: 'saeule', except: '')]
|
||||
public string $saeule = '';
|
||||
|
||||
#[Url]
|
||||
public string $visibility = 'alle';
|
||||
|
||||
@@ -46,7 +39,7 @@ protected function fixedKind(): ?CompositionKind
|
||||
|
||||
protected function bestandFilterEigenschaften(): array
|
||||
{
|
||||
return ['query', 'kindFilter', 'pillar', 'saeule', 'visibility'];
|
||||
return ['query', 'kindFilter', 'pillar', 'visibility'];
|
||||
}
|
||||
|
||||
public function resetFilters(): void
|
||||
@@ -54,14 +47,13 @@ public function resetFilters(): void
|
||||
$this->query = '';
|
||||
$this->kindFilter = 'alle';
|
||||
$this->pillar = '';
|
||||
$this->saeule = '';
|
||||
$this->visibility = 'alle';
|
||||
$this->bestandGrenze = Bestand::SCHRITT;
|
||||
}
|
||||
|
||||
public function hasActiveFilters(): bool
|
||||
{
|
||||
return trim($this->query) !== '' || $this->kindFilter !== 'alle' || $this->pillar !== '' || $this->saeule !== '' || $this->visibility !== 'alle';
|
||||
return trim($this->query) !== '' || $this->kindFilter !== 'alle' || $this->pillar !== '' || $this->visibility !== 'alle';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,7 +61,6 @@ public function hasActiveFilters(): bool
|
||||
*/
|
||||
public function bestand(): array
|
||||
{
|
||||
$this->normalizeLegacyPillarFilter();
|
||||
$fixed = $this->fixedKind();
|
||||
$einheit = match ($fixed) {
|
||||
CompositionKind::Kurs => ['Programm', 'Programme'],
|
||||
@@ -99,14 +90,9 @@ public function bestand(): array
|
||||
'eigenschaft' => 'visibility', 'label' => 'Stand', 'vorgabe' => 'alle',
|
||||
'optionen' => ['alle' => 'Jeder Stand', 'bibliothek' => 'In der Mitgliederbibliothek', 'verborgen' => 'Nicht in der Mitgliederbibliothek', 'entwurf' => 'Noch ohne Fassung'],
|
||||
]],
|
||||
'weitere' => [
|
||||
...($this->pillarOptions() === [] ? [] : [[
|
||||
'eigenschaft' => 'saeule', 'label' => 'Fachliche Säule', 'vorgabe' => '', 'alle' => 'Alle Säulen', 'optionen' => $this->pillarOptions(),
|
||||
]]),
|
||||
...($gruppen === [] ? [] : [[
|
||||
'eigenschaft' => 'pillar', 'label' => 'Fachliche Einordnung', 'vorgabe' => '', 'alle' => 'Alle Einordnungen', 'gruppen' => $gruppen,
|
||||
]]),
|
||||
],
|
||||
'weitere' => $gruppen === [] ? [] : [[
|
||||
'eigenschaft' => 'pillar', 'label' => 'Fachliche Einordnung', 'vorgabe' => '', 'alle' => 'Alle Einordnungen', 'gruppen' => $gruppen,
|
||||
]],
|
||||
'zeilen' => $this->entries(),
|
||||
'einheit' => $einheit,
|
||||
'leer' => [
|
||||
@@ -138,9 +124,7 @@ public function entries(): array
|
||||
$needle = mb_strtolower(trim($this->query));
|
||||
$catalog = app(EditorialCatalog::class);
|
||||
$offered = $catalog->offeredCompositionIds();
|
||||
$this->normalizeLegacyPillarFilter();
|
||||
$pillarIds = $this->pillar === '' ? null : $this->pillarSubjects((int) $this->pillar);
|
||||
$saeuleIds = ctype_digit($this->saeule) && $this->saeule !== '' ? $this->saeuleSubjects((int) $this->saeule) : null;
|
||||
$fixed = $this->fixedKind();
|
||||
$kinds = $fixed !== null ? [$fixed] : match ($this->kindFilter) {
|
||||
'programm' => [CompositionKind::Kurs],
|
||||
@@ -165,10 +149,6 @@ public function entries(): array
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($saeuleIds !== null && ! in_array($composition->id, $saeuleIds, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$stand = $catalog->stand($composition);
|
||||
|
||||
if (! $this->matchesVisibility($stand)) {
|
||||
@@ -269,36 +249,6 @@ private function coverMembers(Composition $composition): array
|
||||
return $members;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alte Adressen mit einem Säulenwert der Einordnung (`?pillar=…`) gelten für die zentrale Säule.
|
||||
*/
|
||||
private function normalizeLegacyPillarFilter(): void
|
||||
{
|
||||
if (ctype_digit($this->pillar) && $this->pillar !== '' && $this->saeule === '' && is_int($pillar = PillarFilterCompat::pillarOfLegacyValue((int) $this->pillar))) {
|
||||
[$this->saeule, $this->pillar] = [(string) $pillar, ''];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function pillarOptions(): array
|
||||
{
|
||||
return Pillar::query()->orderBy('sort_order')->orderBy('name')->pluck('name', 'id')
|
||||
->mapWithKeys(fn (string $name, int|string $id): array => [(string) $id => $name])->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Direkt zugeordnete Module und Programme einer Säule. Die Säulen der enthaltenen Medien zählen hier nicht.
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
private function saeuleSubjects(int $pillarId): array
|
||||
{
|
||||
return DB::table('composition_pillar')->where('pillar_id', $pillarId)->pluck('composition_id')
|
||||
->map(fn (mixed $id): int => (int) $id)->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<int>
|
||||
*/
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
use App\Domain\Catalog\Pillar;
|
||||
use App\Domain\Catalog\PillarFilterCompat;
|
||||
use App\Domain\Catalog\ReleaseContent;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
@@ -133,23 +132,15 @@ public function cards(array $filters, bool $canEdit): array
|
||||
*/
|
||||
private function normalize(array $filters): array
|
||||
{
|
||||
$saeule = ctype_digit($filters['saeule'] ?? '') ? $filters['saeule'] : '';
|
||||
$einordnung = ctype_digit($filters['einordnung'] ?? '') ? $filters['einordnung'] : '';
|
||||
|
||||
if ($einordnung !== '' && $saeule === '' && is_int($pillar = PillarFilterCompat::pillarOfLegacyValue((int) $einordnung))) {
|
||||
[$saeule, $einordnung] = [(string) $pillar, ''];
|
||||
}
|
||||
|
||||
return [
|
||||
'suche' => trim($filters['suche'] ?? ''),
|
||||
'art' => $this->choice($filters['art'] ?? '', ['film', 'text', 'document', 'bild', 'audio']),
|
||||
'freigabe' => $this->choice($filters['freigabe'] ?? '', ['freigegeben', 'entwurf', 'ohne']),
|
||||
'schutz' => $this->choice($filters['schutz'] ?? '', ['geschuetzt', 'oeffentlich', 'website']),
|
||||
'entwurf' => $this->choice($filters['entwurf'] ?? '', ['offen', 'keiner']),
|
||||
'fassung' => $this->choice($filters['fassung'] ?? '', ['mit', 'nur']),
|
||||
'nutzung' => $this->choice($filters['nutzung'] ?? '', ['verwendet', 'unbenutzt']),
|
||||
'saeule' => $saeule,
|
||||
'einordnung' => $einordnung,
|
||||
'saeule' => ctype_digit($filters['saeule'] ?? '') ? $filters['saeule'] : '',
|
||||
'einordnung' => ctype_digit($filters['einordnung'] ?? '') ? $filters['einordnung'] : '',
|
||||
'inhaltsart' => ctype_digit($filters['inhaltsart'] ?? '') ? $filters['inhaltsart'] : '',
|
||||
'verarbeitung' => $this->choice($filters['verarbeitung'] ?? '', ['fehler', 'uebernahme']),
|
||||
'archiv' => $this->choice($filters['archiv'] ?? '', ['aktiv', 'archiviert', 'alle'], 'aktiv'),
|
||||
@@ -384,20 +375,6 @@ private function matches(ContentElement $element, array $portrait, array $uses,
|
||||
return false;
|
||||
}
|
||||
|
||||
$presentation = $this->isPresentationMedium($element, $portrait['versionCount']);
|
||||
|
||||
if ($filters['schutz'] === 'geschuetzt' && $presentation) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($filters['schutz'] === 'oeffentlich' && ! $presentation) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($filters['schutz'] === 'website' && $element->website_released_at === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($filters['freigabe'] === 'freigegeben' && $portrait['ready'] === null) {
|
||||
return false;
|
||||
}
|
||||
@@ -459,15 +436,6 @@ private function matches(ContentElement $element, array $portrait, array $uses,
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Eigenständiges Präsentationsmedium: Bild, Film oder Hörstück ohne Inhaltsfassung. Es ist für die Website
|
||||
* bestimmt und nicht lizenziert; alles mit einer Inhaltsfassung gilt als geschützt.
|
||||
*/
|
||||
private function isPresentationMedium(ContentElement $element, int $versionCount): bool
|
||||
{
|
||||
return $versionCount === 0 && in_array($element->output_class, ['bild', 'film', 'audio'], true);
|
||||
}
|
||||
|
||||
private function matchesArt(ContentElement $element, string $art): bool
|
||||
{
|
||||
if ($art === '') {
|
||||
@@ -522,8 +490,6 @@ private function card(ContentElement $element, array $portrait, array $uses, arr
|
||||
'image' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
|
||||
'imageAlt' => trim((string) ($element->thumbnail_alt ?: $element->working_title)),
|
||||
'imageNote' => $this->imageNote($element),
|
||||
'presentation' => $this->isPresentationMedium($element, $portrait['versionCount']),
|
||||
'websiteReleased' => $element->website_released_at !== null,
|
||||
'stand' => $portrait['stand'],
|
||||
'standTone' => $portrait['standTone'],
|
||||
'draftNote' => $portrait['draftNote'],
|
||||
|
||||
@@ -43,7 +43,7 @@ public static function fields(bool $creating, ?ContentElement $element = null):
|
||||
->required(fn ($get): bool => filled($get('shape')) && $get('shape') !== 'text');
|
||||
$fields[] = Checkbox::make('without_version')
|
||||
->label('Eigenständiges Präsentationsmedium')
|
||||
->helperText('Bild, Film oder Hörstück ohne fachliche Inhaltsfassung, zum Beispiel ein Trailer, der ungeschützt auf der Website laufen soll. Der Film muss dafür MP4 (H.264) oder WebM sein. Er wird nicht lizenziert und erst nach „Für die Website freigeben“ öffentlich.')
|
||||
->helperText('Bild, Film oder Hörstück ohne fachliche Inhaltsfassung. Die Datei bleibt eine technische Ableitung am Medium. Sie wird nicht lizenziert und nicht automatisch für die Website freigegeben.')
|
||||
->visible(fn ($get): bool => in_array($get('shape'), ['film', 'audio', 'bild'], true));
|
||||
} elseif ($element?->output_class === 'text') {
|
||||
$fields[] = Textarea::make('body')->label('Text')->rows(8)->required();
|
||||
@@ -94,10 +94,20 @@ public static function create(array $data, bool $hold): ContentElement
|
||||
{
|
||||
$service = app(ContentService::class);
|
||||
[$kind, $output] = self::shape($data['shape'] ?? null);
|
||||
$incoming = null;
|
||||
$element = $service->createElement($kind, $output, (string) $data['working_title']);
|
||||
self::remember($element, $data);
|
||||
|
||||
if ($output !== 'text') {
|
||||
// Alles prüfen, bevor etwas angelegt wird: Eine abgelehnte Datei darf kein leeres Medium hinterlassen.
|
||||
if ($output === 'text') {
|
||||
$body = trim((string) ($data['body'] ?? ''));
|
||||
|
||||
if ($body === '') {
|
||||
throw new DomainRuleException('Der Text braucht einen Inhalt.');
|
||||
}
|
||||
|
||||
$hold
|
||||
? $service->draftElementVersion($element, $body)
|
||||
: $service->publishElementVersion($element, $body);
|
||||
} else {
|
||||
$incoming = IncomingFile::store($data['incoming'] ?? null);
|
||||
|
||||
if ($incoming === null) {
|
||||
@@ -116,25 +126,6 @@ public static function create(array $data, bool $hold): ContentElement
|
||||
throw new DomainRuleException('Diese Datei passt nicht zur gewählten Art.');
|
||||
}
|
||||
|
||||
if (! empty($data['without_version']) && in_array($output, ['bild', 'film', 'audio'], true)) {
|
||||
app(PresentationFile::class)->validate($output, $incoming);
|
||||
}
|
||||
}
|
||||
|
||||
$element = $service->createElement($kind, $output, (string) $data['working_title']);
|
||||
self::remember($element, $data);
|
||||
|
||||
if ($output === 'text') {
|
||||
$body = trim((string) ($data['body'] ?? ''));
|
||||
|
||||
if ($body === '') {
|
||||
throw new DomainRuleException('Der Text braucht einen Inhalt.');
|
||||
}
|
||||
|
||||
$hold
|
||||
? $service->draftElementVersion($element, $body)
|
||||
: $service->publishElementVersion($element, $body);
|
||||
} else {
|
||||
if (! empty($data['without_version']) && in_array($output, ['bild', 'film', 'audio'], true)) {
|
||||
app(PresentationFile::class)->store($element, $incoming);
|
||||
} else {
|
||||
|
||||
@@ -1,337 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Catalog\ArticleRelease;
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\BundleService;
|
||||
use App\Domain\Catalog\BundleStatus;
|
||||
use App\Domain\Catalog\BundleVersion;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Catalog\ReleaseStatus;
|
||||
use App\Domain\Catalog\StatusValue;
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\ProductOptions;
|
||||
use App\Filament\Resources\LicenseArticles\LicenseArticleResource;
|
||||
use App\Filament\Resources\Offers\OfferResource;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Voraussetzungen bis zur Veröffentlichung für Lizenzartikel, Paket und Angebot in einer gemeinsamen Form
|
||||
* (Verwaltungsstandard 14, Abschnitt 9: eine Komponente für gleiche Aufgaben). Die Klasse liest nur; sie ändert keine
|
||||
* fachliche Regel. Jeder Schritt nennt, was fehlt, und bietet den Weg dorthin an.
|
||||
*
|
||||
* Schritt: ['titel', 'text', 'stand' => erledigt|offen|optional, 'aktion' => ['label', 'wire'|'href']|null]
|
||||
* Ergebnis: ['schritte', 'bereit' (alle Pflichtschritte erledigt), 'naechster' (Text des ersten offenen Pflichtschritts)].
|
||||
*/
|
||||
class PublicationReadiness
|
||||
{
|
||||
public function __construct(
|
||||
private readonly BundleService $bundles,
|
||||
private readonly OfferService $offers,
|
||||
private readonly PublicCatalogReader $catalog,
|
||||
) {}
|
||||
|
||||
/** Ein Artikel ist verwendbar, wenn sein aktueller Stand veröffentlicht ist. */
|
||||
public function articleUsable(LicenseArticle $article): bool
|
||||
{
|
||||
$release = $article->currentRelease;
|
||||
|
||||
return $release instanceof ArticleRelease && StatusValue::of($release->status) === ReleaseStatus::Veroeffentlicht->value;
|
||||
}
|
||||
|
||||
/** Anzeige in Auswahllisten: Name, Kennung und Stand statt der bloßen Kennung. */
|
||||
public function articleLabel(LicenseArticle $article): string
|
||||
{
|
||||
$title = $this->articleName($article);
|
||||
$name = $title !== '' ? $title.' ('.$article->code.')' : (string) $article->code;
|
||||
$release = $article->currentRelease;
|
||||
|
||||
if ($this->articleUsable($article)) {
|
||||
return $name.' · Stand '.$release->number;
|
||||
}
|
||||
|
||||
return $name.' · '.($release === null ? 'noch ohne Stand, nicht verwendbar' : 'Stand gesperrt, nicht verwendbar');
|
||||
}
|
||||
|
||||
/** Name wie in der Redaktion: eigener Name oder Name des Inhalts, sonst der Arbeitstitel; leer ohne beides. */
|
||||
public function articleName(LicenseArticle $article): string
|
||||
{
|
||||
return app(ProductOptions::class)->articleName($article);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function articleOptions(): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (LicenseArticle::query()->with('currentRelease')->orderBy('code')->get() as $article) {
|
||||
$options[$article->id] = $this->articleLabel($article);
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Veröffentlichte Paketfassungen mit ihren Artikeln, damit die Auswahl zeigt, was verkauft wird.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function bundleVersionOptions(): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (BundleVersion::query()->where('status', BundleStatus::Veroeffentlicht)->with('bundle')->orderBy('id')->get() as $version) {
|
||||
try {
|
||||
$codes = LicenseArticle::query()->whereIn('id', $this->bundles->articleIds($version))->orderBy('code')->pluck('code')->all();
|
||||
} catch (DomainRuleException) {
|
||||
$codes = [];
|
||||
}
|
||||
|
||||
$options[$version->id] = $version->bundle->name.' · Fassung '.$version->number.' ('.($codes === [] ? 'ohne Artikel' : implode(', ', $codes)).')';
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Artikel einer Auswahl, die keinen verwendbaren Stand haben.
|
||||
*
|
||||
* @param list<int> $articleIds
|
||||
* @return list<LicenseArticle>
|
||||
*/
|
||||
public function unusableArticles(array $articleIds): array
|
||||
{
|
||||
return LicenseArticle::query()->with('currentRelease')->whereIn('id', array_unique($articleIds))->orderBy('code')->get()
|
||||
->reject(fn (LicenseArticle $article): bool => $this->articleUsable($article))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<LicenseArticle> $articles
|
||||
*/
|
||||
public function unusableMessage(array $articles, string $zweck): string
|
||||
{
|
||||
$namen = implode(', ', array_map(fn (LicenseArticle $article): string => '„'.($this->articleName($article) ?: $article->code).'“ ('.$article->code.')', $articles));
|
||||
|
||||
return (count($articles) === 1 ? 'Der Lizenzartikel ' : 'Die Lizenzartikel ').$namen
|
||||
.(count($articles) === 1 ? ' hat' : ' haben')
|
||||
.' noch keinen veröffentlichten Stand und vergibt'.(count($articles) === 1 ? '' : ' keine').' keine Inhalte. '
|
||||
.'Lege zuerst am Artikel mit „Inhalt festlegen“ den Inhalt fest, bevor du '.$zweck.'.';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function forArticle(LicenseArticle $article): array
|
||||
{
|
||||
$article->loadMissing('currentRelease');
|
||||
$usable = $this->articleUsable($article);
|
||||
$release = $article->currentRelease;
|
||||
$inUse = $this->articleInUse($article);
|
||||
|
||||
return $this->result([
|
||||
[
|
||||
'titel' => 'Inhalt festlegen',
|
||||
'text' => $usable
|
||||
? 'Stand '.$release->number.' ist veröffentlicht und bestimmt, welche Inhalte der Artikel lizenziert.'
|
||||
: 'Der Artikel lizenziert noch nichts. Wähle den freigegebenen Inhalt (Medium, Modul oder Programm), den er umfassen soll.',
|
||||
'stand' => $usable ? 'erledigt' : 'offen',
|
||||
'aktion' => $usable ? null : ['label' => 'Inhalt festlegen', 'wire' => "mountAction('release')"],
|
||||
],
|
||||
[
|
||||
'titel' => 'Name und Beschreibung',
|
||||
'text' => $this->articleName($article) !== ''
|
||||
? 'Der Name „'.$this->articleName($article).'“ erscheint in Paketen, Angeboten, im Shop und in der Bibliothek.'
|
||||
: 'Ohne Name erscheint die Kennung „'.$article->code.'“. Name, Teaser und Beschreibung pflegst du in der Redaktion.',
|
||||
'stand' => $this->articleName($article) !== '' ? 'erledigt' : 'optional',
|
||||
'aktion' => $this->articleName($article) !== '' ? null : ['label' => 'Redaktion bearbeiten', 'wire' => "openRedaktion('texte')"],
|
||||
],
|
||||
[
|
||||
'titel' => 'In einem Paket oder Angebot verwenden',
|
||||
'text' => $inUse
|
||||
? 'Der Artikel ist in einem Paket oder Angebot enthalten.'
|
||||
: 'Verkauft wird der Artikel erst über ein Angebot, allein oder in einem Paket.',
|
||||
'stand' => $inUse ? 'erledigt' : 'offen',
|
||||
'aktion' => $inUse ? null : ['label' => 'Angebote öffnen', 'href' => OfferResource::getUrl('index')],
|
||||
'pflicht' => false,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function forBundle(Bundle $bundle): array
|
||||
{
|
||||
$published = $bundle->versions()->where('status', BundleStatus::Veroeffentlicht)->orderByDesc('number')->first();
|
||||
$missing = [];
|
||||
|
||||
if ($published instanceof BundleVersion) {
|
||||
try {
|
||||
$missing = $this->unusableArticles($this->bundles->articleIds($published));
|
||||
} catch (DomainRuleException) {
|
||||
$missing = [];
|
||||
}
|
||||
}
|
||||
|
||||
$offered = $published instanceof BundleVersion && $this->bundleOffered($bundle);
|
||||
|
||||
return $this->result([
|
||||
[
|
||||
'titel' => 'Bestandteile festlegen',
|
||||
'text' => $published instanceof BundleVersion
|
||||
? 'Fassung '.$published->number.' ist veröffentlicht und unveränderlich.'
|
||||
: 'Wähle die Lizenzartikel und Pakete, die zusammen verkauft werden, und veröffentliche die Fassung.',
|
||||
'stand' => $published instanceof BundleVersion ? 'erledigt' : 'offen',
|
||||
'aktion' => $published instanceof BundleVersion ? null : ['label' => 'Bestandteile festlegen', 'wire' => "mountAction('publish')"],
|
||||
],
|
||||
[
|
||||
'titel' => 'Jeder enthaltene Artikel hat einen Inhalt',
|
||||
'text' => ! $published instanceof BundleVersion
|
||||
? 'Wird geprüft, sobald die Bestandteile feststehen.'
|
||||
: ($missing === []
|
||||
? 'Alle enthaltenen Artikel haben einen veröffentlichten Stand.'
|
||||
: 'Ohne Stand und damit ohne Inhalt: '.implode(', ', array_map(fn (LicenseArticle $article): string => (string) $article->code, $missing)).'. Ein Angebot lässt sich erst aktivieren, wenn jeder Artikel einen Stand hat.'),
|
||||
'stand' => $published instanceof BundleVersion && $missing === [] ? 'erledigt' : 'offen',
|
||||
'aktion' => $missing === [] ? null : ['label' => 'Artikel „'.$missing[0]->code.'“ öffnen', 'href' => LicenseArticleResource::getUrl('view', ['record' => $missing[0]])],
|
||||
],
|
||||
[
|
||||
'titel' => 'Angebot mit Preis und Rechten',
|
||||
'text' => $offered
|
||||
? 'Ein aktives Angebot verkauft dieses Paket.'
|
||||
: 'Verkauft wird das Paket erst über ein Angebot. Dort wählst du die Paketfassung, die Rechte und den Preis.',
|
||||
'stand' => $offered ? 'erledigt' : 'offen',
|
||||
'aktion' => $offered ? null : ['label' => 'Angebote öffnen', 'href' => OfferResource::getUrl('index')],
|
||||
'pflicht' => false,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function forOffer(Offer $offer): array
|
||||
{
|
||||
$active = $offer->versions()->where('status', 'aktiv')->orderByDesc('number')->first();
|
||||
$hasActive = $active instanceof OfferVersion;
|
||||
$articleIds = $hasActive ? $active->resolvedScopes()->pluck('license_article_id')->map(fn ($id): int => (int) $id)->all() : [];
|
||||
$missing = $this->unusableArticles($articleIds);
|
||||
$buyable = $hasActive && $this->offers->purchasableVersion($offer) !== null;
|
||||
$page = $offer->composition;
|
||||
$own = (bool) $offer->standalone_bundle;
|
||||
$shown = $own || ($page !== null && $this->catalog->shownVersion($page) !== null);
|
||||
$pageName = $page !== null ? (string) ($page->display_title ?: $page->designation) : '';
|
||||
$activate = ['label' => $hasActive ? 'Geänderte Fassung aktivieren' : 'Angebot konfigurieren', 'wire' => "mountAction('activate')"];
|
||||
|
||||
return $this->result([
|
||||
[
|
||||
'titel' => 'Artikel oder Paket, Rechte, Preis und Vergabe festlegen',
|
||||
'text' => $hasActive
|
||||
? 'Fassung '.$active->number.' ist aktiv.'
|
||||
: 'Wähle, was verkauft wird (Lizenzartikel oder Paketfassung), welche Nutzungsrechte dazugehören, für wen es gilt und was es kostet. Erst „Fassung aktivieren“ macht das Angebot gültig.',
|
||||
'stand' => $hasActive ? 'erledigt' : 'offen',
|
||||
'aktion' => $hasActive ? null : $activate,
|
||||
],
|
||||
[
|
||||
'titel' => 'Inhalt vorhanden',
|
||||
'text' => ! $hasActive
|
||||
? 'Wird geprüft, sobald die Fassung aktiv ist.'
|
||||
: ($missing === []
|
||||
? 'Jeder enthaltene Lizenzartikel hat einen veröffentlichten Stand.'
|
||||
: 'Ohne Stand und damit ohne Inhalt: '.implode(', ', array_map(fn (LicenseArticle $article): string => (string) $article->code, $missing)).'. Käufer würden nichts erhalten.'),
|
||||
'stand' => $hasActive && $missing === [] ? 'erledigt' : 'offen',
|
||||
'aktion' => $missing === [] ? null : ['label' => 'Artikel „'.$missing[0]->code.'“ öffnen', 'href' => LicenseArticleResource::getUrl('view', ['record' => $missing[0]])],
|
||||
],
|
||||
[
|
||||
'titel' => 'Als Kauf mit Preis angeboten',
|
||||
'text' => $buyable
|
||||
? 'Die aktive Fassung ist ein Kauf zu '.Money::format((int) $active->price_cents).'.'
|
||||
: ($hasActive ? 'Die aktive Fassung ist kein Kauf mit Preis (Vergabe: '.CatalogLabels::vergabe($active).'). Im Shop erscheinen nur Käufe.' : 'Wird mit der Fassung festgelegt.'),
|
||||
'stand' => $buyable ? 'erledigt' : 'offen',
|
||||
'aktion' => $buyable ? null : ($hasActive ? $activate : null),
|
||||
],
|
||||
[
|
||||
'titel' => 'Nutzerkreis festlegen',
|
||||
'text' => ! $hasActive
|
||||
? 'Wird mit der Fassung festgelegt: Einzellizenz (ein Trainer) oder Mehrfachlizenz (Zahl der Trainer).'
|
||||
: ($active->licence_scope !== null
|
||||
? LicenceScope::label($active->licence_scope, $active->trainer_count).'. Der Käufer sieht das auf der Produktseite und in der Bestellung.'
|
||||
: 'Diese Fassung hat keinen festgelegten Nutzerkreis. Käufer sehen „Nutzerkreis nicht festgelegt“. Lege ihn mit „Geänderte Fassung aktivieren“ fest.'),
|
||||
'stand' => $hasActive && $active->licence_scope !== null ? 'erledigt' : 'offen',
|
||||
'aktion' => $hasActive && $active->licence_scope === null ? $activate : null,
|
||||
'pflicht' => false,
|
||||
],
|
||||
[
|
||||
'titel' => 'Produktseite zuordnen',
|
||||
'text' => $own
|
||||
? 'Eigene Paketseite: Sie zeigt den Umfang des Pakets. Optionen desselben Pakets sind Alternativen im Warenkorb.'
|
||||
: ($page !== null
|
||||
? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.'
|
||||
: 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket, das für sich verkauft wird, erhält dort „Eigene Paketseite“ und zeigt seinen Umfang; sonst erscheint es auf der Seite eines fremden Programms.'),
|
||||
'stand' => $own || $page !== null ? 'erledigt' : 'offen',
|
||||
'aktion' => $own || $page !== null ? null : $activate,
|
||||
],
|
||||
[
|
||||
'titel' => 'Produktseite öffentlich',
|
||||
'text' => ! $own && $page === null
|
||||
? 'Wird geprüft, sobald eine Produktseite zugeordnet ist.'
|
||||
: ($own
|
||||
? 'Die eigene Paketseite ist öffentlich, sobald die aktive Fassung ein Kauf mit Preis ist.'
|
||||
: ($shown
|
||||
? 'Das Programm ist zur Anzeige freigegeben. Das Angebot erscheint in der Shop-Suche und auf der Produktseite.'
|
||||
: 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.')),
|
||||
'stand' => $shown ? 'erledigt' : 'offen',
|
||||
'aktion' => $page === null || $shown ? null : ['label' => 'Programm öffnen', 'href' => EditorialCatalog::editUrl($page)],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $schritte
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function result(array $schritte): array
|
||||
{
|
||||
$schritte = array_map(fn (array $schritt): array => ['pflicht' => true, 'aktion' => null, ...$schritt], $schritte);
|
||||
$naechster = null;
|
||||
|
||||
foreach ($schritte as $schritt) {
|
||||
if ($schritt['pflicht'] && $schritt['stand'] === 'offen') {
|
||||
$naechster = $schritt;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'schritte' => $schritte,
|
||||
'bereit' => $naechster === null,
|
||||
'naechster' => $naechster,
|
||||
];
|
||||
}
|
||||
|
||||
private function articleInUse(LicenseArticle $article): bool
|
||||
{
|
||||
return DB::table('offer_lines')->where('license_article_id', $article->id)->exists()
|
||||
|| DB::table('bundle_items')->where('license_article_id', $article->id)->exists();
|
||||
}
|
||||
|
||||
private function bundleOffered(Bundle $bundle): bool
|
||||
{
|
||||
return DB::table('offer_lines')
|
||||
->join('offer_versions', 'offer_versions.id', '=', 'offer_lines.offer_version_id')
|
||||
->join('bundle_versions', 'bundle_versions.id', '=', 'offer_lines.bundle_version_id')
|
||||
->where('bundle_versions.bundle_id', $bundle->id)
|
||||
->where('offer_versions.status', 'aktiv')
|
||||
->exists();
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Identity\StaffRole;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
|
||||
/**
|
||||
* Wer Rabattcodes, Freigaben und Bestellungen verwalten darf: Katalogverwalter und Kundenbetreuung. Die
|
||||
* Berechtigung zum Verkaufen und Erstatten ist eine Betreiberaufgabe, nicht die der Redaktion.
|
||||
*/
|
||||
final class ShopAccess
|
||||
{
|
||||
public static function allowed(): bool
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
return $user instanceof User
|
||||
&& ($user->hasStaffRole(StaffRole::Katalogverwalter) || $user->hasStaffRole(StaffRole::Kundenbetreuung));
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@
|
||||
use App\Domain\Cms\Widgets\WidgetRegistry;
|
||||
use App\Domain\Cms\Widgets\WidgetRenderer;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use App\Domain\Design\DesignSettings;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Builder;
|
||||
use Filament\Forms\Components\Builder\Block;
|
||||
@@ -17,7 +16,6 @@
|
||||
use Filament\Forms\Components\ToggleButtons;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Schemas\Components\Grid;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Tabs;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
@@ -122,92 +120,45 @@ public static function slotBuilder(string $name = 'widget'): Builder
|
||||
->columnSpanFull();
|
||||
}
|
||||
|
||||
/**
|
||||
* Erklärung als kleines (i) neben der Bezeichnung: erscheint beim Überfahren und beim Fokussieren.
|
||||
*/
|
||||
private static function withInfo(ToggleButtons|Select $component, ?string $help): ToggleButtons|Select
|
||||
{
|
||||
return filled($help)
|
||||
? $component->hintIcon('heroicon-m-information-circle', tooltip: $help)->hintColor('gray')
|
||||
: $component;
|
||||
}
|
||||
|
||||
public static function block(WidgetType $type): Block
|
||||
{
|
||||
$icons = $type->optionIcons();
|
||||
$display = [];
|
||||
|
||||
// Aufbau: Anordnung (Variante) und gemeinsame Höhe. Erklärungen stehen im (i) neben der Bezeichnung.
|
||||
$layout = [];
|
||||
if (count($type->variants()) > 1) {
|
||||
$layout[] = self::withInfo(ToggleButtons::make('variant')
|
||||
->label('Anordnung')
|
||||
$display[] = ToggleButtons::make('variant')
|
||||
->label('Darstellung')
|
||||
->options($type->variants())
|
||||
->icons($icons['variant'] ?? [])
|
||||
->default($type->defaultVariant())
|
||||
->inline()
|
||||
->required()
|
||||
->live(), 'Wie Bild und Text zueinander stehen. Bei wenig Platz stellt sich jede Anordnung selbständig um; die gespeicherte Seite bleibt erhalten.');
|
||||
->live();
|
||||
}
|
||||
|
||||
$options = $type->settingOptions();
|
||||
$settings = [];
|
||||
$labels = $type->settingLabels();
|
||||
$hiddenWhen = $type->settingHiddenWhen();
|
||||
|
||||
$field = function (string $key) use ($options, $labels, $type, $icons, $hiddenWhen): Select|ToggleButtons {
|
||||
$help = $labels[$key][1] ?? null;
|
||||
foreach ($type->settingOptions() as $key => $options) {
|
||||
// Gemeinsame Höhe (ADR-38): immer als sichtbare Auswahl mit Vorgabe, nie als freie Eingabe.
|
||||
$component = $key === 'height'
|
||||
$settings[] = $key === 'height'
|
||||
? ToggleButtons::make('height')
|
||||
->label('Höhe')
|
||||
->options($options['height'])
|
||||
->helperText('Gestaltungsparameter, keine Begrenzung: Längere Inhalte erhalten immer den nötigen Platz.')
|
||||
->options($options)
|
||||
->icons($icons['height'] ?? [])
|
||||
->default($type->defaultHeight())
|
||||
->inline()
|
||||
->live()
|
||||
: Select::make($key)
|
||||
->label($labels[$key][0] ?? Str::headline($key))
|
||||
->helperText($labels[$key][1] ?? null)
|
||||
->placeholder('Vorgabe der Darstellung')
|
||||
->options($options[$key])
|
||||
->options($options)
|
||||
->live();
|
||||
|
||||
if ($key === 'height') {
|
||||
$help = 'Gestaltungsparameter, keine Begrenzung: Längere Inhalte erhalten immer den nötigen Platz.';
|
||||
}
|
||||
|
||||
if (isset($hiddenWhen[$key])) {
|
||||
[$controller, $value] = $hiddenWhen[$key];
|
||||
// Ausgeblendete Werte bleiben gespeichert, damit ein späteres Einblenden nichts zurücksetzt.
|
||||
$component->hidden(fn (Get $get): bool => ($get($controller) ?? null) === $value)->dehydratedWhenHidden();
|
||||
}
|
||||
|
||||
return self::withInfo($component, $help);
|
||||
};
|
||||
|
||||
if (isset($options['height'])) {
|
||||
$layout[] = Group::make([$field('height')])->statePath('settings');
|
||||
}
|
||||
|
||||
if ($layout !== []) {
|
||||
$display[] = Section::make('Aufbau')->compact()->schema($layout);
|
||||
}
|
||||
|
||||
$grouped = [];
|
||||
foreach ($type->settingGroups() as $title => $keys) {
|
||||
$keys = array_values(array_filter($keys, fn (string $key): bool => isset($options[$key]) && $key !== 'height'));
|
||||
$grouped = [...$grouped, ...$keys];
|
||||
if ($keys !== []) {
|
||||
$display[] = Section::make($title)->compact()->schema([
|
||||
Grid::make(['default' => 1, 'md' => 2])->schema(array_map($field, $keys))->statePath('settings'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$rest = array_values(array_filter(array_keys($options), fn (string $key): bool => $key !== 'height' && ! in_array($key, $grouped, true)));
|
||||
if ($rest !== []) {
|
||||
$display[] = Section::make($grouped === [] && $layout === [] ? 'Einstellungen' : 'Weitere Einstellungen')->compact()->schema([
|
||||
Grid::make(['default' => 1, 'md' => 2])->schema(array_map($field, $rest))->statePath('settings'),
|
||||
]);
|
||||
if ($settings !== []) {
|
||||
$display[] = Grid::make(['default' => 1, 'md' => 2])->schema($settings)->statePath('settings');
|
||||
}
|
||||
|
||||
$variantField = count($type->variants()) > 1 ? [] : [Hidden::make('variant')->default($type->defaultVariant())];
|
||||
@@ -475,7 +426,7 @@ public static function renderPreview(string $type, array $state): string
|
||||
public static function previewStylesheets(): string
|
||||
{
|
||||
try {
|
||||
return app(Vite::class)(['resources/css/app.css'])->toHtml().DesignSettings::styleTag()->toHtml();
|
||||
return app(Vite::class)(['resources/css/app.css'])->toHtml();
|
||||
} catch (Throwable) {
|
||||
return '';
|
||||
}
|
||||
|
||||
Loaded 100 of 612 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user