From 2e9a391b3703a1157acf4b121ed7fa3ffd2bcd39 Mon Sep 17 00:00:00 2001 From: Lars Stommer Date: Thu, 22 Oct 2026 09:19:49 +0200 Subject: [PATCH] Phase 1: Wohnungen, Saisons & Preisberechnung MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Datenmodell Property/Season/Extra (Beträge in Cent), Seeder mit Preisliste 2026 - PriceCalculator: Saison-Splitting, Mindestaufenthalt, Zusatzperson, Endreinigung, Extras, Anzahlung/Restzahlung - Filament-Verwaltung: Wohnungen, Saisons (Überschneidungsprüfung, Lückenwarnung, Kopie ins Folgejahr, Preisrechner), Zusatzleistungen - Tests für Preisberechnung und Saisonverwaltung Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 13 + CLAUDE.md | 13 + app/Actions/CopySeasonsToNextYear.php | 43 +++ app/Enums/ExtraPricing.php | 19 ++ app/Enums/QuoteLineType.php | 19 ++ app/Filament/Forms/Components/EuroInput.php | 24 ++ .../Properties/Pages/CreateProperty.php | 11 + .../Properties/Pages/EditProperty.php | 19 ++ .../Properties/Pages/ListProperties.php | 19 ++ .../Resources/Properties/PropertyResource.php | 57 ++++ .../ExtrasRelationManager.php | 82 ++++++ .../SeasonsRelationManager.php | 256 ++++++++++++++++++ .../Properties/Schemas/PropertyForm.php | 99 +++++++ .../Properties/Tables/PropertiesTable.php | 37 +++ app/Models/Extra.php | 53 ++++ app/Models/Property.php | 87 ++++++ app/Models/Season.php | 63 +++++ app/Models/User.php | 12 +- app/Pricing/PriceCalculator.php | 133 +++++++++ app/Pricing/PriceQuote.php | 72 +++++ app/Pricing/QuoteException.php | 37 +++ app/Pricing/QuoteLine.php | 33 +++ app/Providers/Filament/AdminPanelProvider.php | 5 +- config/app.php | 2 +- database/factories/ExtraFactory.php | 31 +++ database/factories/PropertyFactory.php | 36 +++ database/factories/SeasonFactory.php | 32 +++ ...6_10_22_091121_create_properties_table.php | 40 +++ ...2026_10_22_091123_create_seasons_table.php | 35 +++ .../2026_10_22_091124_create_extras_table.php | 34 +++ database/seeders/DatabaseSeeder.php | 8 +- database/seeders/PropertySeeder.php | 52 ++++ docs/KONZEPT.md | 6 +- tests/Feature/PriceCalculatorTest.php | 167 ++++++++++++ tests/Feature/SeasonManagementTest.php | 129 +++++++++ 35 files changed, 1766 insertions(+), 12 deletions(-) create mode 100644 app/Actions/CopySeasonsToNextYear.php create mode 100644 app/Enums/ExtraPricing.php create mode 100644 app/Enums/QuoteLineType.php create mode 100644 app/Filament/Forms/Components/EuroInput.php create mode 100644 app/Filament/Resources/Properties/Pages/CreateProperty.php create mode 100644 app/Filament/Resources/Properties/Pages/EditProperty.php create mode 100644 app/Filament/Resources/Properties/Pages/ListProperties.php create mode 100644 app/Filament/Resources/Properties/PropertyResource.php create mode 100644 app/Filament/Resources/Properties/RelationManagers/ExtrasRelationManager.php create mode 100644 app/Filament/Resources/Properties/RelationManagers/SeasonsRelationManager.php create mode 100644 app/Filament/Resources/Properties/Schemas/PropertyForm.php create mode 100644 app/Filament/Resources/Properties/Tables/PropertiesTable.php create mode 100644 app/Models/Extra.php create mode 100644 app/Models/Property.php create mode 100644 app/Models/Season.php create mode 100644 app/Pricing/PriceCalculator.php create mode 100644 app/Pricing/PriceQuote.php create mode 100644 app/Pricing/QuoteException.php create mode 100644 app/Pricing/QuoteLine.php create mode 100644 database/factories/ExtraFactory.php create mode 100644 database/factories/PropertyFactory.php create mode 100644 database/factories/SeasonFactory.php create mode 100644 database/migrations/2026_10_22_091121_create_properties_table.php create mode 100644 database/migrations/2026_10_22_091123_create_seasons_table.php create mode 100644 database/migrations/2026_10_22_091124_create_extras_table.php create mode 100644 database/seeders/PropertySeeder.php create mode 100644 tests/Feature/PriceCalculatorTest.php create mode 100644 tests/Feature/SeasonManagementTest.php diff --git a/AGENTS.md b/AGENTS.md index 42b099f..5d717f4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,16 @@ +# Ferienwohnung Stommer + +Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`. + +- Hosting target: Strato shared webhosting (PHP + MySQL, no Node at runtime) – build assets locally. +- UI and all user-facing texts are German; code, identifiers and PHPDoc are English. +- Money is stored as integer euro cents; edit via `App\Filament\Forms\Components\EuroInput`, display via `->money('EUR', divideBy: 100, locale: 'de')`. +- Season periods are half-open: a night belongs to a season when `starts_on <= night < ends_on`. +- Pricing lives in `app/Pricing` (`PriceCalculator` → `PriceQuote`); guest-facing errors are `QuoteException` messages. +- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded. +- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there). +- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`. + === foundation rules === diff --git a/CLAUDE.md b/CLAUDE.md index 42b099f..5d717f4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,3 +1,16 @@ +# Ferienwohnung Stommer + +Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`. + +- Hosting target: Strato shared webhosting (PHP + MySQL, no Node at runtime) – build assets locally. +- UI and all user-facing texts are German; code, identifiers and PHPDoc are English. +- Money is stored as integer euro cents; edit via `App\Filament\Forms\Components\EuroInput`, display via `->money('EUR', divideBy: 100, locale: 'de')`. +- Season periods are half-open: a night belongs to a season when `starts_on <= night < ends_on`. +- Pricing lives in `app/Pricing` (`PriceCalculator` → `PriceQuote`); guest-facing errors are `QuoteException` messages. +- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded. +- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there). +- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`. + === foundation rules === diff --git a/app/Actions/CopySeasonsToNextYear.php b/app/Actions/CopySeasonsToNextYear.php new file mode 100644 index 0000000..3b74422 --- /dev/null +++ b/app/Actions/CopySeasonsToNextYear.php @@ -0,0 +1,43 @@ +seasons()->whereYear('starts_on', $year)->get(); + + foreach ($seasons as $season) { + $startsOn = $season->starts_on->addYearNoOverflow(); + $endsOn = $season->ends_on->addYearNoOverflow(); + + if ($property->seasons()->overlapping($startsOn, $endsOn)->exists()) { + $skipped++; + + continue; + } + + $property->seasons()->create([ + ...$season->only(['name', 'nightly_rate', 'min_nights']), + 'starts_on' => $startsOn, + 'ends_on' => $endsOn, + ]); + $created++; + } + + return ['created' => $created, 'skipped' => $skipped]; + } +} diff --git a/app/Enums/ExtraPricing.php b/app/Enums/ExtraPricing.php new file mode 100644 index 0000000..4cc836e --- /dev/null +++ b/app/Enums/ExtraPricing.php @@ -0,0 +1,19 @@ + 'pro Stück (einmalig)', + self::PerNight => 'pro Stück und Nacht', + }; + } +} diff --git a/app/Enums/QuoteLineType.php b/app/Enums/QuoteLineType.php new file mode 100644 index 0000000..e02244e --- /dev/null +++ b/app/Enums/QuoteLineType.php @@ -0,0 +1,19 @@ +numeric() + ->minValue(0) + ->step(0.01) + ->suffix('€') + ->formatStateUsing(fn (?int $state): ?string => $state === null ? null : number_format($state / 100, 2, '.', '')) + ->dehydrateStateUsing(fn (string|int|float|null $state): ?int => $state === null || $state === '' ? null : (int) round((float) $state * 100)); + } +} diff --git a/app/Filament/Resources/Properties/Pages/CreateProperty.php b/app/Filament/Resources/Properties/Pages/CreateProperty.php new file mode 100644 index 0000000..fbbad58 --- /dev/null +++ b/app/Filament/Resources/Properties/Pages/CreateProperty.php @@ -0,0 +1,11 @@ + ListProperties::route('/'), + 'create' => CreateProperty::route('/create'), + 'edit' => EditProperty::route('/{record}/edit'), + ]; + } +} diff --git a/app/Filament/Resources/Properties/RelationManagers/ExtrasRelationManager.php b/app/Filament/Resources/Properties/RelationManagers/ExtrasRelationManager.php new file mode 100644 index 0000000..0cbf5d9 --- /dev/null +++ b/app/Filament/Resources/Properties/RelationManagers/ExtrasRelationManager.php @@ -0,0 +1,82 @@ +columns(2) + ->components([ + TextInput::make('name') + ->label('Bezeichnung') + ->required() + ->maxLength(255), + TextInput::make('description') + ->label('Beschreibung') + ->maxLength(255), + EuroInput::make('price') + ->label('Preis') + ->required(), + Select::make('pricing') + ->label('Abrechnung') + ->options(ExtraPricing::class) + ->default(ExtraPricing::PerItem) + ->required(), + Toggle::make('is_active') + ->label('Buchbar') + ->default(true), + ]); + } + + public function table(Table $table): Table + { + return $table + ->recordTitleAttribute('name') + ->reorderable('sort_order') + ->defaultSort('sort_order') + ->columns([ + TextColumn::make('name') + ->label('Bezeichnung') + ->description(fn ($record): ?string => $record->description), + TextColumn::make('price') + ->label('Preis') + ->money('EUR', divideBy: 100, locale: 'de'), + TextColumn::make('pricing') + ->label('Abrechnung'), + IconColumn::make('is_active') + ->label('Buchbar') + ->boolean(), + ]) + ->headerActions([ + CreateAction::make(), + ]) + ->recordActions([ + EditAction::make(), + DeleteAction::make(), + ]); + } +} diff --git a/app/Filament/Resources/Properties/RelationManagers/SeasonsRelationManager.php b/app/Filament/Resources/Properties/RelationManagers/SeasonsRelationManager.php new file mode 100644 index 0000000..e19ff8f --- /dev/null +++ b/app/Filament/Resources/Properties/RelationManagers/SeasonsRelationManager.php @@ -0,0 +1,256 @@ +columns(2) + ->components([ + TextInput::make('name') + ->label('Bezeichnung') + ->required() + ->maxLength(255) + ->datalist(['Winter', 'Nebensaison', 'Vorsaison', 'Hauptsaison', 'Hochsaison', 'Nachsaison', 'Zwischensaison', 'Weihnachten', 'Neujahr']) + ->columnSpanFull(), + DatePicker::make('starts_on') + ->label('Von (erste Nacht)') + ->required() + ->rule(fn (Get $get, ?Season $record): Closure => $this->noOverlapRule($get, $record)), + DatePicker::make('ends_on') + ->label('Bis (Abreisetag)') + ->helperText('= erster Tag der Folgesaison') + ->required() + ->after('starts_on'), + EuroInput::make('nightly_rate') + ->label('Preis pro Nacht') + ->required(), + TextInput::make('min_nights') + ->label('Mindestaufenthalt') + ->required() + ->integer() + ->minValue(1) + ->suffix('Nächte') + ->default(2), + ]); + } + + public function table(Table $table): Table + { + return $table + ->recordTitleAttribute('name') + ->defaultSort('starts_on') + ->description(fn (): ?string => $this->gapWarning()) + ->columns([ + TextColumn::make('name') + ->label('Saison'), + TextColumn::make('starts_on') + ->label('Von') + ->date('D, d.m.Y') + ->sortable(), + TextColumn::make('ends_on') + ->label('Bis') + ->date('D, d.m.Y'), + TextColumn::make('nightly_rate') + ->label('Pro Nacht') + ->money('EUR', divideBy: 100, locale: 'de'), + TextColumn::make('min_nights') + ->label('Mind. Nächte'), + ]) + ->filters([ + SelectFilter::make('year') + ->label('Jahr') + ->options(fn (): array => $this->seasonYears()) + ->default((string) now()->year) + ->query(fn (Builder $query, array $data): Builder => $query->when( + $data['value'], + fn (Builder $query, string $year): Builder => $query->whereYear('starts_on', '<=', $year)->whereYear('ends_on', '>=', $year), + )), + ]) + ->headerActions([ + CreateAction::make(), + $this->copyToNextYearAction(), + $this->priceCalculatorAction(), + ]) + ->recordActions([ + EditAction::make(), + ReplicateAction::make() + ->label('Duplizieren') + ->excludeAttributes(['starts_on', 'ends_on']) + ->schema(fn (Schema $schema): Schema => $this->form($schema)), + DeleteAction::make(), + ]) + ->toolbarActions([ + BulkActionGroup::make([ + DeleteBulkAction::make(), + ]), + ]); + } + + private function noOverlapRule(Get $get, ?Season $record): Closure + { + return function (string $attribute, mixed $value, Closure $fail) use ($get, $record): void { + if (blank($value) || blank($get('ends_on'))) { + return; + } + + $conflict = $this->getOwnerRecord()->seasons() + ->overlapping(CarbonImmutable::parse($value), CarbonImmutable::parse($get('ends_on'))) + ->when($record, fn (Builder $query) => $query->whereKeyNot($record->getKey())) + ->first(); + + if ($conflict) { + $fail("Überschneidet sich mit „{$conflict->name}“ ({$conflict->starts_on->format('d.m.Y')} – {$conflict->ends_on->format('d.m.Y')})."); + } + }; + } + + private function gapWarning(): ?string + { + /** @var Property $property */ + $property = $this->getOwnerRecord(); + $today = CarbonImmutable::today(); + $gaps = $property->uncoveredPeriods($today, $today->addMonths(18)); + + if ($gaps === []) { + return null; + } + + $periods = collect($gaps) + ->map(fn (array $gap): string => $gap['from']->format('d.m.Y').' – '.$gap['until']->format('d.m.Y')) + ->implode(', '); + + return "⚠ Ohne Preis (nicht buchbar) in den nächsten 18 Monaten: {$periods}"; + } + + /** + * @return array + */ + private function seasonYears(): array + { + $years = $this->getOwnerRecord()->seasons()->get()->pluck('starts_on') + ->map(fn (CarbonImmutable $date): string => (string) $date->year) + ->push((string) now()->year) + ->unique() + ->sort() + ->values(); + + return $years->combine($years)->all(); + } + + 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.') + ->schema([ + Select::make('year') + ->label('Jahr kopieren') + ->options(fn (): array => $this->seasonYears()) + ->default((string) now()->year) + ->required(), + ]) + ->action(function (array $data, CopySeasonsToNextYear $copySeasons): void { + $result = $copySeasons->handle($this->getOwnerRecord(), (int) $data['year']); + + Notification::make() + ->title("{$result['created']} Saisons nach ".((int) $data['year'] + 1).' kopiert') + ->body($result['skipped'] > 0 ? "{$result['skipped']} übersprungen, da der Zeitraum bereits belegt ist." : 'Bitte Daten und Preise prüfen.') + ->success() + ->send(); + }); + } + + private function priceCalculatorAction(): Action + { + return Action::make('calculatePrice') + ->label('Preis berechnen') + ->icon(Heroicon::OutlinedCalculator) + ->color('gray') + ->modalSubmitActionLabel('Berechnen') + ->schema([ + DatePicker::make('arrival') + ->label('Anreise') + ->required(), + DatePicker::make('departure') + ->label('Abreise') + ->required() + ->after('arrival'), + TextInput::make('guests') + ->label('Personen') + ->required() + ->integer() + ->minValue(1) + ->default(2), + ]) + ->action(function (array $data, PriceCalculator $calculator): void { + try { + $quote = $calculator->calculate( + $this->getOwnerRecord(), + CarbonImmutable::parse($data['arrival']), + CarbonImmutable::parse($data['departure']), + (int) $data['guests'], + ); + } catch (QuoteException $exception) { + Notification::make()->title('Nicht buchbar')->body($exception->getMessage())->danger()->send(); + + return; + } + + $euro = fn (int $cents): string => Number::currency($cents / 100, 'EUR', 'de'); + $lines = collect($quote->lines) + ->map(fn (QuoteLine $line): string => e($line->label).': '.$euro($line->amount)) + ->push('Anzahlung: '.$euro($quote->deposit()).' · Rest: '.$euro($quote->balance()).' fällig am '.$quote->balanceDueOn->format('d.m.Y')) + ->implode('
'); + + Notification::make() + ->title('Gesamtpreis: '.$euro($quote->total())) + ->body($lines) + ->success() + ->persistent() + ->send(); + }); + } +} diff --git a/app/Filament/Resources/Properties/Schemas/PropertyForm.php b/app/Filament/Resources/Properties/Schemas/PropertyForm.php new file mode 100644 index 0000000..ab16d54 --- /dev/null +++ b/app/Filament/Resources/Properties/Schemas/PropertyForm.php @@ -0,0 +1,99 @@ +components([ + Section::make('Wohnung') + ->columns(2) + ->schema([ + TextInput::make('name') + ->label('Name') + ->required() + ->maxLength(255) + ->live(onBlur: true) + ->afterStateUpdated(fn (Set $set, ?string $state, string $operation) => $operation === 'create' ? $set('slug', Str::slug((string) $state)) : null), + TextInput::make('slug') + ->label('URL-Kürzel') + ->required() + ->maxLength(255) + ->alphaDash() + ->unique(ignoreRecord: true), + TextInput::make('address') + ->label('Adresse') + ->maxLength(255), + TextInput::make('size_sqm') + ->label('Größe') + ->numeric() + ->minValue(1) + ->suffix('m²'), + TimePicker::make('check_in_time') + ->label('Anreise ab') + ->seconds(false), + TimePicker::make('check_out_time') + ->label('Abreise bis') + ->seconds(false), + Toggle::make('is_active') + ->label('Aktiv (auf der Webseite buchbar)') + ->default(true), + ]), + Section::make('Belegung & Preise') + ->description('Übernachtungspreise werden je Saison gepflegt (Reiter „Saisons“ unten).') + ->columns(2) + ->schema([ + TextInput::make('max_guests') + ->label('Maximale Personen') + ->required() + ->integer() + ->minValue(1), + TextInput::make('included_guests') + ->label('Im Preis enthaltene Personen') + ->required() + ->integer() + ->minValue(1) + ->lte('max_guests'), + EuroInput::make('extra_guest_fee_per_night') + ->label('Aufpreis je weitere Person und Nacht') + ->required() + ->default(0), + EuroInput::make('cleaning_fee') + ->label('Endreinigung & Service (einmalig)') + ->required() + ->default(0), + ]), + Section::make('Zahlungsbedingungen') + ->columns(2) + ->schema([ + TextInput::make('deposit_percent') + ->label('Anzahlung') + ->helperText('Anteil am Mietpreis (Übernachtungen ohne Endreinigung und Extras)') + ->required() + ->integer() + ->minValue(0) + ->maxValue(100) + ->suffix('%') + ->default(35), + TextInput::make('balance_due_days_before_arrival') + ->label('Restzahlung fällig') + ->required() + ->integer() + ->minValue(0) + ->suffix('Tage vor Anreise') + ->default(28), + ]), + ]); + } +} diff --git a/app/Filament/Resources/Properties/Tables/PropertiesTable.php b/app/Filament/Resources/Properties/Tables/PropertiesTable.php new file mode 100644 index 0000000..49ce8d8 --- /dev/null +++ b/app/Filament/Resources/Properties/Tables/PropertiesTable.php @@ -0,0 +1,37 @@ +columns([ + TextColumn::make('name') + ->label('Name') + ->searchable(), + TextColumn::make('address') + ->label('Adresse'), + TextColumn::make('size_sqm') + ->label('Größe') + ->suffix(' m²'), + TextColumn::make('max_guests') + ->label('Max. Personen'), + TextColumn::make('cleaning_fee') + ->label('Endreinigung') + ->money('EUR', divideBy: 100, locale: 'de'), + IconColumn::make('is_active') + ->label('Aktiv') + ->boolean(), + ]) + ->recordActions([ + EditAction::make(), + ]); + } +} diff --git a/app/Models/Extra.php b/app/Models/Extra.php new file mode 100644 index 0000000..30fd640 --- /dev/null +++ b/app/Models/Extra.php @@ -0,0 +1,53 @@ + */ + use HasFactory; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'pricing' => ExtraPricing::class, + 'is_active' => 'boolean', + ]; + } + + /** + * @return BelongsTo + */ + public function property(): BelongsTo + { + return $this->belongsTo(Property::class); + } + + /** + * @param Builder $query + * @return Builder + */ + #[Scope] + protected function active(Builder $query): Builder + { + return $query->where('is_active', true); + } +} diff --git a/app/Models/Property.php b/app/Models/Property.php new file mode 100644 index 0000000..9882657 --- /dev/null +++ b/app/Models/Property.php @@ -0,0 +1,87 @@ + */ + use HasFactory; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'is_active' => 'boolean', + ]; + } + + /** + * @return HasMany + */ + public function seasons(): HasMany + { + return $this->hasMany(Season::class)->orderBy('starts_on'); + } + + /** + * Periods within [$from, $until) for which no season defines a price. + * + * @return list + */ + public function uncoveredPeriods(CarbonImmutable $from, CarbonImmutable $until): array + { + $gaps = []; + $cursor = $from; + + foreach ($this->seasons()->overlapping($from, $until)->get() as $season) { + if ($season->starts_on->greaterThan($cursor)) { + $gaps[] = ['from' => $cursor, 'until' => $season->starts_on]; + } + + $cursor = $cursor->max($season->ends_on); + } + + if ($cursor->lessThan($until)) { + $gaps[] = ['from' => $cursor, 'until' => $until]; + } + + return $gaps; + } + + /** + * @return HasMany + */ + public function extras(): HasMany + { + return $this->hasMany(Extra::class)->orderBy('sort_order'); + } +} diff --git a/app/Models/Season.php b/app/Models/Season.php new file mode 100644 index 0000000..a241b55 --- /dev/null +++ b/app/Models/Season.php @@ -0,0 +1,63 @@ + */ + use HasFactory; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'starts_on' => 'immutable_date', + 'ends_on' => 'immutable_date', + ]; + } + + /** + * @return BelongsTo + */ + public function property(): BelongsTo + { + return $this->belongsTo(Property::class); + } + + /** + * Seasons that share at least one night with the half-open period [$from, $until). + * + * @param Builder $query + * @return Builder + */ + #[Scope] + protected function overlapping(Builder $query, CarbonInterface $from, CarbonInterface $until): Builder + { + return $query + ->whereDate('starts_on', '<', $until) + ->whereDate('ends_on', '>', $from); + } + + public function containsNight(CarbonInterface $night): bool + { + return $this->starts_on->lessThanOrEqualTo($night) && $this->ends_on->greaterThan($night); + } +} diff --git a/app/Models/User.php b/app/Models/User.php index f6ba1d2..c68d797 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -4,6 +4,8 @@ // use Illuminate\Contracts\Auth\MustVerifyEmail; use Database\Factories\UserFactory; +use Filament\Models\Contracts\FilamentUser; +use Filament\Panel; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -12,11 +14,19 @@ #[Fillable(['name', 'email', 'password'])] #[Hidden(['password', 'remember_token'])] -class User extends Authenticatable +class User extends Authenticatable implements FilamentUser { /** @use HasFactory */ use HasFactory, Notifiable; + /** + * Only administrators have accounts; there is no public registration. + */ + public function canAccessPanel(Panel $panel): bool + { + return true; + } + /** * Get the attributes that should be cast. * diff --git a/app/Pricing/PriceCalculator.php b/app/Pricing/PriceCalculator.php new file mode 100644 index 0000000..fd17a7c --- /dev/null +++ b/app/Pricing/PriceCalculator.php @@ -0,0 +1,133 @@ + $extraQuantities quantity per extra id + * + * @throws QuoteException + */ + public function calculate( + Property $property, + CarbonImmutable $arrival, + CarbonImmutable $departure, + int $guests, + array $extraQuantities = [], + ): PriceQuote { + $arrival = $arrival->startOfDay(); + $departure = $departure->startOfDay(); + + if ($departure->lessThanOrEqualTo($arrival)) { + throw QuoteException::invalidPeriod(); + } + + if ($guests < 1 || $guests > $property->max_guests) { + throw QuoteException::invalidGuestCount($property->max_guests); + } + + $nights = (int) $arrival->diffInDays($departure); + $lines = $this->accommodationLines($property, $arrival, $departure); + + $extraGuests = max(0, $guests - $property->included_guests); + if ($extraGuests > 0 && $property->extra_guest_fee_per_night > 0) { + $lines[] = new QuoteLine( + QuoteLineType::ExtraGuest, + "Zusätzliche Person ({$extraGuests} × {$nights} Nächte)", + $extraGuests * $nights, + $property->extra_guest_fee_per_night, + $extraGuests * $nights * $property->extra_guest_fee_per_night, + ); + } + + if ($property->cleaning_fee > 0) { + $lines[] = new QuoteLine(QuoteLineType::Cleaning, 'Endreinigung & Service', 1, $property->cleaning_fee, $property->cleaning_fee); + } + + array_push($lines, ...$this->extraLines($property, $extraQuantities, $nights)); + + return new PriceQuote( + arrival: $arrival, + departure: $departure, + guests: $guests, + lines: $lines, + depositPercent: $property->deposit_percent, + balanceDueOn: $arrival->subDays($property->balance_due_days_before_arrival), + ); + } + + /** + * One line per consecutive run of nights in the same season. + * + * @return list + */ + private function accommodationLines(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure): array + { + /** @var Collection $seasons */ + $seasons = $property->seasons()->overlapping($arrival, $departure)->get(); + + /** @var list $runs */ + $runs = []; + for ($night = $arrival; $night->lessThan($departure); $night = $night->addDay()) { + $season = $seasons->first(fn (Season $season): bool => $season->containsNight($night)) + ?? throw QuoteException::noRateForNight($night); + + $lastRun = array_key_last($runs); + if ($lastRun !== null && $runs[$lastRun]['season']->is($season)) { + $runs[$lastRun]['nights']++; + } else { + $runs[] = ['season' => $season, 'nights' => 1]; + } + } + + $arrivalSeason = $runs[0]['season']; + $nights = (int) $arrival->diffInDays($departure); + if ($nights < $arrivalSeason->min_nights) { + throw QuoteException::minimumStay($arrivalSeason->min_nights, $arrivalSeason->name); + } + + return array_map(fn (array $run): QuoteLine => new QuoteLine( + QuoteLineType::Accommodation, + "{$run['season']->name} ({$run['nights']} ".($run['nights'] === 1 ? 'Nacht' : 'Nächte').')', + $run['nights'], + $run['season']->nightly_rate, + $run['nights'] * $run['season']->nightly_rate, + ), $runs); + } + + /** + * @param array $extraQuantities + * @return list + */ + private function extraLines(Property $property, array $extraQuantities, int $nights): array + { + $extraQuantities = array_filter($extraQuantities, fn (int $quantity): bool => $quantity > 0); + if ($extraQuantities === []) { + return []; + } + + $extras = $property->extras()->active()->whereKey(array_keys($extraQuantities))->get()->keyBy('id'); + + $lines = []; + foreach ($extraQuantities as $extraId => $quantity) { + /** @var Extra $extra */ + $extra = $extras->get($extraId) ?? throw QuoteException::unknownExtra($extraId); + $units = $extra->pricing === ExtraPricing::PerNight ? $quantity * $nights : $quantity; + + $lines[] = new QuoteLine(QuoteLineType::Extra, $extra->name, $units, $extra->price, $units * $extra->price); + } + + return $lines; + } +} diff --git a/app/Pricing/PriceQuote.php b/app/Pricing/PriceQuote.php new file mode 100644 index 0000000..72f2775 --- /dev/null +++ b/app/Pricing/PriceQuote.php @@ -0,0 +1,72 @@ + $lines + */ + public function __construct( + public CarbonImmutable $arrival, + public CarbonImmutable $departure, + public int $guests, + public array $lines, + public int $depositPercent, + public CarbonImmutable $balanceDueOn, + ) {} + + public function nights(): int + { + return (int) $this->arrival->diffInDays($this->departure); + } + + public function total(): int + { + return array_sum(array_map(fn (QuoteLine $line): int => $line->amount, $this->lines)); + } + + public function rent(): int + { + return array_sum(array_map( + fn (QuoteLine $line): int => $line->type->isRent() ? $line->amount : 0, + $this->lines, + )); + } + + /** + * Deposit as a share of the rent (nights and extra guests, without cleaning and extras), rounded to full cents. + */ + public function deposit(): int + { + return intdiv($this->rent() * $this->depositPercent + 50, 100); + } + + public function balance(): int + { + return $this->total() - $this->deposit(); + } + + /** + * @return array{arrival: string, departure: string, nights: int, guests: int, lines: list>, total: int, deposit: int, balance: int, balance_due_on: string} + */ + public function toArray(): array + { + return [ + 'arrival' => $this->arrival->toDateString(), + 'departure' => $this->departure->toDateString(), + 'nights' => $this->nights(), + 'guests' => $this->guests, + 'lines' => array_map(fn (QuoteLine $line): array => $line->toArray(), $this->lines), + 'total' => $this->total(), + 'deposit' => $this->deposit(), + 'balance' => $this->balance(), + 'balance_due_on' => $this->balanceDueOn->toDateString(), + ]; + } +} diff --git a/app/Pricing/QuoteException.php b/app/Pricing/QuoteException.php new file mode 100644 index 0000000..2dd3ae6 --- /dev/null +++ b/app/Pricing/QuoteException.php @@ -0,0 +1,37 @@ +format('d.m.Y')} sind noch keine Preise hinterlegt."); + } + + public static function minimumStay(int $minNights, string $seasonName): self + { + return new self("In der Saison „{$seasonName}“ beträgt der Mindestaufenthalt {$minNights} Nächte."); + } + + public static function unknownExtra(int $extraId): self + { + return new self("Die Zusatzleistung #{$extraId} ist nicht buchbar."); + } +} diff --git a/app/Pricing/QuoteLine.php b/app/Pricing/QuoteLine.php new file mode 100644 index 0000000..c3a9bff --- /dev/null +++ b/app/Pricing/QuoteLine.php @@ -0,0 +1,33 @@ + $this->type->value, + 'label' => $this->label, + 'quantity' => $this->quantity, + 'unit_price' => $this->unitPrice, + 'amount' => $this->amount, + ]; + } +} diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index 7c74b3e..4f7778d 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -11,7 +11,6 @@ use Filament\PanelProvider; use Filament\Support\Colors\Color; use Filament\Widgets\AccountWidget; -use Filament\Widgets\FilamentInfoWidget; use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse; use Illuminate\Cookie\Middleware\EncryptCookies; use Illuminate\Foundation\Http\Middleware\PreventRequestForgery; @@ -28,8 +27,9 @@ public function panel(Panel $panel): Panel ->id('admin') ->path('admin') ->login() + ->brandName('FeWo Stommer · Verwaltung') ->colors([ - 'primary' => Color::Amber, + 'primary' => Color::Sky, ]) ->discoverResources(in: app_path('Filament/Resources'), for: 'App\Filament\Resources') ->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages') @@ -39,7 +39,6 @@ public function panel(Panel $panel): Panel ->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\Filament\Widgets') ->widgets([ AccountWidget::class, - FilamentInfoWidget::class, ]) ->middleware([ EncryptCookies::class, diff --git a/config/app.php b/config/app.php index dfa47ba..b8ff0be 100644 --- a/config/app.php +++ b/config/app.php @@ -65,7 +65,7 @@ | */ - 'timezone' => 'UTC', + 'timezone' => env('APP_TIMEZONE', 'Europe/Berlin'), /* |-------------------------------------------------------------------------- diff --git a/database/factories/ExtraFactory.php b/database/factories/ExtraFactory.php new file mode 100644 index 0000000..86dead4 --- /dev/null +++ b/database/factories/ExtraFactory.php @@ -0,0 +1,31 @@ + + */ +class ExtraFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'property_id' => Property::factory(), + 'name' => fake()->randomElement(['Bettwäsche', 'Handtuchpaket', 'Kinderbett']), + 'price' => fake()->numberBetween(5, 25) * 100, + 'pricing' => ExtraPricing::PerItem, + 'is_active' => true, + 'sort_order' => 0, + ]; + } +} diff --git a/database/factories/PropertyFactory.php b/database/factories/PropertyFactory.php new file mode 100644 index 0000000..15af083 --- /dev/null +++ b/database/factories/PropertyFactory.php @@ -0,0 +1,36 @@ + + */ +class PropertyFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + $name = 'Ferienwohnung '.fake()->unique()->lastName(); + + return [ + 'name' => $name, + 'slug' => str($name)->slug()->toString(), + 'address' => fake()->streetAddress().', 18225 Kühlungsborn', + 'size_sqm' => fake()->numberBetween(35, 90), + 'max_guests' => 4, + 'included_guests' => 2, + 'extra_guest_fee_per_night' => 750, + 'cleaning_fee' => 10800, + 'deposit_percent' => 35, + 'balance_due_days_before_arrival' => 28, + 'is_active' => true, + ]; + } +} diff --git a/database/factories/SeasonFactory.php b/database/factories/SeasonFactory.php new file mode 100644 index 0000000..6ca0c04 --- /dev/null +++ b/database/factories/SeasonFactory.php @@ -0,0 +1,32 @@ + + */ +class SeasonFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + $startsOn = fake()->dateTimeBetween('now', '+1 year'); + + return [ + 'property_id' => Property::factory(), + 'name' => fake()->randomElement(['Vorsaison', 'Hauptsaison', 'Nachsaison']), + 'starts_on' => $startsOn->format('Y-m-d'), + 'ends_on' => (clone $startsOn)->modify('+4 weeks')->format('Y-m-d'), + 'nightly_rate' => fake()->numberBetween(50, 120) * 100, + 'min_nights' => 2, + ]; + } +} diff --git a/database/migrations/2026_10_22_091121_create_properties_table.php b/database/migrations/2026_10_22_091121_create_properties_table.php new file mode 100644 index 0000000..6f39926 --- /dev/null +++ b/database/migrations/2026_10_22_091121_create_properties_table.php @@ -0,0 +1,40 @@ +id(); + $table->string('name'); + $table->string('slug')->unique(); + $table->string('address')->nullable(); + $table->unsignedSmallInteger('size_sqm')->nullable(); + $table->unsignedTinyInteger('max_guests'); + $table->unsignedTinyInteger('included_guests'); + $table->unsignedInteger('extra_guest_fee_per_night')->default(0); + $table->unsignedInteger('cleaning_fee')->default(0); + $table->unsignedTinyInteger('deposit_percent')->default(35); + $table->unsignedSmallInteger('balance_due_days_before_arrival')->default(28); + $table->time('check_in_time')->nullable(); + $table->time('check_out_time')->nullable(); + $table->boolean('is_active')->default(true); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('properties'); + } +}; diff --git a/database/migrations/2026_10_22_091123_create_seasons_table.php b/database/migrations/2026_10_22_091123_create_seasons_table.php new file mode 100644 index 0000000..d396b41 --- /dev/null +++ b/database/migrations/2026_10_22_091123_create_seasons_table.php @@ -0,0 +1,35 @@ +id(); + $table->foreignId('property_id')->constrained()->cascadeOnDelete(); + $table->string('name'); + $table->date('starts_on'); + $table->date('ends_on'); + $table->unsignedInteger('nightly_rate'); + $table->unsignedTinyInteger('min_nights')->default(1); + $table->timestamps(); + + $table->index(['property_id', 'starts_on']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('seasons'); + } +}; diff --git a/database/migrations/2026_10_22_091124_create_extras_table.php b/database/migrations/2026_10_22_091124_create_extras_table.php new file mode 100644 index 0000000..5c3ca22 --- /dev/null +++ b/database/migrations/2026_10_22_091124_create_extras_table.php @@ -0,0 +1,34 @@ +id(); + $table->foreignId('property_id')->constrained()->cascadeOnDelete(); + $table->string('name'); + $table->string('description')->nullable(); + $table->unsignedInteger('price'); + $table->string('pricing'); + $table->boolean('is_active')->default(true); + $table->unsignedSmallInteger('sort_order')->default(0); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('extras'); + } +}; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 6b901f8..0f7a957 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -15,11 +15,11 @@ class DatabaseSeeder extends Seeder */ public function run(): void { - // User::factory(10)->create(); - User::factory()->create([ - 'name' => 'Test User', - 'email' => 'test@example.com', + 'name' => 'Admin', + 'email' => 'admin@example.com', ]); + + $this->call(PropertySeeder::class); } } diff --git a/database/seeders/PropertySeeder.php b/database/seeders/PropertySeeder.php new file mode 100644 index 0000000..fb3e690 --- /dev/null +++ b/database/seeders/PropertySeeder.php @@ -0,0 +1,52 @@ + 'Ferienwohnung Stommer', + 'slug' => 'ferienwohnung-stommer', + 'address' => 'Strandstraße 15, 18225 Kühlungsborn', + 'size_sqm' => 53, + 'max_guests' => 3, + 'included_guests' => 2, + 'extra_guest_fee_per_night' => 750, + 'cleaning_fee' => 10800, + 'deposit_percent' => 35, + 'balance_due_days_before_arrival' => 28, + ]); + + $property->seasons()->createMany([ + ['name' => 'Neujahr', 'starts_on' => '2025-12-26', 'ends_on' => '2026-01-03', 'nightly_rate' => 11500, 'min_nights' => 6], + ['name' => 'Winter', 'starts_on' => '2026-01-03', 'ends_on' => '2026-03-07', 'nightly_rate' => 5500, 'min_nights' => 2], + ['name' => 'Nebensaison', 'starts_on' => '2026-03-07', 'ends_on' => '2026-04-03', 'nightly_rate' => 6500, 'min_nights' => 2], + ['name' => 'Vorsaison', 'starts_on' => '2026-04-03', 'ends_on' => '2026-05-23', 'nightly_rate' => 8500, 'min_nights' => 2], + ['name' => 'Hauptsaison', 'starts_on' => '2026-05-23', 'ends_on' => '2026-06-20', 'nightly_rate' => 9500, 'min_nights' => 2], + ['name' => 'Hochsaison', 'starts_on' => '2026-06-20', 'ends_on' => '2026-08-29', 'nightly_rate' => 11500, 'min_nights' => 2], + ['name' => 'Hauptsaison', 'starts_on' => '2026-08-29', 'ends_on' => '2026-09-26', 'nightly_rate' => 9500, 'min_nights' => 3], + ['name' => 'Nachsaison', 'starts_on' => '2026-09-26', 'ends_on' => '2026-10-31', 'nightly_rate' => 8500, 'min_nights' => 2], + ['name' => 'Zwischensaison', 'starts_on' => '2026-10-31', 'ends_on' => '2026-12-19', 'nightly_rate' => 6500, 'min_nights' => 2], + ['name' => 'Weihnachten', 'starts_on' => '2026-12-19', 'ends_on' => '2026-12-26', 'nightly_rate' => 8500, 'min_nights' => 4], + ['name' => 'Neujahr', 'starts_on' => '2026-12-26', 'ends_on' => '2027-01-03', 'nightly_rate' => 11500, 'min_nights' => 6], + ]); + + $property->extras()->createMany([ + ['name' => 'Bettwäsche', 'description' => 'Betten werden bei Anreise bezogen', 'price' => 1400, 'pricing' => ExtraPricing::PerItem, 'sort_order' => 1], + ['name' => 'Handtuchpaket', 'description' => '1 Badetuch, 1 Handtuch, 1 Duschvorleger', 'price' => 1100, 'pricing' => ExtraPricing::PerItem, 'sort_order' => 2], + ['name' => 'Bettwäsche + Handtuchpaket', 'description' => 'Kombipaket pro Person', 'price' => 2300, 'pricing' => ExtraPricing::PerItem, 'sort_order' => 3], + ]); + } +} diff --git a/docs/KONZEPT.md b/docs/KONZEPT.md index 231ff28..dfa7e33 100644 --- a/docs/KONZEPT.md +++ b/docs/KONZEPT.md @@ -23,8 +23,8 @@ ## 3. Technologie | Bereich | Wahl | Begründung | |---|---|---| -| Backend | **Laravel 12** (PHP 8.3+) | Läuft auf Shared Hosting, ausgereift, Queue/Scheduler/Mail/PDF eingebaut | -| Admin | **Filament** | Professionelles Verwaltungs-UI (Tabellen, Formulare, Kalender, Dashboards) ohne Eigenbau | +| Backend | **Laravel 13** (PHP 8.4) | Läuft auf Shared Hosting, ausgereift, Queue/Scheduler/Mail/PDF eingebaut | +| Admin | **Filament 5** | Professionelles Verwaltungs-UI (Tabellen, Formulare, Kalender, Dashboards) ohne Eigenbau | | Frontend | Blade + Tailwind CSS + Alpine.js/Livewire | Server-gerendert → schnell, SEO-stark, kaum JavaScript | | Datenbank | MySQL 8 (Strato), lokal SQLite | | | PDF | dompdf / Browsershot-frei | Läuft ohne Zusatzsoftware auf Shared Hosting | @@ -111,7 +111,7 @@ ## 9. Hosting & Deployment (Strato) ## 10. Umsetzungsphasen -1. **Fundament:** Laravel + Filament, Datenmodell, Saisons/Preise, Preisberechnung (mit Tests). +1. **Fundament:** Laravel + Filament, Datenmodell, Saisons/Preise, Preisberechnung (mit Tests). ✅ 2. **Kalender & Anfrage:** Belegung, Anfrageformular, Auto-Angebot per Mail. 3. **Buchungsworkflow:** Bestätigung, Mietvertrag-PDF, Zahlungsfristen & Erinnerungen. 4. **Webseite:** Design, Inhalte, Galerie, SEO, Barrierefreiheit. diff --git a/tests/Feature/PriceCalculatorTest.php b/tests/Feature/PriceCalculatorTest.php new file mode 100644 index 0000000..13cfeed --- /dev/null +++ b/tests/Feature/PriceCalculatorTest.php @@ -0,0 +1,167 @@ +calculator = new PriceCalculator; + } + + /** + * The old price list showed "first night incl. cleaning" plus "each further night". + * + * @return array + */ + public static function oldPriceListProvider(): array + { + return [ + 'Winter, 3 Nächte' => ['2026-01-10', '2026-01-13', 163_00 + 2 * 55_00], + 'Hochsaison, 7 Nächte' => ['2026-07-04', '2026-07-11', 223_00 + 6 * 115_00], + 'Zwischensaison, 2 Nächte' => ['2026-11-07', '2026-11-09', 173_00 + 65_00], + ]; + } + + #[DataProvider('oldPriceListProvider')] + public function test_totals_match_the_previous_price_list(string $arrival, string $departure, int $expectedTotal): void + { + $this->seed(PropertySeeder::class); + + $quote = $this->calculator->calculate(Property::sole(), CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2); + + $this->assertSame($expectedTotal, $quote->total()); + } + + public function test_stay_across_two_seasons_is_split_per_season(): void + { + $this->seed(PropertySeeder::class); + + $quote = $this->calculator->calculate(Property::sole(), CarbonImmutable::parse('2026-06-18'), CarbonImmutable::parse('2026-06-22'), 2); + + $accommodation = array_values(array_filter($quote->lines, fn ($line) => $line->type === QuoteLineType::Accommodation)); + $this->assertCount(2, $accommodation); + $this->assertSame([2, 9500], [$accommodation[0]->quantity, $accommodation[0]->unitPrice]); + $this->assertSame([2, 11500], [$accommodation[1]->quantity, $accommodation[1]->unitPrice]); + $this->assertSame(2 * 9500 + 2 * 11500 + 10800, $quote->total()); + } + + public function test_deposit_is_a_share_of_the_rent_and_balance_is_due_before_arrival(): void + { + $property = $this->propertyWithSeason(nightlyRate: 5500, cleaningFee: 10800, depositPercent: 35); + + $quote = $this->calculator->calculate($property, CarbonImmutable::parse('2026-03-10'), CarbonImmutable::parse('2026-03-13'), 3); + + $rent = 3 * 5500 + 3 * 750; + $this->assertSame($rent, $quote->rent()); + $this->assertSame((int) round($rent * 0.35), $quote->deposit()); + $this->assertSame($quote->total() - $quote->deposit(), $quote->balance()); + $this->assertSame('2026-02-10', $quote->balanceDueOn->toDateString()); + } + + public function test_extras_are_priced_per_item_or_per_night(): void + { + $property = $this->propertyWithSeason(); + $linen = Extra::factory()->for($property)->create(['price' => 1400, 'pricing' => ExtraPricing::PerItem]); + $babyBed = Extra::factory()->for($property)->create(['price' => 300, 'pricing' => ExtraPricing::PerNight]); + + $quote = $this->calculator->calculate($property, CarbonImmutable::parse('2026-03-10'), CarbonImmutable::parse('2026-03-14'), 2, [ + $linen->id => 2, + $babyBed->id => 1, + ]); + + $extras = array_values(array_filter($quote->lines, fn ($line) => $line->type === QuoteLineType::Extra)); + $this->assertSame([2 * 1400, 4 * 300], array_map(fn ($line) => $line->amount, $extras)); + } + + public function test_minimum_stay_of_the_arrival_season_is_enforced(): void + { + $this->seed(PropertySeeder::class); + + $this->expectException(QuoteException::class); + $this->expectExceptionMessage('Mindestaufenthalt 3 Nächte'); + + $this->calculator->calculate(Property::sole(), CarbonImmutable::parse('2026-08-29'), CarbonImmutable::parse('2026-08-31'), 2); + } + + public function test_nights_without_a_season_cannot_be_priced(): void + { + $property = $this->propertyWithSeason(); + + $this->expectException(QuoteException::class); + $this->expectExceptionMessage('01.04.2026'); + + $this->calculator->calculate($property, CarbonImmutable::parse('2026-03-30'), CarbonImmutable::parse('2026-04-02'), 2); + } + + public function test_guest_count_is_limited_by_the_property(): void + { + $property = $this->propertyWithSeason(); + + $this->expectException(QuoteException::class); + + $this->calculator->calculate($property, CarbonImmutable::parse('2026-03-10'), CarbonImmutable::parse('2026-03-12'), $property->max_guests + 1); + } + + public function test_departure_must_be_after_arrival(): void + { + $property = $this->propertyWithSeason(); + + $this->expectException(QuoteException::class); + + $this->calculator->calculate($property, CarbonImmutable::parse('2026-03-10'), CarbonImmutable::parse('2026-03-10'), 2); + } + + public function test_inactive_extras_cannot_be_booked(): void + { + $property = $this->propertyWithSeason(); + $extra = Extra::factory()->for($property)->create(['is_active' => false]); + + $this->expectException(QuoteException::class); + + $this->calculator->calculate($property, CarbonImmutable::parse('2026-03-10'), CarbonImmutable::parse('2026-03-12'), 2, [$extra->id => 1]); + } + + /** + * A property with a single season covering March 2026. + */ + private function propertyWithSeason(int $nightlyRate = 5500, int $cleaningFee = 10800, int $depositPercent = 35): Property + { + $property = Property::factory()->create([ + 'max_guests' => 3, + 'included_guests' => 2, + 'extra_guest_fee_per_night' => 750, + 'cleaning_fee' => $cleaningFee, + 'deposit_percent' => $depositPercent, + 'balance_due_days_before_arrival' => 28, + ]); + + Season::factory()->for($property)->create([ + 'starts_on' => '2026-03-01', + 'ends_on' => '2026-04-01', + 'nightly_rate' => $nightlyRate, + 'min_nights' => 2, + ]); + + return $property; + } +} diff --git a/tests/Feature/SeasonManagementTest.php b/tests/Feature/SeasonManagementTest.php new file mode 100644 index 0000000..5bad351 --- /dev/null +++ b/tests/Feature/SeasonManagementTest.php @@ -0,0 +1,129 @@ +actingAs(User::factory()->create()); + $this->property = Property::factory()->create(); + Season::factory()->for($this->property)->create([ + 'name' => 'Winter', + 'starts_on' => '2026-01-03', + 'ends_on' => '2026-03-07', + ]); + } + + public function test_season_is_created_with_euro_amounts_stored_as_cents(): void + { + $this->seasonsManager() + ->callAction(TestAction::make(CreateAction::class)->table(), [ + 'name' => 'Nebensaison', + 'starts_on' => '2026-03-07', + 'ends_on' => '2026-04-03', + 'nightly_rate' => '65.50', + 'min_nights' => 2, + ]) + ->assertHasNoFormErrors(); + + $this->assertDatabaseHas('seasons', [ + 'property_id' => $this->property->id, + 'name' => 'Nebensaison', + 'nightly_rate' => 6550, + ]); + } + + public function test_overlapping_season_is_rejected(): void + { + $this->seasonsManager() + ->callAction(TestAction::make(CreateAction::class)->table(), [ + 'name' => 'Überschneidung', + 'starts_on' => '2026-03-01', + 'ends_on' => '2026-03-14', + 'nightly_rate' => '70', + 'min_nights' => 2, + ]) + ->assertHasFormErrors(['starts_on']); + + $this->assertDatabaseMissing('seasons', ['name' => 'Überschneidung']); + } + + public function test_uncovered_periods_are_reported(): void + { + Season::factory()->for($this->property)->create(['starts_on' => '2026-04-03', 'ends_on' => '2026-05-23']); + + $gaps = $this->property->uncoveredPeriods(CarbonImmutable::parse('2026-01-01'), CarbonImmutable::parse('2026-06-01')); + + $this->assertSame( + [['2026-01-01', '2026-01-03'], ['2026-03-07', '2026-04-03'], ['2026-05-23', '2026-06-01']], + array_map(fn (array $gap): array => [$gap['from']->toDateString(), $gap['until']->toDateString()], $gaps), + ); + } + + public function test_seasons_are_copied_to_the_next_year_without_overwriting(): void + { + Season::factory()->for($this->property)->create(['name' => 'Bereits gepflegt', 'starts_on' => '2027-01-10', 'ends_on' => '2027-01-20']); + Season::factory()->for($this->property)->create(['name' => 'Sommer', 'starts_on' => '2026-06-20', 'ends_on' => '2026-08-29', 'nightly_rate' => 11500]); + + $result = (new CopySeasonsToNextYear)->handle($this->property, 2026); + + $this->assertSame(['created' => 1, 'skipped' => 1], $result); + $this->assertTrue($this->property->seasons() + ->where('name', 'Sommer') + ->where('nightly_rate', 11500) + ->whereDate('starts_on', '2027-06-20') + ->whereDate('ends_on', '2027-08-29') + ->exists()); + } + + public function test_admin_pages_render(): void + { + $this->get(PropertyResource::getUrl('index'))->assertOk()->assertSee($this->property->name); + $this->get(PropertyResource::getUrl('edit', ['record' => $this->property]))->assertOk(); + + $this->seasonsManager() + ->set('tableFilters.year.value', '2026') + ->assertCanSeeTableRecords($this->property->seasons) + ->assertSee('Ohne Preis'); + } + + public function test_price_calculator_action_shows_the_total(): void + { + $this->seasonsManager() + ->callAction(TestAction::make('calculatePrice')->table(), [ + 'arrival' => '2026-01-10', + 'departure' => '2026-01-13', + 'guests' => 2, + ]) + ->assertNotified(); + } + + private function seasonsManager(): mixed + { + return Livewire::test(SeasonsRelationManager::class, [ + 'ownerRecord' => $this->property, + 'pageClass' => EditProperty::class, + ]); + } +}