diff --git a/app/Domain/Cms/LinkTargets.php b/app/Domain/Cms/LinkTargets.php index 0052e1b..9f76dc1 100644 --- a/app/Domain/Cms/LinkTargets.php +++ b/app/Domain/Cms/LinkTargets.php @@ -23,7 +23,8 @@ public function pages(string $search = '', ?int $exceptId = null): array { $needle = mb_strtolower(trim($search)); - return Page::query()->with(['latestRevision', 'publishedRevision'])->orderBy('path')->get() + return Page::query()->with(['latestRevision', 'publishedRevision'])->get() + ->sort(fn (Page $a, Page $b): int => PagePath::compare($a->path, $b->path)) ->reject(fn (Page $page): bool => $page->getKey() === $exceptId) ->map(fn (Page $page): array => [ 'id' => (int) $page->getKey(), diff --git a/app/Domain/Cms/PageService.php b/app/Domain/Cms/PageService.php index 899dd8c..93545e7 100644 --- a/app/Domain/Cms/PageService.php +++ b/app/Domain/Cms/PageService.php @@ -7,10 +7,11 @@ use App\Models\User; use Illuminate\Support\Facades\Schema; use Illuminate\Validation\ValidationException; +use InvalidArgumentException; class PageService { - public function __construct(private readonly PageSections $sections) {} + public function __construct(private readonly PageSections $sections, private readonly ReservedPaths $reserved) {} /** * Speichert einen Entwurf als neue Revision. Veröffentlicht nichts. @@ -88,12 +89,20 @@ public function duplicate(Page $source, string $path, ?User $author): Page } /** - * Normalisiert den Pfad und prüft, dass keine andere Seite ihn verwendet. + * Normalisiert den Pfad und prüft, dass er keiner festen Funktion der Anwendung gehört und keine andere Seite ihn verwendet. */ public function availablePath(string $path, ?Page $except = null): string { $path = $this->normalizePath($path); + // Eine bestehende Seite mit unverändertem Pfad bleibt speicherbar, auch wenn ihr Pfad später reserviert wurde + // (sie ist dann nur nicht erreichbar); geprüft wird, wenn der Pfad neu vergeben oder geändert wird. + if ($except?->path !== $path && $this->reserved->blocks($path)) { + throw ValidationException::withMessages([ + 'path' => 'Diese Adresse gehört zu einer festen Funktion der Anwendung ('.PagePath::segments($path)[0].') und kann keine Seite sein.', + ]); + } + $taken = Page::query() ->where('path', $path) ->when($except !== null, fn ($query) => $query->whereKeyNot($except->getKey())) @@ -110,21 +119,26 @@ public function availablePath(string $path, ?Page $except = null): string public function normalizePath(string $path): string { - $path = '/'.trim($path, '/'); + try { + return PagePath::normalize($path); + } catch (InvalidArgumentException $exception) { + throw ValidationException::withMessages(['path' => $exception->getMessage()]); + } + } - if ($path === '/') { - return '/'; + /** + * Adresse der übergeordneten Stufe, an der keine Seite liegt (für einen Hinweis am Adressfeld); null, wenn dort eine + * Seite liegt oder es keine Zwischenstufe gibt. Die Zwischenstufe muss keine Seite sein, sie ergibt dann 404. + */ + public function missingParent(string $path): ?string + { + $parent = PagePath::parent($path); + + if ($parent === null || $parent === '/') { + return null; } - $path = mb_strtolower($path); - - if (preg_match('#^/[a-z0-9]+(?:-[a-z0-9]+)*$#', $path) !== 1) { - throw ValidationException::withMessages([ - 'path' => 'Der Pfad darf nur Kleinbuchstaben, Ziffern und Bindestriche enthalten.', - ]); - } - - return $path; + return Page::query()->where('path', $parent)->exists() ? null : $parent; } /** diff --git a/app/Domain/Cms/ReservedPaths.php b/app/Domain/Cms/ReservedPaths.php new file mode 100644 index 0000000..b2d6f00 --- /dev/null +++ b/app/Domain/Cms/ReservedPaths.php @@ -0,0 +1,60 @@ +firstSegments(), true); + } + + /** + * @return list + */ + public function firstSegments(): array + { + $segments = []; + + foreach ($this->router->getRoutes()->getRoutes() as $route) { + $first = explode('/', ltrim($route->uri(), '/'))[0]; + + // Die Auffangroute für Seiten ("{path}") und Routen mit Parameter im ersten Teil sind nicht reservierbar. + if ($first !== '' && ! str_contains($first, '{')) { + $segments[$first] = true; + } + } + + foreach (glob(public_path('*')) ?: [] as $entry) { + $segments[basename($entry)] = true; + } + + return array_keys($segments); + } +} diff --git a/app/Domain/Cms/SiteNavigation.php b/app/Domain/Cms/SiteNavigation.php index f7c4595..201c7c0 100644 --- a/app/Domain/Cms/SiteNavigation.php +++ b/app/Domain/Cms/SiteNavigation.php @@ -37,10 +37,12 @@ public function header(): array foreach ($topLevel as $item) { $children = []; + $childBelow = false; foreach ($this->items->where('parent_id', $item->id) as $child) { $href = $child->href(); if ($href !== null) { + $childBelow = $childBelow || $this->isBelow($child); $children[] = [ 'id' => $child->id, 'label' => $child->label, @@ -62,7 +64,7 @@ public function header(): array 'label' => $item->label, 'href' => $href, 'current' => $current, - 'activeTrail' => $current || in_array(true, array_column($children, 'current'), true), + 'activeTrail' => $current || $childBelow || in_array(true, array_column($children, 'current'), true) || ($href !== null && $this->isBelow($item)), 'children' => $children, ]; } @@ -101,4 +103,15 @@ private function isCurrent(NavigationItem $item): bool { return $item->targetPath() === $this->currentPath; } + + /** + * Die aktuelle Seite liegt unterhalb des Ziels ("/kurse" → "/kurse/kinder"), ganze Pfadteile. Die Startseite ist + * ausgenommen, sonst läge jede Seite unter ihr. + */ + private function isBelow(NavigationItem $item): bool + { + $target = $item->targetPath(); + + return $target !== null && $target !== '/' && PagePath::isDescendantOf($this->currentPath, $target); + } } diff --git a/app/Filament/Pages/Webpraesenz.php b/app/Filament/Pages/Webpraesenz.php index 79e48e8..d1dc3ad 100644 --- a/app/Filament/Pages/Webpraesenz.php +++ b/app/Filament/Pages/Webpraesenz.php @@ -5,6 +5,7 @@ use App\Domain\Cms\LinkTargets; use App\Domain\Cms\NavigationItem; use App\Domain\Cms\Page as CmsPage; +use App\Domain\Cms\PagePath; use App\Domain\Cms\PageService; use App\Domain\Cms\Sections\PageSections; use App\Domain\Cms\Widgets\Support\SafeUrl; @@ -169,8 +170,9 @@ public function bestand(): array $seiten = CmsPage::query()->with('latestRevision')->get(); $seiten = match ($this->sortierung) { 'bearbeitet_alt' => $seiten->sortBy([['updated_at', 'asc'], ['id', 'asc']]), - 'adresse' => $seiten->sortBy('path', SORT_NATURAL), - 'adresse_ab' => $seiten->sortByDesc('path', SORT_NATURAL), + // Nach Pfadteilen, damit Unterseiten unmittelbar hinter ihrer übergeordneten Adresse stehen. + 'adresse' => $seiten->sort(fn (CmsPage $a, CmsPage $b): int => PagePath::compare($a->path, $b->path)), + 'adresse_ab' => $seiten->sort(fn (CmsPage $a, CmsPage $b): int => PagePath::compare($b->path, $a->path)), default => $seiten->sortBy([['updated_at', 'desc'], ['id', 'desc']]), }; @@ -241,6 +243,10 @@ private function seitenZeile(CmsPage $seite, Collection $menues): array } } + if (PagePath::depth($seite->path) > 1) { + $chips[] = ['label' => 'Unterseite von '.PagePath::parent($seite->path), 'ton' => 'leise']; + } + $eintraege = $menues->filter(fn (NavigationItem $item): bool => $item->page_id === $seite->id || ($item->page_id === null && $item->targetPath() === $seite->path)); $sichtbarImKopf = false; @@ -297,8 +303,9 @@ public function duplicateAction(): Action TextInput::make('path') ->label('Pfad der neuen Seite') ->required() - ->maxLength(255) - ->helperText('Zum Beispiel /neue-landingpage'), + ->maxLength(PagePath::MAX_LENGTH) + ->live(onBlur: true) + ->helperText(fn (?string $state): string => PageResource::pathHelp($state)), ]) ->modalSubmitActionLabel('Duplizieren') ->action(function (array $arguments, array $data, PageService $service): void { @@ -772,7 +779,8 @@ public function zielSeiten(): array { $needle = mb_strtolower(trim($this->zielSuche)); - return CmsPage::query()->with('latestRevision')->orderBy('path')->get() + return CmsPage::query()->with('latestRevision')->get() + ->sort(fn (CmsPage $a, CmsPage $b): int => PagePath::compare($a->path, $b->path)) ->map(fn (CmsPage $seite): array => [ 'id' => $seite->id, 'titel' => $seite->latestRevision?->contentTitle() ?: $seite->path, diff --git a/app/Filament/Resources/NavigationItems/NavigationItemResource.php b/app/Filament/Resources/NavigationItems/NavigationItemResource.php index fdb23a6..281ed3b 100644 --- a/app/Filament/Resources/NavigationItems/NavigationItemResource.php +++ b/app/Filament/Resources/NavigationItems/NavigationItemResource.php @@ -4,6 +4,7 @@ use App\Domain\Cms\NavigationItem; use App\Domain\Cms\Page; +use App\Domain\Cms\PagePath; use App\Domain\Cms\Widgets\Support\SafeUrl; use App\Filament\Resources\NavigationItems\Pages\ManageNavigationItems; use Closure; @@ -70,7 +71,7 @@ public static function form(Schema $schema): Schema }), Select::make('page_id') ->label('Interne Seite') - ->options(fn (): array => Page::query()->orderBy('path')->pluck('path', 'id')->all()) + ->options(fn (): array => Page::query()->get()->sort(fn (Page $a, Page $b): int => PagePath::compare($a->path, $b->path))->pluck('path', 'id')->all()) ->searchable() ->helperText('Bevorzugt: eine CMS-Seite wählen. Dann folgt der Link automatisch einer Pfadänderung.'), TextInput::make('url') diff --git a/app/Filament/Resources/Pages/PageResource.php b/app/Filament/Resources/Pages/PageResource.php index 5ca772e..7d55558 100644 --- a/app/Filament/Resources/Pages/PageResource.php +++ b/app/Filament/Resources/Pages/PageResource.php @@ -4,6 +4,7 @@ use App\Domain\Catalog\Pillar; use App\Domain\Cms\Page; +use App\Domain\Cms\PagePath; use App\Domain\Cms\PageService; use App\Filament\Resources\Pages\Pages\CreatePage; use App\Filament\Resources\Pages\Pages\EditPage; @@ -36,6 +37,28 @@ class PageResource extends Resource protected static ?string $recordTitleAttribute = 'path'; + /** + * Hilfetext am Adressfeld: Form der Adresse und, falls die übergeordnete Stufe keine Seite ist, ein Hinweis. + */ + public static function pathHelp(?string $state): string + { + $help = 'Zum Beispiel /praevention oder /kurse/kinder. Beliebig viele Ebenen, nur Kleinbuchstaben, Ziffern und Bindestriche.'; + + if (! is_string($state) || trim($state) === '') { + return $help; + } + + $service = app(PageService::class); + + try { + $parent = $service->missingParent($service->normalizePath($state)); + } catch (ValidationException) { + return $help; + } + + return $parent === null ? $help : $help.' Hinweis: '.$parent.' ist keine Seite; diese Adresse ergibt 404, bis dort eine Seite liegt.'; + } + public static function form(Schema $schema): Schema { return $schema->components([ @@ -48,8 +71,9 @@ public static function form(Schema $schema): Schema TextInput::make('path') ->label('Pfad') ->required() - ->maxLength(255) - ->helperText('Zum Beispiel / oder /praevention'), + ->maxLength(PagePath::MAX_LENGTH) + ->live(onBlur: true) + ->helperText(fn (?string $state): string => self::pathHelp($state)), TextInput::make('seo_title') ->label('SEO-Titel') ->maxLength(255), @@ -115,8 +139,9 @@ public static function table(Table $table): Table TextInput::make('path') ->label('Pfad der neuen Seite') ->required() - ->maxLength(255) - ->helperText('Zum Beispiel /neue-landingpage'), + ->maxLength(PagePath::MAX_LENGTH) + ->live(onBlur: true) + ->helperText(fn (?string $state): string => self::pathHelp($state)), ]) ->modalSubmitActionLabel('Duplizieren') ->action(function (Page $record, array $data, PageService $service) { diff --git a/app/Filament/Support/SectionTransferActions.php b/app/Filament/Support/SectionTransferActions.php index 13c7ab9..00b6968 100644 --- a/app/Filament/Support/SectionTransferActions.php +++ b/app/Filament/Support/SectionTransferActions.php @@ -3,6 +3,7 @@ namespace App\Filament\Support; use App\Domain\Cms\Page; +use App\Domain\Cms\PagePath; use App\Domain\Cms\SectionTransfer; use Filament\Actions\Action; use Filament\Forms\Components\Repeater; @@ -82,8 +83,8 @@ private static function pageOptions(mixed $livewire): array return Page::query() ->with(['latestRevision', 'publishedRevision']) ->when($current !== null, fn ($query) => $query->whereKeyNot($current)) - ->orderBy('path') ->get() + ->sort(fn (Page $a, Page $b): int => PagePath::compare($a->path, $b->path)) ->filter(fn (Page $page): bool => $user?->can('update', $page) ?? false) ->mapWithKeys(function (Page $page): array { $title = ($page->latestRevision ?? $page->publishedRevision)?->contentTitle(); diff --git a/routes/web.php b/routes/web.php index 9010f0e..cf26f96 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,5 +1,6 @@ name('profile.address'); }); -Route::get('/{path}', [PageController::class, 'show'])->where('path', '[a-z0-9\-]+')->name('page'); +// Seiten des CMS unter ein- oder mehrteiligen Adressen (/kurse, /kurse/kinder). Zuletzt, damit feste Routen Vorrang haben; +// ihre ersten Pfadteile sind für Seiten reserviert (ReservedPaths). +Route::get('/{path}', [PageController::class, 'show'])->where('path', PagePath::ROUTE_PATTERN)->name('page'); diff --git a/tests/Feature/CmsPageHierarchyTest.php b/tests/Feature/CmsPageHierarchyTest.php new file mode 100644 index 0000000..d8d60db --- /dev/null +++ b/tests/Feature/CmsPageHierarchyTest.php @@ -0,0 +1,455 @@ +redakteur()->create(); + $editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP'); + + return $editor; + } + + private function page(string $path, string $heading = 'Überschrift', bool $publish = true): Page + { + $service = app(PageService::class); + $page = Page::query()->create(['path' => $path]); + $revision = $service->saveRevision($page, [ + ['layout' => 'u4', 'style' => [], 'slots' => [['type' => 'heading', 'v' => 1, 'data' => ['heading' => $heading]]]], + ], null, null, null); + + if ($publish) { + $service->publish($page, $revision); + } + + return $page->fresh(); + } + + private function blocked(string $path): bool + { + try { + app(PageService::class)->availablePath($path); + } catch (ValidationException $exception) { + return isset($exception->errors()['path']); + } + + return false; + } + + // ----------------------------------------------------------------------------------------------------------------- + // Adresse prüfen + // ----------------------------------------------------------------------------------------------------------------- + + public function test_multi_part_paths_are_normalized_and_available(): void + { + $service = app(PageService::class); + + $this->assertSame('/kurse/kinder', $service->availablePath('/Kurse/Kinder/')); + $this->assertSame('/kurse/erwachsene/ab-18/gruppe-2', $service->availablePath('kurse/erwachsene/ab-18/gruppe-2')); + } + + public function test_an_invalid_path_is_reported_at_the_path_field(): void + { + foreach (['/kurse//kinder', '/kurse/../kinder', '/kurse/größe', '/kurse/kinder.html', '/'.str_repeat('abcdefghi/', 26)] as $path) { + $this->assertTrue($this->blocked($path), $path); + } + } + + public function test_the_path_must_stay_unique_but_may_keep_its_own_value(): void + { + $page = $this->page('/kurse/kinder'); + $service = app(PageService::class); + + $this->assertTrue($this->blocked('/kurse/kinder')); + $this->assertTrue($this->blocked('/Kurse/Kinder/')); + $this->assertSame('/kurse/kinder', $service->availablePath('/kurse/kinder', $page)); + } + + public function test_an_existing_page_on_a_reserved_path_stays_saveable_but_cannot_move_onto_one(): void + { + $page = Page::query()->create(['path' => '/kasse']); + $service = app(PageService::class); + + $this->assertSame('/kasse', $service->availablePath('/kasse', $page), 'Unveränderter Pfad: die Seite bleibt speicherbar.'); + + $other = Page::query()->create(['path' => '/frei']); + $this->expectException(ValidationException::class); + $service->availablePath('/kasse/x', $other); + } + + /** + * @return array + */ + public static function reservedPaths(): array + { + return [ + 'Themen' => ['/themen/xyz'], + 'Programme' => ['/programme/abc'], + 'Medien' => ['/medien/a/b'], + 'Speicher' => ['/storage/x'], + 'Mitgliederbereich' => ['/bereich/x'], + 'Redaktionsvorschau' => ['/redaktion/x'], + 'Verwaltung' => ['/verwaltung/x'], + 'Kasse' => ['/kasse'], + 'Kasse darunter' => ['/kasse/x'], + 'Warenkorb' => ['/warenkorb'], + 'Anmeldung' => ['/anmelden/x'], + 'nur POST: Abmelden' => ['/abmelden'], + 'nur POST: Stripe' => ['/stripe/webhook'], + 'Ordner in public' => ['/build/x'], + 'Ordner in public, einteilig' => ['/css'], + 'Unterseite des Shops' => ['/shop/kinder'], + 'Unterseite der Angebote' => ['/angebote/x'], + 'Hinweisseite des Shops' => ['/kauf-noch-nicht-moeglich'], + ]; + } + + #[DataProvider('reservedPaths')] + public function test_paths_under_a_fixed_route_are_blocked(string $path): void + { + $this->assertTrue($this->blocked($path), $path.' gehört zu einer festen Funktion der Anwendung.'); + } + + public function test_the_exact_addresses_the_cms_serves_on_purpose_stay_available(): void + { + $reserved = app(ReservedPaths::class); + + foreach (['/', '/shop', '/angebote'] as $path) { + $this->assertFalse($reserved->blocks($path), $path); + } + + // Ähnlich klingende Namen sind keine reservierten Teile. + $service = app(PageService::class); + $this->assertSame('/themen-test', $service->availablePath('/themen-test')); + $this->assertSame('/shopping/kurse', $service->availablePath('/shopping/kurse')); + $this->assertSame('/kurse/themen/x', $service->availablePath('/kurse/themen/x')); + } + + public function test_reserved_parts_come_from_the_router_including_the_livewire_segment(): void + { + $livewire = collect(Route::getRoutes()->getRoutes()) + ->map(fn ($route): string => explode('/', ltrim($route->uri(), '/'))[0]) + ->first(fn (string $first): bool => str_starts_with($first, 'livewire')); + + $this->assertNotNull($livewire); + $this->assertTrue($this->blocked('/'.$livewire.'/x')); + + $this->assertFalse($this->blocked('/neu-fest/y')); + Route::get('/neu-fest/x', fn () => 'fest'); + $this->assertTrue($this->blocked('/neu-fest/y'), 'Eine später hinzugefügte feste Route reserviert ihren ersten Teil.'); + } + + public function test_every_route_but_the_catch_all_has_a_static_first_part(): void + { + $dynamic = collect(Route::getRoutes()->getRoutes()) + ->filter(fn ($route): bool => str_contains(explode('/', ltrim($route->uri(), '/'))[0], '{')) + ->map(fn ($route): string => $route->uri()) + ->values() + ->all(); + + $this->assertSame(['{path}'], $dynamic, 'Eine Route mit Parameter im ersten Teil ließe sich nicht reservieren (ReservedPaths).'); + } + + public function test_every_first_part_of_the_router_is_reserved(): void + { + $reserved = app(ReservedPaths::class)->firstSegments(); + + foreach (Route::getRoutes()->getRoutes() as $route) { + $first = explode('/', ltrim($route->uri(), '/'))[0]; + + if ($first === '' || str_contains($first, '{')) { + continue; + } + + $this->assertContains($first, $reserved, $route->uri()); + } + } + + public function test_pages_created_by_migrations_and_seeders_pass_the_check(): void + { + $service = app(PageService::class); + + foreach (Page::query()->get() as $page) { + $this->assertSame($page->path, $service->availablePath($page->path, $page), $page->path.' wäre unerreichbar.'); + } + } + + // ----------------------------------------------------------------------------------------------------------------- + // Öffentliche Auslieferung + // ----------------------------------------------------------------------------------------------------------------- + + public function test_a_published_page_is_served_under_its_multi_part_address(): void + { + $this->page('/kurse/kinder', 'Kurse für Kinder'); + $this->page('/kurse/erwachsene/ab-18/gruppe-2/abend', 'Abendgruppe'); + + $this->get('/kurse/kinder')->assertOk()->assertSee('Kurse für Kinder'); + $this->get('/kurse/erwachsene/ab-18/gruppe-2/abend')->assertOk()->assertSee('Abendgruppe'); + } + + public function test_an_intermediate_level_without_a_page_is_not_found(): void + { + $this->page('/kurse/kinder'); + + $this->get('/kurse')->assertNotFound(); + $this->get('/kurse/erwachsene')->assertNotFound(); + } + + public function test_a_draft_is_not_public_and_a_capital_letter_is_not_found(): void + { + $this->page('/kurse/entwurf', 'Nur Entwurf', publish: false); + $this->page('/kurse/kinder'); + + $this->get('/kurse/entwurf')->assertNotFound(); + $this->get('/kurse/Kinder')->assertNotFound(); + } + + public function test_a_trailing_slash_serves_the_same_page_as_before(): void + { + $this->page('/kurse/kinder', 'Kurse für Kinder'); + + $this->get('/kurse/kinder/')->assertOk()->assertSee('Kurse für Kinder'); + } + + public function test_the_sitemap_lists_multi_part_pages(): void + { + $this->page('/kurse/kinder'); + $this->page('/kurse/entwurf', publish: false); + + $this->get('/sitemap.xml')->assertOk() + ->assertSee(url('/kurse/kinder'), false) + ->assertDontSee(url('/kurse/entwurf'), false); + } + + public function test_fixed_routes_answer_as_before(): void + { + $this->get('/themen')->assertOk(); + $this->get('/anmelden')->assertOk(); + $this->get('/praevention')->assertOk(); + $this->get('/angebote')->assertRedirect(route('shop')); + } + + // ----------------------------------------------------------------------------------------------------------------- + // Verwaltung + // ----------------------------------------------------------------------------------------------------------------- + + public function test_the_editor_creates_a_page_under_a_multi_part_address(): void + { + Livewire::actingAs($this->editor(), 'staff') + ->test(CreatePage::class) + ->fillForm(['path' => '/Kurse/Kinder/', 'sections' => []]) + ->call('create') + ->assertHasNoFormErrors(); + + $this->assertNotNull(Page::query()->where('path', '/kurse/kinder')->first()); + } + + public function test_a_reserved_address_is_reported_at_the_path_field_and_nothing_is_saved(): void + { + Livewire::actingAs($this->editor(), 'staff') + ->test(CreatePage::class) + ->fillForm(['path' => '/themen/xyz', 'sections' => []]) + ->call('create'); + + $this->assertNull(Page::query()->where('path', '/themen/xyz')->first()); + $this->assertSame(0, Page::query()->where('path', 'like', '/themen/%')->count()); + } + + public function test_the_page_address_can_be_changed_to_a_deeper_one(): void + { + $page = $this->page('/kurse'); + + Livewire::actingAs($this->editor(), 'staff') + ->test(EditPage::class, ['record' => $page->id]) + ->set('data.path', '/angebote-kurse/kinder') + ->call('save') + ->assertHasNoFormErrors(); + + $this->assertSame('/angebote-kurse/kinder', $page->fresh()->path); + } + + public function test_renaming_a_page_leaves_the_pages_below_it_where_they_are(): void + { + $parent = $this->page('/kurse'); + $child = $this->page('/kurse/kinder'); + + Livewire::actingAs($this->editor(), 'staff') + ->test(EditPage::class, ['record' => $parent->id]) + ->set('data.path', '/lehrgaenge') + ->call('save') + ->assertHasNoFormErrors(); + + $this->assertSame('/lehrgaenge', $parent->fresh()->path); + $this->assertSame('/kurse/kinder', $child->fresh()->path, 'Die Hierarchie ist eine Eigenschaft der Adresse: Unterseiten ziehen nicht mit.'); + } + + public function test_a_page_can_be_duplicated_under_a_deeper_address_but_not_onto_a_fixed_route(): void + { + $source = $this->page('/kurse'); + $editor = $this->editor(); + + Livewire::actingAs($editor, 'staff') + ->test(Webpraesenz::class) + ->callAction(TestAction::make('duplicate')->arguments(['page' => $source->id]), ['path' => '/verwaltung/kurse']) + ->assertHasActionErrors(['path']); + + Livewire::actingAs($editor, 'staff') + ->test(Webpraesenz::class) + ->callAction(TestAction::make('duplicate')->arguments(['page' => $source->id]), ['path' => '/kurse/kinder']) + ->assertHasNoActionErrors(); + + $this->assertNull(Page::query()->where('path', '/kurse/kinder')->firstOrFail()->published_revision_id); + } + + public function test_the_page_list_sorts_by_address_part_by_part_and_shows_the_level(): void + { + foreach (['/kurse-extra', '/kurse/kinder', '/kurse', '/kurse/erwachsene', '/kurse/kinder/ab-6'] as $path) { + $this->page($path); + } + + $component = Livewire::withQueryParams(['sortierung' => 'adresse'])->actingAs($this->editor(), 'staff')->test(Webpraesenz::class); + $rows = collect($component->instance()->bestand()['zeilen']); + $addresses = $rows->pluck('meta')->filter(fn (string $meta): bool => str_starts_with($meta, '/kurse'))->values()->all(); + + $this->assertSame(['/kurse', '/kurse/erwachsene', '/kurse/kinder', '/kurse/kinder/ab-6', '/kurse-extra'], $addresses); + + $child = $rows->firstWhere('meta', '/kurse/kinder/ab-6'); + $this->assertContains('Unterseite von /kurse/kinder', array_column($child['chips'], 'label')); + $top = array_column($rows->firstWhere('meta', '/kurse')['chips'], 'label'); + $this->assertSame([], array_filter($top, fn (string $label): bool => str_starts_with($label, 'Unterseite von'))); + } + + public function test_the_link_targets_list_sub_pages_right_after_their_parent(): void + { + foreach (['/kurse-extra', '/kurse/kinder', '/kurse'] as $path) { + $this->page($path); + } + + $paths = array_values(array_filter( + array_column(app(LinkTargets::class)->pages(), 'pfad'), + fn (string $path): bool => str_starts_with($path, '/kurse'), + )); + + $this->assertSame(['/kurse', '/kurse/kinder', '/kurse-extra'], $paths); + } + + public function test_the_missing_parent_is_named_for_a_hint(): void + { + $this->page('/kurse/kinder'); + $service = app(PageService::class); + + $this->assertSame('/kurse', $service->missingParent('/kurse/kinder')); + $this->assertNull($service->missingParent('/kurse/kinder/ab-6'), 'Die Stufe /kurse/kinder ist eine Seite.'); + $this->assertSame('/kurse/erwachsene', $service->missingParent('/kurse/erwachsene/ab-6')); + $this->assertNull($service->missingParent('/kurse'), 'Der erste Teil hat nur die Wurzel als Elternstufe.'); + $this->page('/kurse'); + $this->assertNull($service->missingParent('/kurse/kinder')); + $this->assertNull($service->missingParent('/')); + } + + // ----------------------------------------------------------------------------------------------------------------- + // Menü + // ----------------------------------------------------------------------------------------------------------------- + + private function entry(string $label, ?string $url, ?int $parent = null, ?Page $page = null): NavigationItem + { + return NavigationItem::query()->create([ + 'label' => $label, + 'url' => $url, + 'page_id' => $page?->id, + 'parent_id' => $parent, + 'placement' => 'header', + 'sort_order' => 1, + 'is_visible' => true, + ]); + } + + public function test_a_menu_entry_is_in_the_active_trail_when_the_current_page_lies_below_its_target(): void + { + NavigationItem::query()->delete(); + $this->entry('Start', '/'); + $this->entry('Kurse', '/kurse'); + $this->entry('Kurse-Extra', '/kurse-extra'); + + $entries = collect(SiteNavigation::forPath(NavigationItem::query()->visible()->get(), '/kurse/kinder/ab-6')->header())->keyBy('label'); + + $this->assertTrue($entries['Kurse']['activeTrail']); + $this->assertFalse($entries['Kurse']['current'], 'Nur der genaue Treffer ist die aktuelle Seite.'); + $this->assertFalse($entries['Kurse-Extra']['activeTrail'], '/kurse-extra liegt nicht unter /kurse.'); + $this->assertFalse($entries['Start']['activeTrail'], 'Die Startseite wäre sonst immer aktiv.'); + } + + public function test_the_active_trail_also_reaches_a_parent_entry_without_an_address(): void + { + NavigationItem::query()->delete(); + $group = $this->entry('Angebot', null); + $this->entry('Kinder', '/kurse/kinder', $group->id); + + $entries = collect(SiteNavigation::forPath(NavigationItem::query()->visible()->get(), '/kurse/kinder/ab-6')->header()); + + $this->assertTrue($entries->firstWhere('label', 'Angebot')['activeTrail']); + } + + public function test_the_active_trail_still_marks_the_exact_page_as_current(): void + { + NavigationItem::query()->delete(); + $this->entry('Kinder', '/kurse/kinder'); + + $entry = SiteNavigation::forPath(NavigationItem::query()->visible()->get(), '/kurse/kinder')->header()[0]; + + $this->assertTrue($entry['current']); + $this->assertTrue($entry['activeTrail']); + } + + public function test_a_menu_entry_for_a_deep_page_links_to_its_full_address(): void + { + $page = $this->page('/kurse/kinder/ab-6'); + $item = $this->entry('Ab 6', null, null, $page); + + $this->assertSame(url('/kurse/kinder/ab-6'), $item->href()); + $this->assertSame('/kurse/kinder/ab-6', $item->targetPath()); + } + + public function test_the_public_page_marks_the_parent_menu_entry_as_active_trail(): void + { + NavigationItem::query()->delete(); + $this->entry('Kurse', '/kurse'); + $this->page('/kurse/kinder'); + + $this->get('/kurse/kinder')->assertOk()->assertSee('is-active-trail', false); + } +} diff --git a/tests/Feature/ShopSwitchTest.php b/tests/Feature/ShopSwitchTest.php index c7f8937..2412076 100644 --- a/tests/Feature/ShopSwitchTest.php +++ b/tests/Feature/ShopSwitchTest.php @@ -85,8 +85,9 @@ public function test_production_without_release_creates_no_order_through_the_rem $this->production(); $offer = $this->privateKonflikte(); + // Die Adresse ist keine Route mehr; die Auffangroute für Seiten trifft sie (mehrteilige Seitenadressen, ADR-72), kennt aber nur GET. foreach (['/bereich/angebote/'.$offer->id.'/kaufen', '/angebote/'.$offer->id.'/kaufen'] as $path) { - $this->postProduction($path, [], $this->tina())->assertStatus(404); + $this->postProduction($path, [], $this->tina())->assertStatus(405); } $this->assertSame(0, Order::query()->count()); @@ -97,7 +98,7 @@ public function test_the_direct_purchase_is_gone_in_test_mode_too_and_checkout_h { $offer = $this->privateKonflikte(); - $this->actingAs($this->tina())->post('/bereich/angebote/'.$offer->id.'/kaufen')->assertStatus(404); + $this->actingAs($this->tina())->post('/bereich/angebote/'.$offer->id.'/kaufen')->assertStatus(405); $this->assertSame(0, Order::query()->count()); $this->assertFalse(method_exists(Checkout::class, 'place'), 'Es gibt nur noch die Bestellung aus dem Warenkorb mit Pflichtangaben.'); }