Stornoregeln mit automatischer Kostenberechnung, Storno-Verwaltung, Vertragsanlagen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m34s

- Stornoregel (Stufen nach Tagen vor Anreise, Mietpreis oder Gesamtpreis, Ersatzmieter-Gebuehr), je Vertragsvorlage,
  beim Angebot eingefroren, als Platzhalter im Vertrag
- Stornierung (Gast-Link oder Verwaltung) berechnet die Kosten, legt einen Stornofall an; Verwaltung Stornierungen
  mit Vorschlag, Festlegung, Saldo, Abrechnung und Erlass; Gast sieht die Kosten vorab auf der Storno-Seite
- Vertragsanlagen als eigene versionierte Dokumente mit Bedingung (immer, Zusatzleistung, Portal, von Hand),
  je Angebot ausgewaehlt und eingefroren; Zusatzleistungen in der Buchung erfassbar
- FeWo-direkt-Installation legt die Stornoregel aus Paragraf 13 an

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Sonnet 5.5 committed 2026-10-30 16:32:48 +01:00
1 parent 5baf39441f
commit 0c4187edaf
37 files changed
+1440 -10

No files matched your search

+9 -1
View File
@@ -10,6 +10,8 @@
use App\Mail\CancellationRequested;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Support\CancellationCost;
use App\Support\Money;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
@@ -42,12 +44,18 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa
}
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
app(RecordCancellation::class)->handle($booking, 'landlord');
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
if ($costsTask) {
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], ['status' => BookingTaskStatus::Open, 'due_on' => today()]);
$cost = CancellationCost::calculate($booking);
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], [
'status' => BookingTaskStatus::Open,
'due_on' => today(),
'note' => $cost ? 'Vorschlag nach Stornoregel „'.$cost['policy'].'“: '.Money::format($cost['fee']).' ('.$cost['tier_text'].')' : 'Keine Stornoregel hinterlegt – Kosten von Hand festlegen.',
]);
}
});
+5 -1
View File
@@ -11,6 +11,7 @@
use App\Mail\CancellationRequested;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Support\CancellationCost;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
@@ -34,7 +35,9 @@ public function modeFor(Booking $booking): CancellationMode
return match ($property->cancellation_mode) {
CancellationMode::Instant => CancellationMode::Instant,
CancellationMode::InstantWhenFree => today()->lessThanOrEqualTo($freeUntil) ? CancellationMode::Instant : CancellationMode::Request,
CancellationMode::InstantWhenFree => ($cost = CancellationCost::calculate($booking)) !== null
? ($cost['free'] ? CancellationMode::Instant : CancellationMode::Request)
: (today()->lessThanOrEqualTo($freeUntil) ? CancellationMode::Instant : CancellationMode::Request),
default => CancellationMode::Request,
};
}
@@ -60,6 +63,7 @@ public function handle(Booking $booking, ?string $message = null): ?Cancellation
$mode = $this->modeFor($booking);
if ($mode === CancellationMode::Instant) {
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
app(RecordCancellation::class)->handle($booking, 'guest');
}
BookingTask::query()->create([
'booking_id' => $booking->id,
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Actions;
use App\Models\Booking;
use App\Models\Cancellation;
use App\Support\CancellationCost;
/**
* Records the cancellation of a booking with the cost proposed by the frozen cancellation rule. Called when a booking
* is cancelled (by the landlord or through the guest's link); safe to call twice.
*/
class RecordCancellation
{
public function handle(Booking $booking, string $initiatedBy): Cancellation
{
$cost = CancellationCost::calculate($booking);
return Cancellation::query()->firstOrCreate(
['booking_id' => $booking->id],
[
'cancelled_on' => today(),
'initiated_by' => $initiatedBy,
'has_policy' => $cost !== null,
'policy_name' => $cost['policy'] ?? null,
'days_before' => $cost['days_before'] ?? null,
'percent' => $cost['percent'] ?? null,
'base_amount' => $cost['base_amount'] ?? null,
'calculated_fee' => $cost['fee'] ?? null,
'paid_amount' => $booking->paidAmount(),
'status' => Cancellation::OPEN,
],
);
}
}
+2 -2
View File
@@ -42,7 +42,7 @@ public function __construct(
) {}
/**
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, guest?: array<string, ?string>} $changes
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, annex_ids?: ?list<int|string>, guest?: array<string, ?string>} $changes
*
* @throws QuoteException
* @throws ReservationException
@@ -97,7 +97,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
'offer_version' => $booking->offer_version + 1,
'offer_sent_at' => now(),
'offer_message' => $changes['offer_message'] ?? null,
'offer_terms' => OfferTerms::capture(OfferTerms::templateFor($booking, $changes['contract_template_id'] ?? null), $booking),
'offer_terms' => OfferTerms::capture(OfferTerms::templateFor($booking, $changes['contract_template_id'] ?? null), $booking, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null),
]);
$booking->refresh();
$booking->update(['offer_hash' => OfferTerms::hash($booking)]);
@@ -2,6 +2,7 @@
namespace App\Console\Commands;
use App\Models\CancellationPolicy;
use App\Models\ContractTemplate;
use App\Models\Property;
use App\Models\Tenant;
@@ -45,6 +46,14 @@ public function handle(TenantRunner $runner): int
$this->info("{$tenant->name}: Vorlage „".self::NAME.'“ angelegt.');
}
$policy = CancellationPolicy::query()->firstOrCreate(['name' => 'Direktbuchung Standard'], [
'base' => CancellationPolicy::BASE_RENT,
'tiers' => [['min_days' => 60, 'percent' => 0], ['min_days' => 30, 'percent' => 50], ['min_days' => 0, 'percent' => 100]],
'replacement_fee' => 3500,
'notes' => 'Staffel und Ersatzmieter-Gebühr aus § 13 des FeWo-direkt-Vertrags, berechnet vom Mietpreis. Bitte prüfen.',
]);
ContractTemplate::query()->where('name', self::NAME)->whereNull('cancellation_policy_id')->update(['cancellation_policy_id' => $policy->id]);
if ($data !== []) {
$property = Property::query()->first();
if ($property !== null) {
+15 -1
View File
@@ -3,6 +3,7 @@
namespace App\Documents;
use App\Models\Booking;
use App\Models\CancellationPolicy;
use App\Support\Money;
/**
@@ -12,6 +13,9 @@
*/
class ContractPlaceholders
{
/** Placeholders whose value is already safe HTML. */
private const RAW = ['storno_regel'];
private const PATTERN = '/\{\{\s*([a-z][a-z0-9_]*(?:\.[a-z0-9_]+)?)\s*\}\}/i';
/**
@@ -44,6 +48,7 @@ public static function catalog(): array
'checkin' => 'Anreisezeit (Uhr)',
'checkout' => 'Abreisezeit (Uhr)',
'portal' => 'Name des Portals (leer bei eigener Buchung)',
'storno_regel' => 'Die Stornoregel dieser Vorlage als Aufzählung (Stufen und Prozent)',
'wohnung.<name>' => 'Eigene Wohnungsdaten (Wohnung bearbeiten › Vertragsdaten), z. B. wohnung.wlan_passwort',
];
}
@@ -58,7 +63,11 @@ public static function render(string $html, Booking $booking, array $propertyDat
return (string) preg_replace_callback(self::PATTERN, function (array $match) use ($values): string {
$key = strtolower($match[1]);
return array_key_exists($key, $values) && $values[$key] !== null ? e((string) $values[$key]) : '[<b>'.e($key).'?</b>]';
if (! array_key_exists($key, $values) || $values[$key] === null) {
return '[<b>'.e($key).'?</b>]';
}
return in_array($key, self::RAW, true) ? (string) $values[$key] : e((string) $values[$key]);
}, $html);
}
@@ -113,6 +122,11 @@ private static function values(Booking $booking, array $propertyData): array
'portal' => ($booking->importChannel ?? $booking->originChannel)?->name ?? '',
];
$policy = $booking->offer_terms['cancellation_policy'] ?? null;
if (is_array($policy) && ! empty($policy['tiers'])) {
$values['storno_regel'] = '<ul>'.collect(CancellationPolicy::describe($policy))->map(fn (string $line): string => '<li>'.e($line).'</li>')->implode('').'</ul>';
}
foreach ($propertyData as $name => $value) {
$values['wohnung.'.strtolower((string) $name)] = is_scalar($value) ? (string) $value : null;
}
+25 -1
View File
@@ -4,6 +4,7 @@
use App\Enums\ChannelBookingModel;
use App\Models\Booking;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Support\Content;
use Filament\Forms\Components\RichEditor\RichContentRenderer;
@@ -32,14 +33,20 @@ class OfferTerms
/**
* @return array{captured_at: string, template: ?array{id: int, name: string, version: int}, texts: array<string, ?string>, deposit_due_days: int, owner: array<string, mixed>, bank: array<string, mixed>}
*/
public static function capture(?ContractTemplate $template = null, ?Booking $booking = null): array
public static function capture(?ContractTemplate $template = null, ?Booking $booking = null, ?array $annexIds = null): array
{
$overrides = $template?->overrides() ?? [];
$annexes = $annexIds !== null
? ContractAnnex::query()->whereIn('id', $annexIds)->orderBy('name')->get()
: ($template !== null && $booking !== null ? $template->annexesFor($booking) : collect());
return [
'captured_at' => now()->toIso8601String(),
'template' => $template ? ['id' => $template->id, 'name' => $template->name, 'version' => $template->version] : null,
'document' => $template?->hasDocument() ? ['body' => $template->body, 'annex_title' => $template->annex_title, 'annex_body' => $template->annex_body] : null,
'annex_ids' => $annexes->pluck('id')->all(),
'annexes' => $annexes->map(fn (ContractAnnex $annex): array => ['id' => $annex->id, 'name' => $annex->name, 'version' => $annex->version, 'title' => $annex->title, 'body' => $annex->body])->values()->all(),
'cancellation_policy' => $template?->cancellationPolicy?->snapshot(),
'property_data' => (array) ($booking?->property?->contract_data ?? []),
'texts' => collect(self::TEXT_KEYS)->mapWithKeys(fn (string $key): array => [$key => $overrides[$key] ?? Content::get($key)])->all(),
'deposit_due_days' => (int) config('fewo.deposit_due_days'),
@@ -81,6 +88,23 @@ public static function document(Booking $booking): ?array
return ['body' => (string) $render($document['body']), 'annex_title' => $document['annex_title'] ?? null, 'annex' => $render($document['annex_body'] ?? null)];
}
/**
* The annexes frozen in the offer, with placeholders filled.
*
* @return list<array{title: string, name: string, version: int, html: string}>
*/
public static function annexes(Booking $booking): array
{
$data = (array) ($booking->offer_terms['property_data'] ?? []);
return collect((array) ($booking->offer_terms['annexes'] ?? []))->map(fn (array $annex): array => [
'title' => (string) $annex['title'],
'name' => (string) $annex['name'],
'version' => (int) $annex['version'],
'html' => (string) RichContentRenderer::make(ContractPlaceholders::render((string) $annex['body'], $booking, $data))->toHtml(),
])->values()->all();
}
public static function text(Booking $booking, string $key): ?string
{
$texts = $booking->offer_terms['texts'] ?? null;
+2
View File
@@ -7,6 +7,7 @@
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\BookingTasks\BookingTaskResource;
use App\Filament\Resources\Cancellations\CancellationResource;
use App\Filament\Resources\Channels\ChannelResource;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use App\Filament\Resources\Guests\GuestResource;
@@ -39,6 +40,7 @@ enum AdminMode: string implements HasDescription, HasLabel
GuestResource::class,
ChannelTaskResource::class,
BookingTaskResource::class,
CancellationResource::class,
ChannelResource::class,
ReviewResource::class,
PhotoResource::class,
@@ -6,13 +6,16 @@
use App\Actions\ConfirmBooking;
use App\Actions\DeclineBooking;
use App\Actions\SendOffer;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Filament\Actions\AssignGuestAction;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\Booking;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Models\Extra;
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
@@ -22,6 +25,7 @@
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
@@ -88,7 +92,13 @@ protected function getHeaderActions(): array
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80),
Text::make(fn (Get $get): string => $this->offerPricePreview($get))->columnSpanFull(),
]),
Section::make('Vertragsvorlage')->schema([
Section::make('Vertragsvorlage und Anlagen')->schema([
Select::make('annex_ids')
->label('Anlagen')
->multiple()
->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all())
->default(fn (): array => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? [])
->helperText('Vorausgewählt: Anlagen der Vorlage, deren Bedingung zu dieser Buchung passt (z. B. gebuchtes Wäschepaket). Sie können Anlagen hinzufügen oder entfernen.'),
Select::make('contract_template_id')
->label('Vorlage für dieses Angebot')
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
@@ -190,6 +200,31 @@ protected function getHeaderActions(): array
$notification = Notification::make()->title($sent ? 'Bestätigung gesendet' : 'Versand fehlgeschlagen');
($sent ? $notification->success() : $notification->danger()->body('Details im Postfach.'))->send();
}),
Action::make('services')
->label('Zusatzleistungen erfassen')
->icon(Heroicon::OutlinedPlusCircle)
->color('gray')
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true))
->modalDescription('Gebuchte Zusatzleistungen (kostenpflichtig oder kostenlos), z. B. aus einer Portalbuchung oder per E-Mail erfragt. Sie bestimmen, welche Vertragsanlagen angehängt werden. Der Preis der Buchung wird dadurch nicht verändert.')
->fillForm(fn (): array => ['items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all()])
->schema([
Repeater::make('items')
->label('Leistungen')
->schema([
Select::make('extra_id')->label('Leistung')->options(fn (): array => Extra::query()->orderBy('name')->get()->mapWithKeys(fn (Extra $extra): array => [$extra->id => $extra->name.($extra->price > 0 ? ' ('.Money::format($extra->price).')' : ' (kostenlos)')])->all())->required(),
TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(),
])
->columns(2)
->addActionLabel('Leistung hinzufügen'),
])
->action(function (array $data): void {
$extras = [];
foreach ((array) ($data['items'] ?? []) as $item) {
$extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) $item['quantity']);
}
$this->record->update(['extras' => $extras]);
Notification::make()->title('Zusatzleistungen gespeichert')->success()->send();
}),
Action::make('contractText')
->label('Vertragstext ansehen')
->icon(Heroicon::OutlinedDocumentMagnifyingGlass)
@@ -0,0 +1,93 @@
<?php
namespace App\Filament\Resources\CancellationPolicies;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Resources\CancellationPolicies\Pages\CreateCancellationPolicy;
use App\Filament\Resources\CancellationPolicies\Pages\EditCancellationPolicy;
use App\Filament\Resources\CancellationPolicies\Pages\ListCancellationPolicies;
use App\Models\CancellationPolicy;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;
use UnitEnum;
/**
* Cancellation rules: stepped percentages by days before arrival. Assigned to contract templates.
*/
class CancellationPolicyResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = CancellationPolicy::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedReceiptPercent;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static ?string $modelLabel = 'Stornoregel';
protected static ?string $pluralModelLabel = 'Stornoregeln';
protected static ?int $navigationSort = 7;
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('name')->label('Name')->required()->maxLength(120)->helperText('z. B. „Direktbuchung“ oder „FeWo-direkt“.'),
Select::make('base')
->label('Berechnungsgrundlage')
->options([CancellationPolicy::BASE_RENT => 'Mietpreis (ohne Endreinigung, Service und Kurtaxe)', CancellationPolicy::BASE_TOTAL => 'Gesamtpreis'])
->default(CancellationPolicy::BASE_RENT)
->required(),
Repeater::make('tiers')
->label('Stufen')
->helperText('Jede Stufe gilt, wenn bis zur Anreise mindestens so viele Tage bleiben. Beispiel: ab 60 Tagen 0 %, ab 30 Tagen 50 %, ab 0 Tagen 100 %. Die letzte Stufe (0 Tage) gilt für alles danach.')
->schema([
TextInput::make('min_days')->label('Ab Tagen vor Anreise')->integer()->minValue(0)->required(),
TextInput::make('percent')->label('Entschädigung')->integer()->minValue(0)->maxValue(100)->suffix('%')->required(),
])
->columns(2)
->default([['min_days' => 60, 'percent' => 0], ['min_days' => 30, 'percent' => 50], ['min_days' => 0, 'percent' => 100]])
->minItems(1)
->required()
->columnSpanFull(),
EuroInput::make('replacement_fee')->label('Gebühr bei Ersatzmieter (optional)'),
Text::make(fn (?CancellationPolicy $record): HtmlString => new HtmlString($record ? '<strong>So steht es im Vertrag ({{ storno_regel }}):</strong><ul style="margin-top:.4rem">'.collect(CancellationPolicy::describe($record->snapshot()))->map(fn (string $line): string => '<li>'.e($line).'</li>')->implode('').'</ul>' : ''))->columnSpanFull(),
Textarea::make('notes')->label('Interne Notiz')->rows(2)->columnSpanFull(),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('name')
->columns([
TextColumn::make('name')->label('Regel')->weight('medium')->searchable(),
TextColumn::make('base')->label('Grundlage')->formatStateUsing(fn (string $state): string => $state === CancellationPolicy::BASE_TOTAL ? 'Gesamtpreis' : 'Mietpreis'),
TextColumn::make('steps')->label('Stufen')->state(fn (CancellationPolicy $record): string => collect(CancellationPolicy::normalise((array) $record->tiers))->map(fn (array $tier): string => 'ab '.$tier['min_days'].' T: '.$tier['percent'].' %')->implode(' · ')),
])
->recordActions([EditAction::make(), DeleteAction::make()]);
}
public static function getPages(): array
{
return [
'index' => ListCancellationPolicies::route('/'),
'create' => CreateCancellationPolicy::route('/create'),
'edit' => EditCancellationPolicy::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Filament\Resources\CancellationPolicies\Pages;
use App\Filament\Resources\CancellationPolicies\CancellationPolicyResource;
use App\Models\CancellationPolicy;
use Filament\Resources\Pages\CreateRecord;
class CreateCancellationPolicy extends CreateRecord
{
protected static string $resource = CancellationPolicyResource::class;
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['tiers'] = CancellationPolicy::normalise((array) ($data['tiers'] ?? []));
return $data;
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Filament\Resources\CancellationPolicies\Pages;
use App\Filament\Resources\CancellationPolicies\CancellationPolicyResource;
use App\Models\CancellationPolicy;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditCancellationPolicy extends EditRecord
{
protected static string $resource = CancellationPolicyResource::class;
protected function getHeaderActions(): array
{
return [DeleteAction::make()];
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
$data['tiers'] = CancellationPolicy::normalise((array) ($data['tiers'] ?? []));
return $data;
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\CancellationPolicies\Pages;
use App\Filament\Resources\CancellationPolicies\CancellationPolicyResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListCancellationPolicies extends ListRecords
{
protected static string $resource = CancellationPolicyResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()];
}
}
@@ -0,0 +1,119 @@
<?php
namespace App\Filament\Resources\Cancellations;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Cancellations\Pages\ListCancellations;
use App\Models\Cancellation;
use App\Support\Money;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Resource;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use UnitEnum;
/**
* Cancellation management: every cancelled booking with the days before arrival, the cost proposed by its
* cancellation rule, the amount finally charged, what was paid and what is still to collect or refund.
*/
class CancellationResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = Cancellation::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedArchiveBoxXMark;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static ?string $modelLabel = 'Stornierung';
protected static ?string $pluralModelLabel = 'Stornierungen';
protected static ?int $navigationSort = 5;
public static function table(Table $table): Table
{
return $table
->defaultSort('cancelled_on', 'desc')
->description('Storno-Verwaltung: Kosten werden nach der Stornoregel der Vertragsvorlage vorgeschlagen. Sie legen den Betrag endgültig fest, rechnen ab oder erlassen ihn. Gäste erhalten hierzu keine automatische Mail.')
->columns([
TextColumn::make('booking.reference')->label('Buchung')->weight('medium')->description(fn (Cancellation $record): string => $record->booking->guest?->full_name ?? ''),
TextColumn::make('cancelled_on')->label('Storniert am')->date('d.m.Y')->description(fn (Cancellation $record): string => $record->initiated_by === 'guest' ? 'durch den Gast' : 'durch die Verwaltung'),
TextColumn::make('days_before')->label('Tage vor Anreise')->placeholder('–'),
TextColumn::make('policy_name')->label('Stornoregel')->placeholder('Keine Regel')->description(fn (Cancellation $record): ?string => $record->percent !== null ? $record->percent.' % von '.Money::format((int) $record->base_amount) : null),
TextColumn::make('calculated_fee')->label('Vorschlag')->formatStateUsing(fn (?int $state): string => $state === null ? '–' : Money::format($state)),
TextColumn::make('final_fee')->label('Festgelegt')->formatStateUsing(fn (?int $state): string => $state === null ? '–' : Money::format($state)),
TextColumn::make('paid_amount')->label('Bezahlt')->formatStateUsing(fn (int $state): string => Money::format($state)),
TextColumn::make('balance')->label('Saldo')->state(fn (Cancellation $record): string => $record->balance() > 0 ? Money::format($record->balance()).' einzufordern' : ($record->balance() < 0 ? Money::format(-$record->balance()).' zu erstatten' : 'ausgeglichen')),
TextColumn::make('status')->label('Status')->badge()->formatStateUsing(fn (string $state): string => match ($state) {
Cancellation::SETTLED => 'Abgerechnet',
Cancellation::WAIVED => 'Erlassen',
default => 'Offen',
})->color(fn (string $state): string => $state === Cancellation::OPEN ? 'warning' : 'success'),
])
->filters([
SelectFilter::make('status')->label('Status')->options([Cancellation::OPEN => 'Offen', Cancellation::SETTLED => 'Abgerechnet', Cancellation::WAIVED => 'Erlassen'])->default(Cancellation::OPEN),
])
->recordActions([
Action::make('booking')->label('Buchung')->icon(Heroicon::OutlinedArrowTopRightOnSquare)->color('gray')
->url(fn (Cancellation $record): string => BookingResource::getUrl('view', ['record' => $record->booking])),
Action::make('decide')
->label('Kosten festlegen')
->icon(Heroicon::OutlinedPencilSquare)
->visible(fn (Cancellation $record): bool => $record->status === Cancellation::OPEN)
->fillForm(fn (Cancellation $record): array => ['final_fee' => $record->final_fee ?? $record->calculated_fee, 'note' => $record->note])
->schema([
EuroInput::make('final_fee')->label('Endgültige Stornokosten')->required(),
Textarea::make('note')->label('Begründung / Notiz')->rows(2),
])
->action(fn (array $data, Cancellation $record) => $record->update(['final_fee' => $data['final_fee'], 'note' => $data['note']])),
Action::make('settle')
->label('Abgerechnet')
->icon(Heroicon::OutlinedCheck)
->color('success')
->requiresConfirmation()
->modalDescription('Die Stornokosten sind beglichen bzw. Rückzahlung und Forderung sind erledigt.')
->visible(fn (Cancellation $record): bool => $record->status === Cancellation::OPEN)
->action(fn (Cancellation $record) => $record->update(['status' => Cancellation::SETTLED, 'settled_at' => now()])),
Action::make('waive')
->label('Erlassen')
->icon(Heroicon::OutlinedXMark)
->color('gray')
->requiresConfirmation()
->modalDescription('Es werden keine Stornokosten berechnet.')
->visible(fn (Cancellation $record): bool => $record->status === Cancellation::OPEN)
->action(fn (Cancellation $record) => $record->update(['status' => Cancellation::WAIVED, 'settled_at' => now()])),
]);
}
public static function canCreate(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
$open = Cancellation::query()->where('status', Cancellation::OPEN)->count();
return $open > 0 ? (string) $open : null;
}
public static function getNavigationBadgeColor(): string
{
return 'warning';
}
public static function getPages(): array
{
return [
'index' => ListCancellations::route('/'),
];
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Filament\Resources\Cancellations\Pages;
use App\Filament\Concerns\ListsCurrentProperty;
use App\Filament\Resources\Cancellations\CancellationResource;
use App\Models\Property;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\Builder;
class ListCancellations extends ListRecords
{
use ListsCurrentProperty;
protected static string $resource = CancellationResource::class;
protected function scopeToProperty(Builder $query, Property $property): Builder
{
return $query->whereHas('booking', fn (Builder $booking) => $booking->where('property_id', $property->id));
}
}
@@ -0,0 +1,135 @@
<?php
namespace App\Filament\Resources\ContractAnnexes;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Resources\ContractAnnexes\Pages\CreateContractAnnex;
use App\Filament\Resources\ContractAnnexes\Pages\EditContractAnnex;
use App\Filament\Resources\ContractAnnexes\Pages\ListContractAnnexes;
use App\Models\Channel;
use App\Models\ContractAnnex;
use App\Models\Extra;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
use UnitEnum;
/**
* Contract annexes as documents of their own, versioned, with a condition that decides per booking whether the
* annex is attached (always, when an extra service is booked, for a portal, only by hand).
*/
class ContractAnnexResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = ContractAnnex::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPaperClip;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static ?string $modelLabel = 'Vertragsanlage';
protected static ?string $pluralModelLabel = 'Vertragsanlagen';
protected static ?int $navigationSort = 8;
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('name')->label('Name (intern)')->required()->maxLength(120)->helperText('z. B. „WLAN“, „Wäschepaket“, „Key Pickup“. Versionen haben denselben Namen.'),
TextInput::make('title')->label('Überschrift im Vertrag')->required()->maxLength(200),
Select::make('condition_type')
->label('Wann wird die Anlage angehängt?')
->options([
ContractAnnex::ALWAYS => 'Immer, wenn die Vorlage sie enthält',
ContractAnnex::EXTRA => 'Wenn eine bestimmte Zusatzleistung gebucht ist',
ContractAnnex::CHANNEL => 'Nur bei Buchungen über ein bestimmtes Portal',
ContractAnnex::MANUAL => 'Nur von Hand (im Angebot auswählen)',
])
->default(ContractAnnex::ALWAYS)
->required()
->live(),
Select::make('condition_id')
->label('Zusatzleistung / Portal')
->options(fn (Get $get): array => match ($get('condition_type')) {
ContractAnnex::EXTRA => Extra::query()->orderBy('name')->pluck('name', 'id')->all(),
ContractAnnex::CHANNEL => Channel::query()->orderBy('name')->pluck('name', 'id')->all(),
default => [],
})
->visible(fn (Get $get): bool => in_array($get('condition_type'), [ContractAnnex::EXTRA, ContractAnnex::CHANNEL], true))
->required(fn (Get $get): bool => in_array($get('condition_type'), [ContractAnnex::EXTRA, ContractAnnex::CHANNEL], true)),
RichEditor::make('body')
->label('Text der Anlage (mit Platzhaltern wie {{ mieter }}, {{ wohnung.wlan_passwort }})')
->toolbarButtons([['bold', 'italic', 'underline', 'link'], ['h2', 'h3'], ['bulletList', 'orderedList'], ['undo', 'redo']])
->required()
->columnSpanFull(),
Textarea::make('notes')->label('Interne Notiz')->rows(2)->columnSpanFull(),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('name')
->columns([
TextColumn::make('name')->label('Anlage')->weight('medium')->searchable(),
TextColumn::make('version')->label('Version')->badge(),
TextColumn::make('condition')->label('Bedingung')->state(fn (ContractAnnex $record): string => match ($record->condition_type) {
ContractAnnex::EXTRA => 'Zusatzleistung: '.(Extra::query()->find($record->condition_id)?->name ?? '?'),
ContractAnnex::CHANNEL => 'Portal: '.(Channel::query()->find($record->condition_id)?->name ?? '?'),
ContractAnnex::MANUAL => 'Nur von Hand',
default => 'Immer',
}),
IconColumn::make('used')->label('In Angeboten')->boolean()->state(fn (ContractAnnex $record): bool => $record->isUsed()),
])
->recordActions([
EditAction::make(),
Action::make('newVersion')
->label('Neue Version')
->icon(Heroicon::OutlinedDocumentDuplicate)
->requiresConfirmation()
->modalDescription('Es wird eine Kopie mit der nächsten Versionsnummer angelegt. Die bisherige Version bleibt unverändert.')
->action(function (ContractAnnex $record): void {
Notification::make()->title('Version '.$record->newVersion()->version.' angelegt')->success()->send();
}),
DeleteAction::make(),
]);
}
/**
* A version used in an offer is a document of record and is never edited; a new version is made instead.
*/
public static function canEdit(Model $record): bool
{
return ! $record->isUsed();
}
public static function canDelete(Model $record): bool
{
return ! $record->isUsed();
}
public static function getPages(): array
{
return [
'index' => ListContractAnnexes::route('/'),
'create' => CreateContractAnnex::route('/create'),
'edit' => EditContractAnnex::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Filament\Resources\ContractAnnexes\Pages;
use App\Filament\Resources\ContractAnnexes\ContractAnnexResource;
use Filament\Resources\Pages\CreateRecord;
class CreateContractAnnex extends CreateRecord
{
protected static string $resource = ContractAnnexResource::class;
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['version'] = 1;
return $data;
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\ContractAnnexes\Pages;
use App\Filament\Resources\ContractAnnexes\ContractAnnexResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditContractAnnex extends EditRecord
{
protected static string $resource = ContractAnnexResource::class;
protected function getHeaderActions(): array
{
return [DeleteAction::make()];
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\ContractAnnexes\Pages;
use App\Filament\Resources\ContractAnnexes\ContractAnnexResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListContractAnnexes extends ListRecords
{
protected static string $resource = ContractAnnexResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()];
}
}
@@ -3,7 +3,10 @@
namespace App\Filament\Resources\ContractTemplates\Schemas;
use App\Documents\ContractPlaceholders;
use App\Models\CancellationPolicy;
use App\Models\ContractAnnex;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Section;
@@ -26,6 +29,16 @@ public static function configure(Schema $schema): Schema
->helperText('z. B. „Direktbuchung“ oder „Portal XY“. Versionen derselben Vorlage haben denselben Namen.'),
TextInput::make('version')->label('Version')->integer()->default(1)->disabled()->dehydrated(false)
->helperText('Neue Versionen entstehen über „Neue Version“ in der Liste. Eine Vorlage, die in einem Angebot verwendet wurde, kann nicht mehr geändert werden.'),
Select::make('cancellation_policy_id')
->label('Stornoregel')
->options(fn (): array => CancellationPolicy::query()->orderBy('name')->pluck('name', 'id')->all())
->placeholder('Keine – Stornokosten von Hand')
->helperText('Stufen und Berechnungsgrundlage für die automatische Berechnung der Stornokosten. Im Vertragstext mit {{ storno_regel }} einfügbar.'),
Select::make('annex_ids')
->label('Mögliche Anlagen dieser Vorlage')
->multiple()
->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all())
->helperText('Welche davon einem Angebot angehängt werden, entscheidet die Bedingung der Anlage (z. B. gebuchte Zusatzleistung). Im Angebot lässt sich die Auswahl ändern.'),
Section::make('Vertragsdokument')
->description('Der ganze Vertrag als ein Text mit Platzhaltern (siehe unten). Ist hier etwas eingetragen, wird dieser Text als Mietvertrag verwendet – mit Briefkopf, Anrede, Paragrafen und optionaler Anlage. Leer lassen, um nur die Textbausteine darunter zu verwenden.')
->columnSpanFull()
@@ -8,6 +8,7 @@
use App\Enums\CancellationMode;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Support\CancellationCost;
use DateTimeInterface;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
@@ -54,6 +55,7 @@ public function showCancel(Booking $booking, CancelBookingByGuest $cancel): View
'canCancel' => $open && ! $booking->cancellationRequested(),
'alreadyAsked' => $booking->status === BookingStatus::Cancelled || $booking->cancellationRequested(),
'instant' => $cancel->modeFor($booking) === CancellationMode::Instant,
'cost' => CancellationCost::calculate($booking),
'action' => $this->signed('bookings.cancel.confirm', $booking, now()->addHour()),
'title' => 'Buchung stornieren',
]);
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* The record of a cancelled booking: when, how many days before arrival, the cost proposed by the cancellation rule
* and the amount the landlord finally charges. Cancelled bookings stay in the system for this history.
*/
#[Fillable(['booking_id', 'cancelled_on', 'initiated_by', 'has_policy', 'policy_name', 'days_before', 'percent', 'base_amount', 'calculated_fee', 'final_fee', 'paid_amount', 'status', 'note', 'settled_at'])]
class Cancellation extends Model
{
use BelongsToTenant;
public const OPEN = 'open';
public const SETTLED = 'settled';
public const WAIVED = 'waived';
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return ['cancelled_on' => 'immutable_date', 'has_policy' => 'boolean', 'settled_at' => 'immutable_datetime'];
}
/**
* @return BelongsTo<Booking, $this>
*/
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
/**
* What the guest owes: the final fee, else the proposal; nothing when waived.
*/
public function fee(): int
{
return $this->status === self::WAIVED ? 0 : (int) ($this->final_fee ?? $this->calculated_fee ?? 0);
}
/**
* Positive: the guest still has to pay; negative: the landlord has to refund.
*/
public function balance(): int
{
return $this->fee() - $this->paid_amount;
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use App\Support\Money;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
/**
* A cancellation rule: stepped percentages by the days left before arrival, calculated from the rent (accommodation
* without cleaning, service and tourist tax) or from the total price, plus an optional fee for a replacement tenant.
* Used by contract templates; an offer freezes a copy ({@see snapshot()}), so later edits never change it.
*/
#[Fillable(['name', 'base', 'tiers', 'replacement_fee', 'notes'])]
class CancellationPolicy extends Model
{
use BelongsToTenant;
public const BASE_RENT = 'rent';
public const BASE_TOTAL = 'total';
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return ['tiers' => 'array', 'replacement_fee' => 'integer'];
}
/**
* The frozen form stored in an offer.
*
* @return array{name: string, base: string, tiers: list<array{min_days: int, percent: int}>, replacement_fee: ?int}
*/
public function snapshot(): array
{
return [
'name' => $this->name,
'base' => $this->base,
'tiers' => self::normalise((array) $this->tiers),
'replacement_fee' => $this->replacement_fee,
];
}
/**
* Tiers sorted from the earliest to the latest cancellation: "from N days before arrival: P %".
*
* @param array<int, array<string, mixed>> $tiers
* @return list<array{min_days: int, percent: int}>
*/
public static function normalise(array $tiers): array
{
$clean = array_map(fn (array $tier): array => ['min_days' => max(0, (int) ($tier['min_days'] ?? 0)), 'percent' => min(100, max(0, (int) ($tier['percent'] ?? 0)))], $tiers);
usort($clean, fn (array $a, array $b): int => $b['min_days'] <=> $a['min_days']);
return array_values($clean);
}
/**
* The tier that applies when cancelling this many days before arrival (the last tier covers everything later).
*
* @param array{tiers: list<array{min_days: int, percent: int}>} $policy
* @return array{min_days: int, percent: int}
*/
public static function tierFor(array $policy, int $daysBefore): array
{
foreach ($policy['tiers'] as $tier) {
if ($daysBefore >= $tier['min_days']) {
return $tier;
}
}
return $policy['tiers'][array_key_last($policy['tiers'])] ?? ['min_days' => 0, 'percent' => 100];
}
/**
* The rule as readable lines for contracts and pages, e.g. "Rücktritt bis 60 Tage vor Mietbeginn: 0 % …".
*
* @param array{base: string, tiers: list<array{min_days: int, percent: int}>, replacement_fee: ?int} $policy
* @return list<string>
*/
public static function describe(array $policy): array
{
$base = $policy['base'] === self::BASE_TOTAL ? 'des Gesamtpreises' : 'des Mietpreises';
$lines = [];
$tiers = $policy['tiers'];
foreach ($tiers as $index => $tier) {
$next = $tiers[$index + 1] ?? null;
$when = match (true) {
$index === 0 => 'Rücktritt bis '.$tier['min_days'].' Tage vor Mietbeginn',
$next === null => 'Rücktritt ab '.($tiers[$index - 1]['min_days'] - 1).' Tage vor Mietbeginn bis Mietbeginn',
default => 'Rücktritt '.($tiers[$index - 1]['min_days'] - 1).' bis '.$tier['min_days'].' Tage vor Mietbeginn',
};
$lines[] = $when.': '.$tier['percent'].' % '.$base;
}
if (($policy['replacement_fee'] ?? null) !== null) {
$lines[] = 'Stellung eines Ersatzmieters: Bearbeitungsgebühr '.Money::format((int) $policy['replacement_fee']);
}
return $lines;
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
/**
* An annex of the rental contract as a document of its own (e.g. WLAN terms, linen package, key pick-up). A contract
* template lists the annexes it may use; the condition decides per booking whether an annex is attached. An offer freezes
* a copy; a version used in an offer is never edited – a new version is made instead.
*/
#[Fillable(['name', 'version', 'title', 'body', 'condition_type', 'condition_id', 'notes'])]
class ContractAnnex extends Model
{
use BelongsToTenant;
public const ALWAYS = 'always';
public const EXTRA = 'extra';
public const CHANNEL = 'channel';
public const MANUAL = 'manual';
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return ['version' => 'integer', 'condition_id' => 'integer'];
}
public function label(): string
{
return $this->name.' (Version '.$this->version.')';
}
/**
* Whether this annex belongs to the booking by its condition (manual annexes are only added by hand).
*/
public function appliesTo(Booking $booking): bool
{
$channelId = $booking->import_channel_id ?? $booking->origin_channel_id;
return match ($this->condition_type) {
self::ALWAYS => true,
self::EXTRA => $this->condition_id !== null && (int) ($booking->extras[$this->condition_id] ?? 0) > 0,
self::CHANNEL => $this->condition_id !== null && (int) $channelId === $this->condition_id,
default => false,
};
}
public function isUsed(): bool
{
return Booking::query()->whereJsonContains('offer_terms->annex_ids', $this->id)->exists();
}
public function newVersion(): self
{
$latest = static::query()->where('name', $this->name)->max('version');
return static::query()->create([
'name' => $this->name,
'version' => $latest + 1,
'title' => $this->title,
'body' => $this->body,
'condition_type' => $this->condition_type,
'condition_id' => $this->condition_id,
'notes' => $this->notes,
]);
}
}
+24 -2
View File
@@ -5,13 +5,15 @@
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Collection;
/**
* A version of contract texts for offers (e.g. conditions demanded by a portal). The texts replace the website
* texts of the same meaning when an offer is made; the offer then freezes a copy. A version that has been used in
* an offer is never edited – a new version is created instead.
*/
#[Fillable(['name', 'version', 'texts', 'body', 'annex_title', 'annex_body', 'notes'])]
#[Fillable(['name', 'version', 'texts', 'body', 'annex_title', 'annex_body', 'cancellation_policy_id', 'annex_ids', 'notes'])]
class ContractTemplate extends Model
{
use BelongsToTenant;
@@ -33,7 +35,7 @@ class ContractTemplate extends Model
*/
protected function casts(): array
{
return ['texts' => 'array', 'version' => 'integer'];
return ['texts' => 'array', 'version' => 'integer', 'annex_ids' => 'array'];
}
/**
@@ -44,6 +46,24 @@ public function hasDocument(): bool
return filled($this->body) && trim(strip_tags((string) $this->body)) !== '';
}
/**
* @return BelongsTo<CancellationPolicy, $this>
*/
public function cancellationPolicy(): BelongsTo
{
return $this->belongsTo(CancellationPolicy::class);
}
/**
* The annexes of this template whose condition fits the booking.
*
* @return Collection<int, ContractAnnex>
*/
public function annexesFor(Booking $booking): Collection
{
return ContractAnnex::query()->whereIn('id', (array) ($this->annex_ids ?? []))->orderBy('name')->get()->filter(fn (ContractAnnex $annex): bool => $annex->appliesTo($booking))->values();
}
public function label(): string
{
return $this->name.' (Version '.$this->version.')';
@@ -83,6 +103,8 @@ public function newVersion(): self
'body' => $this->body,
'annex_title' => $this->annex_title,
'annex_body' => $this->annex_body,
'cancellation_policy_id' => $this->cancellation_policy_id,
'annex_ids' => $this->annex_ids,
'notes' => $this->notes,
]);
}
+15 -1
View File
@@ -8,6 +8,7 @@
use App\Enums\ChannelBookingModel;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Cancellation;
use Carbon\CarbonImmutable;
/**
@@ -91,6 +92,19 @@ public static function steps(Booking $booking): array
return $steps;
}
private static function cancelledText(Booking $booking, bool $open): string
{
$cancellation = Cancellation::query()->where('booking_id', $booking->id)->first();
if ($cancellation === null) {
return $open ? 'Stornokosten bzw. Rückzahlung sind noch zu klären (siehe Aufgaben).' : 'Nichts mehr zu tun. Die Buchung bleibt zur Historie erhalten.';
}
$balance = $cancellation->balance();
$text = 'Storniert am '.$cancellation->cancelled_on->format('d.m.Y').' ('.($cancellation->days_before ?? '?').' Tage vor Anreise). Stornokosten '.Money::format($cancellation->fee()).', bezahlt '.Money::format($cancellation->paid_amount).'.';
return $text.($cancellation->status === Cancellation::OPEN ? ($balance > 0 ? ' Noch einzufordern: '.Money::format($balance).'.' : ($balance < 0 ? ' Zu erstatten: '.Money::format(-$balance).'.' : ' Ausgeglichen – bitte als abgerechnet markieren.')) : ' Erledigt.');
}
/**
* @return array{title: string, text: string, color: string}
*/
@@ -109,7 +123,7 @@ public static function next(Booking $booking): array
}
return match (true) {
$booking->status === BookingStatus::Cancelled => ['title' => 'Storniert', 'text' => $costs !== null || $wish !== null ? 'Stornokosten bzw. Rückzahlung sind noch zu klären (siehe Aufgaben).' : 'Nichts mehr zu tun. Die Buchung bleibt zur Historie erhalten.', 'color' => $costs !== null ? 'warning' : 'gray'],
$booking->status === BookingStatus::Cancelled => ['title' => 'Storniert', 'text' => self::cancelledText($booking, $costs !== null || $wish !== null), 'color' => $costs !== null ? 'warning' : 'gray'],
$booking->status === BookingStatus::Declined => ['title' => 'Abgelehnt', 'text' => 'Der Zeitraum ist wieder frei.', 'color' => 'gray'],
$booking->status === BookingStatus::Expired => ['title' => 'Abgelaufen', 'text' => 'Die Haltefrist ist verstrichen. Sie können die Anfrage trotzdem noch bestätigen, solange der Zeitraum frei ist.', 'color' => 'gray'],
$booking->status === BookingStatus::Reserved => ['title' => 'Anfrage prüfen', 'text' => $kind === self::PORTAL_BOOKING
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Support;
use App\Enums\QuoteLineType;
use App\Models\Booking;
use App\Models\CancellationPolicy;
use Carbon\CarbonInterface;
/**
* Calculates what a cancellation costs according to the cancellation rule frozen in the offer. Returns null when
* the booking has no rule (then the landlord decides by hand). The result is a proposal: the landlord can adjust it.
*/
class CancellationCost
{
/**
* @return array{policy: string, base: string, days_before: int, percent: int, base_amount: int, fee: int, free: bool, tier_text: string}|null
*/
public static function calculate(Booking $booking, ?CarbonInterface $on = null): ?array
{
$policy = $booking->offer_terms['cancellation_policy'] ?? null;
if (! is_array($policy) || empty($policy['tiers'])) {
return null;
}
$on ??= today();
$daysBefore = max(0, (int) $on->copy()->startOfDay()->diffInDays($booking->arrival, false));
$tier = CancellationPolicy::tierFor($policy, $daysBefore);
$baseAmount = $policy['base'] === CancellationPolicy::BASE_TOTAL ? (int) $booking->total : self::rent($booking);
$fee = (int) round($baseAmount * $tier['percent'] / 100);
return [
'policy' => (string) $policy['name'],
'base' => (string) $policy['base'],
'days_before' => $daysBefore,
'percent' => $tier['percent'],
'base_amount' => $baseAmount,
'fee' => $fee,
'free' => $fee === 0,
'tier_text' => $tier['percent'].' % '.($policy['base'] === CancellationPolicy::BASE_TOTAL ? 'des Gesamtpreises' : 'des Mietpreises').' ('.$daysBefore.' Tage vor Anreise)',
];
}
/**
* The rent: accommodation, extra guests, discounts and manual adjustments – without cleaning, services and extras.
*/
public static function rent(Booking $booking): int
{
$rentTypes = [QuoteLineType::Accommodation->value, QuoteLineType::ExtraGuest->value, QuoteLineType::Discount->value, QuoteLineType::Adjustment->value];
return (int) collect($booking->quote['lines'] ?? [])->filter(fn (array $line): bool => in_array($line['type'] ?? null, $rentTypes, true))->sum('amount');
}
}