Files
fewo-stommer/app/Filament/Resources/Properties/RelationManagers/SeasonsRelationManager.php
T

293 lines
12 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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 App\Pricing\StayRequest;
use App\Support\Money;
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\Forms\Components\Toggle;
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;
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';
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->minimumStayRulesAction(),
$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();
}
/**
* 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 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'], filled($data['weekday'] ?? null) ? (int) $data['weekday'] : null);
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),
TextInput::make('promo_code')
->label('Aktionscode (optional)'),
])
->action(function (array $data, PriceCalculator $calculator): void {
try {
$quote = $calculator->calculate($this->getOwnerRecord(), new StayRequest(
CarbonImmutable::parse($data['arrival']),
CarbonImmutable::parse($data['departure']),
(int) $data['guests'],
promoCode: $data['promo_code'] ?? null,
));
} catch (QuoteException $exception) {
Notification::make()->title('Nicht buchbar')->body($exception->getMessage())->danger()->send();
return;
}
$lines = collect($quote->lines)
->map(fn (QuoteLine $line): string => e($line->label).': '.Money::format($line->amount))
->push('Anzahlung: '.Money::format($quote->deposit()).' · Rest: '.Money::format($quote->balance()).' fällig am '.$quote->balanceDueOn->format('d.m.Y'))
->implode('<br>');
Notification::make()
->title('Gesamtpreis: '.Money::format($quote->total()))
->body($lines)
->success()
->persistent()
->send();
});
}
}