Phase 1: Wohnungen, Saisons & Preisberechnung

- 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 <noreply@anthropic.com>
This commit is contained in:
Lars StommerandClaude Opus 5.5 committed 2026-10-22 09:19:49 +02:00
1 parent bf4c1c0838
commit 2e9a391b37
35 files changed
+1766 -12

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
<?php
namespace App\Actions;
use App\Models\Property;
/**
* 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.
*/
class CopySeasonsToNextYear
{
/**
* @return array{created: int, skipped: int}
*/
public function handle(Property $property, int $year): array
{
$created = 0;
$skipped = 0;
$seasons = $property->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];
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum ExtraPricing: string implements HasLabel
{
case PerItem = 'per_item';
case PerNight = 'per_night';
public function getLabel(): string
{
return match ($this) {
self::PerItem => 'pro Stück (einmalig)',
self::PerNight => 'pro Stück und Nacht',
};
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Enums;
enum QuoteLineType: string
{
case Accommodation = 'accommodation';
case ExtraGuest = 'extra_guest';
case Cleaning = 'cleaning';
case Extra = 'extra';
/**
* Whether the line counts towards the rent on which the deposit is calculated.
*/
public function isRent(): bool
{
return in_array($this, [self::Accommodation, self::ExtraGuest], true);
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Filament\Forms\Components;
use Filament\Forms\Components\TextInput;
/**
* Edits an amount stored in euro cents as a euro value with two decimals.
*/
class EuroInput extends TextInput
{
protected function setUp(): void
{
parent::setUp();
$this
->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));
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Properties\Pages;
use App\Filament\Resources\Properties\PropertyResource;
use Filament\Resources\Pages\CreateRecord;
class CreateProperty extends CreateRecord
{
protected static string $resource = PropertyResource::class;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Properties\Pages;
use App\Filament\Resources\Properties\PropertyResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditProperty extends EditRecord
{
protected static string $resource = PropertyResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Properties\Pages;
use App\Filament\Resources\Properties\PropertyResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListProperties extends ListRecords
{
protected static string $resource = PropertyResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\Properties;
use App\Filament\Resources\Properties\Pages\CreateProperty;
use App\Filament\Resources\Properties\Pages\EditProperty;
use App\Filament\Resources\Properties\Pages\ListProperties;
use App\Filament\Resources\Properties\RelationManagers\ExtrasRelationManager;
use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager;
use App\Filament\Resources\Properties\Schemas\PropertyForm;
use App\Filament\Resources\Properties\Tables\PropertiesTable;
use App\Models\Property;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
class PropertyResource extends Resource
{
protected static ?string $model = Property::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedHomeModern;
protected static ?string $modelLabel = 'Wohnung';
protected static ?string $pluralModelLabel = 'Wohnungen';
protected static ?string $recordTitleAttribute = 'name';
public static function form(Schema $schema): Schema
{
return PropertyForm::configure($schema);
}
public static function table(Table $table): Table
{
return PropertiesTable::configure($table);
}
public static function getRelations(): array
{
return [
SeasonsRelationManager::class,
ExtrasRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => ListProperties::route('/'),
'create' => CreateProperty::route('/create'),
'edit' => EditProperty::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,82 @@
<?php
namespace App\Filament\Resources\Properties\RelationManagers;
use App\Enums\ExtraPricing;
use App\Filament\Forms\Components\EuroInput;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class ExtrasRelationManager extends RelationManager
{
protected static string $relationship = 'extras';
protected static ?string $title = 'Zusatzleistungen';
protected static ?string $modelLabel = 'Zusatzleistung';
protected static ?string $pluralModelLabel = 'Zusatzleistungen';
public function form(Schema $schema): Schema
{
return $schema
->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(),
]);
}
}
@@ -0,0 +1,256 @@
<?php
namespace App\Filament\Resources\Properties\RelationManagers;
use App\Actions\CopySeasonsToNextYear;
use App\Filament\Forms\Components\EuroInput;
use App\Models\Property;
use App\Models\Season;
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\QuoteLine;
use Carbon\CarbonImmutable;
use Closure;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ReplicateAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Number;
class SeasonsRelationManager extends RelationManager
{
protected static string $relationship = 'seasons';
protected static ?string $title = 'Saisons & Preise';
protected static ?string $modelLabel = 'Saison';
protected static ?string $pluralModelLabel = 'Saisons';
public function form(Schema $schema): Schema
{
return $schema
->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<string, string>
*/
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('<br>');
Notification::make()
->title('Gesamtpreis: '.$euro($quote->total()))
->body($lines)
->success()
->persistent()
->send();
});
}
}
@@ -0,0 +1,99 @@
<?php
namespace App\Filament\Resources\Properties\Schemas;
use App\Filament\Forms\Components\EuroInput;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\TimePicker;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Illuminate\Support\Str;
class PropertyForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->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),
]),
]);
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Filament\Resources\Properties\Tables;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class PropertiesTable
{
public static function configure(Table $table): Table
{
return $table
->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(),
]);
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Models;
use App\Enums\ExtraPricing;
use Database\Factories\ExtraFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* An optional bookable service such as bed linen or towels.
*/
#[Fillable(['property_id', 'name', 'description', 'price', 'pricing', 'is_active', 'sort_order'])]
class Extra extends Model
{
/** @use HasFactory<ExtraFactory> */
use HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'pricing' => ExtraPricing::class,
'is_active' => 'boolean',
];
}
/**
* @return BelongsTo<Property, $this>
*/
public function property(): BelongsTo
{
return $this->belongsTo(Property::class);
}
/**
* @param Builder<Extra> $query
* @return Builder<Extra>
*/
#[Scope]
protected function active(Builder $query): Builder
{
return $query->where('is_active', true);
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Models;
use Carbon\CarbonImmutable;
use Database\Factories\PropertyFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* A rentable holiday apartment. All money amounts are stored in euro cents.
*/
#[Fillable([
'name',
'slug',
'address',
'size_sqm',
'max_guests',
'included_guests',
'extra_guest_fee_per_night',
'cleaning_fee',
'deposit_percent',
'balance_due_days_before_arrival',
'check_in_time',
'check_out_time',
'is_active',
])]
class Property extends Model
{
/** @use HasFactory<PropertyFactory> */
use HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_active' => 'boolean',
];
}
/**
* @return HasMany<Season, $this>
*/
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<array{from: CarbonImmutable, until: CarbonImmutable}>
*/
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<Extra, $this>
*/
public function extras(): HasMany
{
return $this->hasMany(Extra::class)->orderBy('sort_order');
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Models;
use Carbon\CarbonInterface;
use Database\Factories\SeasonFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A pricing period. A night belongs to the season when starts_on <= night < ends_on,
* so consecutive seasons share their boundary date (e.g. 03.01.–07.03. and 07.03.–03.04.).
*/
#[Fillable(['property_id', 'name', 'starts_on', 'ends_on', 'nightly_rate', 'min_nights'])]
class Season extends Model
{
/** @use HasFactory<SeasonFactory> */
use HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'starts_on' => 'immutable_date',
'ends_on' => 'immutable_date',
];
}
/**
* @return BelongsTo<Property, $this>
*/
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<Season> $query
* @return Builder<Season>
*/
#[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);
}
}
+11 -1
View File
@@ -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<UserFactory> */
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.
*
+133
View File
@@ -0,0 +1,133 @@
<?php
namespace App\Pricing;
use App\Enums\ExtraPricing;
use App\Enums\QuoteLineType;
use App\Models\Extra;
use App\Models\Property;
use App\Models\Season;
use Carbon\CarbonImmutable;
use Illuminate\Support\Collection;
class PriceCalculator
{
/**
* Price a stay from $arrival (first night) to $departure (day of departure, not a night).
*
* @param array<int, int> $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<QuoteLine>
*/
private function accommodationLines(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure): array
{
/** @var Collection<int, Season> $seasons */
$seasons = $property->seasons()->overlapping($arrival, $departure)->get();
/** @var list<array{season: Season, nights: int}> $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<int, int> $extraQuantities
* @return list<QuoteLine>
*/
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;
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace App\Pricing;
use Carbon\CarbonImmutable;
/**
* The complete price of a stay. Amounts are in euro cents.
*/
final readonly class PriceQuote
{
/**
* @param list<QuoteLine> $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<array<string, mixed>>, 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(),
];
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Pricing;
use Carbon\CarbonInterface;
use RuntimeException;
/**
* A stay that cannot be priced. Messages are shown to guests and administrators.
*/
class QuoteException extends RuntimeException
{
public static function invalidPeriod(): self
{
return new self('Die Abreise muss nach der Anreise liegen.');
}
public static function invalidGuestCount(int $maxGuests): self
{
return new self("Die Wohnung bietet Platz für 1 bis {$maxGuests} Personen.");
}
public static function noRateForNight(CarbonInterface $night): self
{
return new self("Für den {$night->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.");
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Pricing;
use App\Enums\QuoteLineType;
/**
* One position of a price quote. Amounts are in euro cents.
*/
final readonly class QuoteLine
{
public function __construct(
public QuoteLineType $type,
public string $label,
public int $quantity,
public int $unitPrice,
public int $amount,
) {}
/**
* @return array{type: string, label: string, quantity: int, unit_price: int, amount: int}
*/
public function toArray(): array
{
return [
'type' => $this->type->value,
'label' => $this->label,
'quantity' => $this->quantity,
'unit_price' => $this->unitPrice,
'amount' => $this->amount,
];
}
}
@@ -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,