From 70a8c5072bed28fb2c937dd3ffb67df08eefb30a Mon Sep 17 00:00:00 2001 From: Lars Stommer Date: Thu, 22 Oct 2026 22:38:27 +0200 Subject: [PATCH] Minimum stay exceptions (gap filled, ends on changeover day, offers, absolute minimum); copy seasons aligned to a weekday Co-Authored-By: Claude Opus 5.5 --- app/Actions/CopySeasonsToNextYear.php | 41 +++++- .../SeasonsRelationManager.php | 38 +++++- .../SpecialOffersRelationManager.php | 8 +- app/Models/Property.php | 19 +++ app/Pricing/PriceCalculator.php | 27 +++- ...add_min_stay_rules_to_properties_table.php | 31 +++++ docs/KONZEPT.md | 3 +- tests/Feature/MinimumStayRulesTest.php | 127 ++++++++++++++++++ tests/Feature/OfferShowcaseTest.php | 1 + 9 files changed, 280 insertions(+), 15 deletions(-) create mode 100644 database/migrations/2026_10_22_223225_add_min_stay_rules_to_properties_table.php create mode 100644 tests/Feature/MinimumStayRulesTest.php diff --git a/app/Actions/CopySeasonsToNextYear.php b/app/Actions/CopySeasonsToNextYear.php index 3b74422..5b6d20b 100644 --- a/app/Actions/CopySeasonsToNextYear.php +++ b/app/Actions/CopySeasonsToNextYear.php @@ -3,26 +3,40 @@ namespace App\Actions; use App\Models\Property; +use Carbon\CarbonImmutable; /** - * Copies all seasons starting in a given year to the following year with the same calendar dates, - * so a new price year only needs adjusting instead of re-entering. + * Copies all seasons starting in a given year to the following year, so a new price year only needs adjusting + * instead of re-entering. Optionally every season start is moved to the nearest given weekday (e.g. Saturday + * as changeover day); seasons that were adjacent stay adjacent. */ class CopySeasonsToNextYear { /** + * @param int|null $alignToWeekday ISO weekday (1 = Monday … 7 = Sunday) or null for the same calendar dates * @return array{created: int, skipped: int} */ - public function handle(Property $property, int $year): array + public function handle(Property $property, int $year, ?int $alignToWeekday = null): array { $created = 0; $skipped = 0; - $seasons = $property->seasons()->whereYear('starts_on', $year)->get(); + $seasons = $property->seasons()->whereYear('starts_on', $year)->orderBy('starts_on')->get(); + + // New start per old start date; an end that equals another season's start follows that start. + $moved = []; + foreach ($seasons as $season) { + $moved[$season->starts_on->toDateString()] = $this->shift($season->starts_on, $alignToWeekday); + } foreach ($seasons as $season) { - $startsOn = $season->starts_on->addYearNoOverflow(); - $endsOn = $season->ends_on->addYearNoOverflow(); + $startsOn = $moved[$season->starts_on->toDateString()]; + $endsOn = $moved[$season->ends_on->toDateString()] ?? $this->shift($season->ends_on, $alignToWeekday); + if ($endsOn->lessThanOrEqualTo($startsOn)) { + $skipped++; + + continue; + } if ($property->seasons()->overlapping($startsOn, $endsOn)->exists()) { $skipped++; @@ -40,4 +54,19 @@ public function handle(Property $property, int $year): array return ['created' => $created, 'skipped' => $skipped]; } + + /** + * One year later; with a weekday, moved to the nearest such day (at most 3 days earlier or later). + */ + private function shift(CarbonImmutable $date, ?int $weekday): CarbonImmutable + { + $next = $date->addYearNoOverflow(); + if ($weekday === null) { + return $next; + } + + $difference = ($weekday - $next->isoWeekday() + 7) % 7; + + return $difference <= 3 ? $next->addDays($difference) : $next->subDays(7 - $difference); + } } diff --git a/app/Filament/Resources/Properties/RelationManagers/SeasonsRelationManager.php b/app/Filament/Resources/Properties/RelationManagers/SeasonsRelationManager.php index 841bfc0..0bf7c84 100644 --- a/app/Filament/Resources/Properties/RelationManagers/SeasonsRelationManager.php +++ b/app/Filament/Resources/Properties/RelationManagers/SeasonsRelationManager.php @@ -23,6 +23,7 @@ use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; +use Filament\Forms\Components\Toggle; use Filament\Notifications\Notification; use Filament\Resources\RelationManagers\RelationManager; use Filament\Schemas\Components\Utilities\Get; @@ -35,6 +36,8 @@ class SeasonsRelationManager extends RelationManager { + public const WEEKDAYS = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag']; + protected static string $relationship = 'seasons'; protected static ?string $title = 'Saisons & Preise'; @@ -111,6 +114,7 @@ public function table(Table $table): Table ->headerActions([ CreateAction::make(), $this->copyToNextYearAction(), + $this->minimumStayRulesAction(), $this->priceCalculatorAction(), ]) ->recordActions([ @@ -179,22 +183,52 @@ private function seasonYears(): array return $years->combine($years)->all(); } + /** + * The relaxations of the seasons' minimum stay, edited where the seasons are maintained. + */ + private function minimumStayRulesAction(): Action + { + return Action::make('minimumStayRules') + ->label('Regeln Mindestaufenthalt') + ->icon(Heroicon::OutlinedAdjustmentsHorizontal) + ->color('gray') + ->modalHeading('Mindestaufenthalt – Ausnahmen') + ->modalDescription('Jede Saison hat ihre Mindestnächte. Diese Regeln erlauben kürzere Aufenthalte, wenn sie den Kalender nicht zerstückeln. Sonderangebote können den Mindestaufenthalt zusätzlich aufheben.') + ->fillForm(fn (): array => $this->getOwnerRecord()->only(['changeover_weekday', 'min_stay_fill_gaps', 'min_stay_until_changeover', 'min_stay_absolute'])) + ->schema([ + Select::make('changeover_weekday')->label('Typischer An- und Abreisetag')->options(self::WEEKDAYS)->placeholder('keiner'), + Toggle::make('min_stay_fill_gaps')->label('Kalenderlücken: kürzer erlaubt, wenn die Buchung eine Lücke zwischen zwei Belegungen vollständig füllt'), + Toggle::make('min_stay_until_changeover')->label('Kürzer erlaubt, wenn die Buchung am typischen Anreisetag endet (die Woche danach bleibt frei buchbar)'), + TextInput::make('min_stay_absolute')->label('Untergrenze für alle Ausnahmen')->integer()->minValue(1)->maxValue(14)->suffix('Nächte')->required(), + ]) + ->action(function (array $data): void { + $this->getOwnerRecord()->update($data); + Notification::make()->title('Regeln gespeichert')->success()->send(); + }); + } + private function copyToNextYearAction(): Action { return Action::make('copyToNextYear') ->label('In Folgejahr kopieren') ->icon(Heroicon::OutlinedDocumentDuplicate) ->color('gray') - ->modalDescription('Alle Saisons, die im gewählten Jahr beginnen, werden mit gleichen Kalenderdaten und Preisen ins Folgejahr übernommen. Bereits belegte Zeiträume werden übersprungen.') + ->modalDescription('Alle Saisons, die im gewählten Jahr beginnen, werden mit Preisen und Mindestnächten ins Folgejahr übernommen. Bereits belegte Zeiträume werden übersprungen.') ->schema([ Select::make('year') ->label('Jahr kopieren') ->options(fn (): array => $this->seasonYears()) ->default((string) now()->year) ->required(), + Select::make('weekday') + ->label('Saisonbeginn legen auf') + ->helperText('Jeder Saisonbeginn wird auf den nächstgelegenen Wochentag verschoben (höchstens 3 Tage); aneinandergrenzende Saisons bleiben lückenlos.') + ->options(self::WEEKDAYS) + ->placeholder('gleiche Kalenderdaten wie im Vorjahr') + ->default(fn (): ?int => $this->getOwnerRecord()->changeover_weekday), ]) ->action(function (array $data, CopySeasonsToNextYear $copySeasons): void { - $result = $copySeasons->handle($this->getOwnerRecord(), (int) $data['year']); + $result = $copySeasons->handle($this->getOwnerRecord(), (int) $data['year'], filled($data['weekday'] ?? null) ? (int) $data['weekday'] : null); Notification::make() ->title("{$result['created']} Saisons nach ".((int) $data['year'] + 1).' kopiert') diff --git a/app/Filament/Resources/Properties/RelationManagers/SpecialOffersRelationManager.php b/app/Filament/Resources/Properties/RelationManagers/SpecialOffersRelationManager.php index 795a0db..e45b7d0 100644 --- a/app/Filament/Resources/Properties/RelationManagers/SpecialOffersRelationManager.php +++ b/app/Filament/Resources/Properties/RelationManagers/SpecialOffersRelationManager.php @@ -121,6 +121,9 @@ public function form(Schema $schema): Schema Toggle::make('is_combinable') ->label('Mit anderen kombinierbaren Angeboten kombinierbar') ->helperText('Sonst erhält der Gast automatisch das für ihn beste Einzelangebot.'), + Toggle::make('waives_min_stay') + ->label('Mindestaufenthalt der Saison aufheben') + ->helperText('Wenn das Angebot gilt, darf der Aufenthalt kürzer sein als die Mindestnächte der Saison (z. B. Special Weekend mit 2 Nächten, kurze Lücke).'), ]), Section::make('Bewerbung auf der Webseite') ->description('Welche Angebote gerade erscheinen, ergibt sich automatisch: aktiv, ohne Aktionscode, im Buchungszeitraum, feste Termine nur solange frei, Lückenfüller je gefundener Lücke. Mehrere gleichzeitig werden im Baustein „Sonderangebote“ nebeneinander, als Liste oder rollierend gezeigt.') @@ -144,10 +147,7 @@ public function form(Schema $schema): Schema ->visible(fn (Get $get): bool => $this->kind($get) === OfferKind::GapFiller) ->schema([ TextInput::make('max_gap_nights')->label('Lücken bis höchstens … Nächte')->integer()->minValue(1)->default(4)->required(), - Toggle::make('waives_min_stay') - ->label('Mindestaufenthalt der Saison aufheben') - ->helperText('Damit auch kurze Lücken (z. B. 2 Nächte bei 5 Nächten Mindestaufenthalt) buchbar werden.') - ->default(true), + ]), Section::make('Bedingungen') ->description('Leere Felder bedeuten: keine Einschränkung.') diff --git a/app/Models/Property.php b/app/Models/Property.php index ecf2082..528ef5d 100644 --- a/app/Models/Property.php +++ b/app/Models/Property.php @@ -27,6 +27,10 @@ 'hold_hours', 'check_in_time', 'check_out_time', + 'changeover_weekday', + 'min_stay_fill_gaps', + 'min_stay_until_changeover', + 'min_stay_absolute', 'is_active', ])] class Property extends Model @@ -39,10 +43,25 @@ class Property extends Model * * @return array */ + /** + * Defaults of the minimum stay rules (as in the migration), also before the model is reloaded. + * + * @var array + */ + protected $attributes = [ + 'min_stay_fill_gaps' => true, + 'min_stay_until_changeover' => false, + 'min_stay_absolute' => 2, + ]; + protected function casts(): array { return [ 'is_active' => 'boolean', + 'min_stay_fill_gaps' => 'boolean', + 'min_stay_until_changeover' => 'boolean', + 'changeover_weekday' => 'integer', + 'min_stay_absolute' => 'integer', ]; } diff --git a/app/Pricing/PriceCalculator.php b/app/Pricing/PriceCalculator.php index fde3e68..f609364 100644 --- a/app/Pricing/PriceCalculator.php +++ b/app/Pricing/PriceCalculator.php @@ -40,8 +40,7 @@ public function calculate(Property $property, StayRequest $stay, ?CarbonImmutabl $offers = $this->applicableOffers($property, $stay, $nightSeasons, $bookedAt); $arrivalSeason = $nightSeasons[0]; - $minimumStayWaived = $offers->contains(fn (SpecialOffer $offer): bool => $offer->waives_min_stay && $offer->kind === OfferKind::GapFiller); - if ($nights < $arrivalSeason->min_nights && ! $minimumStayWaived) { + if ($nights < $arrivalSeason->min_nights && ! $this->minimumStayRelaxed($property, $stay, $offers)) { throw QuoteException::minimumStay($arrivalSeason->min_nights, $arrivalSeason->name); } @@ -125,6 +124,30 @@ private function accommodationLines(array $nightSeasons): array ), $runs); } + /** + * Whether a stay shorter than the season's minimum is still allowed: an applicable offer waives it, or – + * never below the property's absolute minimum – the stay fills a calendar gap completely, or it ends on the + * typical changeover day (so the following week stays bookable). + * + * @param Collection $offers + */ + private function minimumStayRelaxed(Property $property, StayRequest $stay, Collection $offers): bool + { + if ($offers->contains(fn (SpecialOffer $offer): bool => $offer->waives_min_stay)) { + return true; + } + + if ($stay->nights() < max(1, (int) $property->min_stay_absolute)) { + return false; + } + + if ($property->min_stay_until_changeover && $property->changeover_weekday !== null && $stay->departure->isoWeekday() === $property->changeover_weekday) { + return true; + } + + return $property->min_stay_fill_gaps && $this->gaps->gapContaining($property, $stay->arrival, $stay->departure) === $stay->nights(); + } + /** * Active offers whose conditions the stay meets. The calendar gap is only looked up if a gap filler exists. * diff --git a/database/migrations/2026_10_22_223225_add_min_stay_rules_to_properties_table.php b/database/migrations/2026_10_22_223225_add_min_stay_rules_to_properties_table.php new file mode 100644 index 0000000..e506ae3 --- /dev/null +++ b/database/migrations/2026_10_22_223225_add_min_stay_rules_to_properties_table.php @@ -0,0 +1,31 @@ +unsignedTinyInteger('changeover_weekday')->nullable()->after('check_out_time'); + $table->boolean('min_stay_fill_gaps')->default(true)->after('changeover_weekday'); + $table->boolean('min_stay_until_changeover')->default(false)->after('min_stay_fill_gaps'); + $table->unsignedTinyInteger('min_stay_absolute')->default(2)->after('min_stay_until_changeover'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('properties', function (Blueprint $table) { + $table->dropColumn(['changeover_weekday', 'min_stay_fill_gaps', 'min_stay_until_changeover', 'min_stay_absolute']); + }); + } +}; diff --git a/docs/KONZEPT.md b/docs/KONZEPT.md index 340ddf2..aa49a65 100644 --- a/docs/KONZEPT.md +++ b/docs/KONZEPT.md @@ -57,7 +57,8 @@ ## 5. Verwaltungssystem (Admin) - **Dashboard:** nächste An-/Abreisen, offene Anfragen, fällige Zahlungen, Auslastung/Umsatz pro Jahr. - **Kalender:** alle Buchungen + Portal-Blockierungen + manuelle Sperrzeiten (Eigennutzung, Renovierung). -- **Saisons & Preise:** pro Saison Zeitraum, Preis/Nacht, Mindestaufenthalt, optional An-/Abreisetage. Jahr kopieren („Preise 2027 = 2026“) mit einem Klick. +- **Saisons & Preise:** pro Saison Zeitraum, Preis/Nacht, Mindestaufenthalt, optional An-/Abreisetage. Jahr kopieren („Preise 2027 = 2026“) mit einem Klick – optional mit **Saisonbeginn auf einen Wochentag** (z. B. Samstag; aneinandergrenzende Saisons bleiben lückenlos). +- **Ausnahmen vom Mindestaufenthalt** (je Wohnung, „Preise & Angebote › Saisons › Regeln Mindestaufenthalt“): kürzer erlaubt, wenn die Buchung eine Kalenderlücke vollständig füllt oder am typischen Anreisetag endet; Sonderangebote jeder Art können ihn aufheben; absolute Untergrenze für alle Ausnahmen (Standard 2 Nächte). - **Preisbestandteile (konfigurierbar):** Endreinigung/Service (108 €), Zusatzperson ab 3. Person (7,50 €/Nacht), Extras (Bettwäsche 14 €, Handtücher 11 €, Paket 23 €), Kurtaxe (Hinweis, vor Ort), Anzahlungsquote 35 %, Restzahlungsfrist 4 Wochen. - Darstellung wahlweise wie heute („erste Nacht inkl. Endreinigung“) oder transparent getrennt – die Berechnung ist identisch. - **Sonderangebote & Sonderkonditionen:** werden bei jeder Preisberechnung automatisch geprüft (siehe 5a). diff --git a/tests/Feature/MinimumStayRulesTest.php b/tests/Feature/MinimumStayRulesTest.php new file mode 100644 index 0000000..6f65280 --- /dev/null +++ b/tests/Feature/MinimumStayRulesTest.php @@ -0,0 +1,127 @@ +property = Property::factory()->create(['min_stay_absolute' => 2]); + Season::factory()->for($this->property)->create(['name' => 'Hauptsaison', 'starts_on' => '2026-06-06', 'ends_on' => '2026-09-05', 'nightly_rate' => 9000, 'min_nights' => 7]); + } + + public function test_season_minimum_applies_without_a_rule(): void + { + $this->expectException(QuoteException::class); + + $this->quote('2026-07-08', '2026-07-11'); + } + + public function test_stay_filling_a_calendar_gap_completely_may_be_shorter(): void + { + BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-07-01', 'ends_on' => '2026-07-08']); + BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-07-11', 'ends_on' => '2026-07-18']); + + $this->assertSame(3, $this->quote('2026-07-08', '2026-07-11')->nights()); + + $this->expectException(QuoteException::class); + $this->quote('2026-07-08', '2026-07-10'); + } + + public function test_gap_rule_can_be_switched_off(): void + { + $this->property->update(['min_stay_fill_gaps' => false]); + BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-07-01', 'ends_on' => '2026-07-08']); + BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-07-11', 'ends_on' => '2026-07-18']); + + $this->expectException(QuoteException::class); + $this->quote('2026-07-08', '2026-07-11'); + } + + public function test_stay_ending_on_the_changeover_day_may_be_shorter_but_not_below_the_absolute_minimum(): void + { + $this->property->update(['changeover_weekday' => 6, 'min_stay_until_changeover' => true]); + + $this->assertSame(3, $this->quote('2026-07-08', '2026-07-11')->nights(), 'Wednesday to Saturday'); + + try { + $this->quote('2026-07-10', '2026-07-11'); + $this->fail('one night is below the absolute minimum'); + } catch (QuoteException) { + $this->addToAssertionCount(1); + } + + $this->expectException(QuoteException::class); + $this->quote('2026-07-08', '2026-07-10'); + } + + public function test_any_special_offer_can_waive_the_minimum_stay(): void + { + SpecialOffer::factory()->for($this->property)->create(['name' => 'Special Weekend', 'arrival_weekdays' => [5], 'max_nights' => 2, 'waives_min_stay' => true, 'discount_value' => 10]); + + $quote = $this->quote('2026-07-10', '2026-07-12'); + + $this->assertSame(2, $quote->nights()); + $this->assertGreaterThan(0, $quote->discount()); + } + + public function test_copying_seasons_moves_their_start_to_the_weekday_and_keeps_them_adjacent(): void + { + Season::factory()->for($this->property)->create(['name' => 'Vorsaison', 'starts_on' => '2026-04-04', 'ends_on' => '2026-06-06', 'nightly_rate' => 7000, 'min_nights' => 3]); + + $result = app(CopySeasonsToNextYear::class)->handle($this->property, 2026, 6); + + $copies = $this->property->seasons()->whereYear('starts_on', 2027)->orderBy('starts_on')->get(); + $this->assertSame(2, $result['created']); + $this->assertSame(['2027-04-03', '2027-06-05', '2027-06-05', '2027-09-04'], [ + $copies[0]->starts_on->toDateString(), $copies[0]->ends_on->toDateString(), + $copies[1]->starts_on->toDateString(), $copies[1]->ends_on->toDateString(), + ]); + $this->assertTrue($copies->every(fn (Season $season): bool => $season->starts_on->isSaturday())); + } + + public function test_rules_are_edited_next_to_the_seasons(): void + { + $this->actingAs(User::factory()->create()); + + Livewire::test(SeasonsRelationManager::class, ['ownerRecord' => $this->property, 'pageClass' => EditProperty::class]) + ->callAction(TestAction::make('minimumStayRules')->table(), [ + 'changeover_weekday' => 6, + 'min_stay_fill_gaps' => true, + 'min_stay_until_changeover' => true, + 'min_stay_absolute' => 3, + ]) + ->assertHasNoFormErrors(); + + $this->assertSame([6, true, 3], [$this->property->fresh()->changeover_weekday, $this->property->fresh()->min_stay_until_changeover, $this->property->fresh()->min_stay_absolute]); + } + + private function quote(string $arrival, string $departure): PriceQuote + { + return app(PriceCalculator::class)->calculate($this->property->fresh(), new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), CarbonImmutable::parse('2026-03-01')); + } +} diff --git a/tests/Feature/OfferShowcaseTest.php b/tests/Feature/OfferShowcaseTest.php index c3ddeba..ad144c7 100644 --- a/tests/Feature/OfferShowcaseTest.php +++ b/tests/Feature/OfferShowcaseTest.php @@ -94,6 +94,7 @@ public function test_gap_filler_advertises_each_gap_found_in_the_calendar(): voi public function test_gap_below_minimum_stay_is_not_advertised_unless_the_offer_waives_it(): void { + $this->property->update(['min_stay_fill_gaps' => false]); BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-02-05', 'ends_on' => '2026-02-10']); BlockedPeriod::factory()->for($this->property)->create(['starts_on' => '2026-02-12', 'ends_on' => '2026-02-20']); $this->offer(['name' => 'Lückenfüller', 'kind' => OfferKind::GapFiller, 'max_gap_nights' => 4, 'discount_value' => 20]);