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 <noreply@anthropic.com>
This commit is contained in:
Lars StommerandClaude Opus 5.5 committed 2026-10-22 22:38:27 +02:00
1 parent 20235b9139
commit 70a8c5072b
9 files changed
+280 -15

No files matched your search

+35 -6
View File
@@ -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);
}
}
@@ -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')
@@ -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.')
+19
View File
@@ -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<string, string>
*/
/**
* Defaults of the minimum stay rules (as in the migration), also before the model is reloaded.
*
* @var array<string, mixed>
*/
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',
];
}
+25 -2
View File
@@ -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<int, SpecialOffer> $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.
*
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Relaxations of the seasons' minimum stay (see Property::minimumStayRules / PriceCalculator).
*/
public function up(): void
{
Schema::table('properties', function (Blueprint $table) {
$table->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']);
});
}
};
+2 -1
View File
@@ -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).
+127
View File
@@ -0,0 +1,127 @@
<?php
namespace Tests\Feature;
use App\Actions\CopySeasonsToNextYear;
use App\Filament\Resources\Properties\Pages\EditProperty;
use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager;
use App\Models\BlockedPeriod;
use App\Models\Property;
use App\Models\Season;
use App\Models\SpecialOffer;
use App\Models\User;
use App\Pricing\PriceCalculator;
use App\Pricing\PriceQuote;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use Carbon\CarbonImmutable;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;
class MinimumStayRulesTest extends TestCase
{
use RefreshDatabase;
private Property $property;
protected function setUp(): void
{
parent::setUp();
$this->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'));
}
}
+1
View File
@@ -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]);