diff --git a/app/Actions/ConfirmBooking.php b/app/Actions/ConfirmBooking.php index 9d8ee7e..a085327 100644 --- a/app/Actions/ConfirmBooking.php +++ b/app/Actions/ConfirmBooking.php @@ -3,6 +3,7 @@ namespace App\Actions; use App\Availability\AvailabilityChecker; +use App\Documents\RentalContract; use App\Enums\BookingStatus; use App\Exceptions\ReservationException; use App\Mail\BookingConfirmed; @@ -11,11 +12,16 @@ use Illuminate\Support\Facades\Mail; /** - * The landlord accepts a reservation. Expired reservations can still be confirmed while the dates are free. + * The landlord accepts a reservation: the booking becomes binding, payment due dates are fixed, + * the rental contract is generated and sent with the confirmation. + * Expired reservations can still be confirmed while the dates are free. */ class ConfirmBooking { - public function __construct(private AvailabilityChecker $availability) {} + public function __construct( + private AvailabilityChecker $availability, + private RentalContract $contract, + ) {} /** * @throws ReservationException @@ -35,9 +41,12 @@ public function handle(Booking $booking, bool $notifyGuest = true): void 'status' => BookingStatus::Confirmed, 'hold_expires_at' => null, 'confirmed_at' => now(), + 'deposit_due_on' => today()->addDays(config('fewo.deposit_due_days'))->toDateString(), ]); }); + $this->contract->generate($booking); + if ($notifyGuest) { Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking)); } diff --git a/app/Actions/RecordPayment.php b/app/Actions/RecordPayment.php new file mode 100644 index 0000000..78832d4 --- /dev/null +++ b/app/Actions/RecordPayment.php @@ -0,0 +1,54 @@ +payments()->create([ + 'amount' => $amount, + 'paid_on' => $paidOn->toDateString(), + 'method' => $method, + 'note' => $note, + 'recorded_by' => $recordedBy, + ]); + + $booking->unsetRelation('payments'); + $this->updateStatus($booking); + + return $payment; + }); + } + + public function updateStatus(Booking $booking): void + { + $paymentStatuses = [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid]; + if (! in_array($booking->status, $paymentStatuses, true)) { + return; + } + + $paid = $booking->paidAmount(); + $status = match (true) { + $paid >= $booking->total => BookingStatus::Paid, + $paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid, + default => BookingStatus::Confirmed, + }; + + if ($status !== $booking->status) { + $booking->update(['status' => $status]); + } + } +} diff --git a/app/Actions/SendBookingReminders.php b/app/Actions/SendBookingReminders.php new file mode 100644 index 0000000..9f81be4 --- /dev/null +++ b/app/Actions/SendBookingReminders.php @@ -0,0 +1,100 @@ +bookings(fn (Builder $query) => $query + ->where('status', BookingStatus::Confirmed) + ->whereNull('deposit_reminded_at') + ->whereDate('deposit_due_on', '<', $today)) + ->filter(fn (Booking $booking): bool => $booking->openDeposit() > 0); + $this->remind($depositOverdue, PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'); + + $balanceRequest = $this->bookings(fn (Builder $query) => $query + ->whereIn('status', $unpaid) + ->whereNull('balance_requested_at') + ->whereDate('balance_due_on', '>=', $today) + ->whereDate('balance_due_on', '<=', $today->copy()->addDays(self::BALANCE_REQUEST_DAYS_BEFORE))) + ->filter(fn (Booking $booking): bool => ! $booking->requiresFullPayment() && $booking->openAmount() > 0 && $booking->status === BookingStatus::DepositPaid); + $this->remind($balanceRequest, PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'); + + $balanceOverdue = $this->bookings(fn (Builder $query) => $query + ->whereIn('status', $unpaid) + ->whereNull('balance_reminded_at') + ->whereDate('balance_due_on', '<', $today)) + ->filter(fn (Booking $booking): bool => $booking->openAmount() > 0 && ($booking->status === BookingStatus::DepositPaid || $booking->requiresFullPayment())); + $this->remind($balanceOverdue, PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'); + + $arrivals = $this->bookings(fn (Builder $query) => $query + ->whereIn('status', BookingStatus::occupying()) + ->whereNull('arrival_info_sent_at') + ->whereDate('arrival', '>=', $today) + ->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_DAYS_BEFORE))); + foreach ($arrivals as $booking) { + Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking)); + $booking->update(['arrival_info_sent_at' => now()]); + } + + $completed = Booking::query() + ->where('status', BookingStatus::Paid) + ->whereDate('departure', '<', $today) + ->get(); + $completed->each->update(['status' => BookingStatus::Completed]); + + return [ + 'deposit_overdue' => $depositOverdue->count(), + 'balance_request' => $balanceRequest->count(), + 'balance_overdue' => $balanceOverdue->count(), + 'arrival_info' => $arrivals->count(), + 'completed' => $completed->count(), + ]; + } + + /** + * @param callable(Builder): Builder $constraints + * @return Collection + */ + private function bookings(callable $constraints): Collection + { + return $constraints(Booking::query()->with(['guest', 'property', 'payments'])) + ->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at')) + ->get() + ->toBase(); + } + + /** + * @param Collection $bookings + */ + private function remind(Collection $bookings, string $kind, string $sentAtColumn): void + { + foreach ($bookings as $booking) { + Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind)); + $booking->update([$sentAtColumn => now()]); + } + } +} diff --git a/app/Documents/RentalContract.php b/app/Documents/RentalContract.php new file mode 100644 index 0000000..633e449 --- /dev/null +++ b/app/Documents/RentalContract.php @@ -0,0 +1,34 @@ +loadMissing(['guest', 'property']); + $path = "contracts/Mietvertrag-{$booking->reference}.pdf"; + + Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', ['booking' => $booking])->setPaper('a4')->output()); + $booking->update(['contract_path' => $path]); + + return $path; + } + + public function absolutePath(Booking $booking): ?string + { + return $booking->contract_path && Storage::disk(self::DISK)->exists($booking->contract_path) + ? Storage::disk(self::DISK)->path($booking->contract_path) + : null; + } +} diff --git a/app/Enums/PaymentMethod.php b/app/Enums/PaymentMethod.php new file mode 100644 index 0000000..ac96747 --- /dev/null +++ b/app/Enums/PaymentMethod.php @@ -0,0 +1,21 @@ + 'Überweisung', + self::Cash => 'Bar', + self::Other => 'Sonstiges', + }; + } +} diff --git a/app/Filament/Resources/Bookings/BookingResource.php b/app/Filament/Resources/Bookings/BookingResource.php index b7446a6..7827e4b 100644 --- a/app/Filament/Resources/Bookings/BookingResource.php +++ b/app/Filament/Resources/Bookings/BookingResource.php @@ -6,6 +6,7 @@ use App\Filament\Resources\Bookings\Pages\CreateBooking; use App\Filament\Resources\Bookings\Pages\ListBookings; use App\Filament\Resources\Bookings\Pages\ViewBooking; +use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager; use App\Filament\Resources\Bookings\Schemas\BookingForm; use App\Filament\Resources\Bookings\Schemas\BookingInfolist; use App\Filament\Resources\Bookings\Tables\BookingsTable; @@ -63,6 +64,13 @@ public static function getNavigationBadgeColor(): string return 'warning'; } + public static function getRelations(): array + { + return [ + PaymentsRelationManager::class, + ]; + } + public static function getPages(): array { return [ diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index 7296c63..f547c56 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -4,6 +4,7 @@ use App\Actions\ConfirmBooking; use App\Actions\DeclineBooking; +use App\Documents\RentalContract; use App\Enums\BookingStatus; use App\Exceptions\ReservationException; use App\Filament\Resources\Bookings\BookingResource; @@ -75,7 +76,23 @@ protected function getHeaderActions(): array Notification::make()->title('Vorgemerkt bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send(); }), + Action::make('contract') + ->label('Mietvertrag') + ->icon(Heroicon::OutlinedDocumentText) + ->color('gray') + ->visible(fn (): bool => $this->record->contract_path !== null) + ->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record) ?? abort(404), "Mietvertrag-{$this->record->reference}.pdf")), ActionGroup::make([ + Action::make('regenerateContract') + ->label('Mietvertrag neu erzeugen') + ->icon(Heroicon::OutlinedArrowPath) + ->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying()], true)) + ->requiresConfirmation() + ->modalDescription('Der Vertrag wird mit den aktuellen Texten neu erstellt. Der Gast erhält ihn nicht automatisch.') + ->action(function (RentalContract $contract): void { + $contract->generate($this->record); + Notification::make()->title('Mietvertrag neu erzeugt')->success()->send(); + }), Action::make('notes') ->label('Interne Notiz bearbeiten') ->icon(Heroicon::OutlinedPencilSquare) diff --git a/app/Filament/Resources/Bookings/RelationManagers/PaymentsRelationManager.php b/app/Filament/Resources/Bookings/RelationManagers/PaymentsRelationManager.php new file mode 100644 index 0000000..84ff6f4 --- /dev/null +++ b/app/Filament/Resources/Bookings/RelationManagers/PaymentsRelationManager.php @@ -0,0 +1,81 @@ +recordTitleAttribute('amount') + ->description(fn (): string => 'Bezahlt: '.Money::format($this->ownerRecord->paidAmount()).' · offen: '.Money::format($this->ownerRecord->openAmount())) + ->columns([ + TextColumn::make('paid_on')->label('Eingang')->date('d.m.Y'), + TextColumn::make('amount')->label('Betrag')->money('EUR', divideBy: 100, locale: 'de'), + TextColumn::make('method')->label('Art'), + TextColumn::make('note')->label('Notiz')->placeholder('–'), + TextColumn::make('recorded_by')->label('Erfasst von')->placeholder('–'), + ]) + ->headerActions([ + Action::make('record') + ->label('Zahlung erfassen') + ->icon(Heroicon::OutlinedBanknotes) + ->fillForm(fn (): array => [ + 'amount' => number_format(($this->ownerRecord->openDeposit() ?: $this->ownerRecord->openAmount()) / 100, 2, '.', ''), + 'paid_on' => today(), + 'method' => PaymentMethod::Transfer, + ]) + ->schema([ + EuroInput::make('amount')->label('Betrag')->helperText('Erstattungen mit Minus erfassen.')->minValue(null)->required(), + DatePicker::make('paid_on')->label('Zahlungseingang')->required(), + Select::make('method')->label('Art')->options(PaymentMethod::class)->required(), + TextInput::make('note')->label('Notiz')->maxLength(255), + ]) + ->action(function (array $data, RecordPayment $recordPayment): void { + $recordPayment->handle( + $this->ownerRecord, + (int) $data['amount'], + CarbonImmutable::parse($data['paid_on']), + $data['method'] instanceof PaymentMethod ? $data['method'] : PaymentMethod::from($data['method']), + $data['note'] ?: null, + auth()->user()?->name, + ); + + Notification::make()->title('Zahlung erfasst – Status: '.$this->ownerRecord->fresh()->status->getLabel())->success()->send(); + }), + ]) + ->recordActions([ + DeleteAction::make()->after(fn (Payment $record) => app(RecordPayment::class)->updateStatus($this->ownerRecord->fresh())), + ]); + } +} diff --git a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php index b312e36..10ad312 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php @@ -48,6 +48,9 @@ public static function configure(Schema $schema): Schema TextEntry::make('deposit')->label('Anzahlung')->money('EUR', divideBy: 100, locale: 'de'), TextEntry::make('balance')->label('Restzahlung')->state(fn (Booking $record): string => Money::format($record->total - $record->deposit)), TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y'), + TextEntry::make('paid')->label('Bezahlt')->state(fn (Booking $record): string => Money::format($record->paidAmount())), + TextEntry::make('open')->label('Offen')->state(fn (Booking $record): string => Money::format($record->openAmount()))->color(fn (Booking $record): string => $record->openAmount() > 0 ? 'danger' : 'success'), + TextEntry::make('deposit_due_on')->label('Anzahlung fällig am')->date('d.m.Y')->placeholder('–'), ]), ]), Section::make('Nachricht des Gastes') diff --git a/app/Filament/Resources/Bookings/Tables/BookingsTable.php b/app/Filament/Resources/Bookings/Tables/BookingsTable.php index ce1a2c0..02b5b82 100644 --- a/app/Filament/Resources/Bookings/Tables/BookingsTable.php +++ b/app/Filament/Resources/Bookings/Tables/BookingsTable.php @@ -4,6 +4,7 @@ use App\Enums\BookingStatus; use App\Models\Booking; +use App\Support\Money; use Filament\Actions\ViewAction; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Filters\Filter; @@ -16,7 +17,7 @@ class BookingsTable public static function configure(Table $table): Table { return $table - ->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property'])) + ->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property', 'payments'])) ->defaultSort('created_at', 'desc') ->columns([ TextColumn::make('reference') @@ -46,7 +47,8 @@ public static function configure(Table $table): Table ->label('Pers.'), TextColumn::make('total') ->label('Gesamt') - ->money('EUR', divideBy: 100, locale: 'de'), + ->money('EUR', divideBy: 100, locale: 'de') + ->description(fn (Booking $record): ?string => in_array($record->status, BookingStatus::occupying(), true) && $record->openAmount() > 0 ? 'offen '.Money::format($record->openAmount()) : null), TextColumn::make('source') ->label('Quelle') ->toggleable(isToggledHiddenByDefault: true), diff --git a/app/Mail/ArrivalInformation.php b/app/Mail/ArrivalInformation.php new file mode 100644 index 0000000..5dbd944 --- /dev/null +++ b/app/Mail/ArrivalInformation.php @@ -0,0 +1,36 @@ +booking->arrival->format('d.m.Y'), + replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))], + ); + } + + public function content(): Content + { + return new Content( + markdown: 'mail.arrival-information', + ); + } +} diff --git a/app/Mail/BookingConfirmed.php b/app/Mail/BookingConfirmed.php index f383ae5..50f1b1e 100644 --- a/app/Mail/BookingConfirmed.php +++ b/app/Mail/BookingConfirmed.php @@ -2,10 +2,12 @@ namespace App\Mail; +use App\Documents\RentalContract; use App\Models\Booking; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Address; +use Illuminate\Mail\Mailables\Attachment; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; use Illuminate\Queue\SerializesModels; @@ -33,4 +35,14 @@ public function content(): Content markdown: 'mail.booking-confirmed', ); } + + /** + * @return list + */ + public function attachments(): array + { + $path = app(RentalContract::class)->absolutePath($this->booking); + + return $path ? [Attachment::fromPath($path)->as("Mietvertrag-{$this->booking->reference}.pdf")->withMime('application/pdf')] : []; + } } diff --git a/app/Mail/PaymentReminder.php b/app/Mail/PaymentReminder.php new file mode 100644 index 0000000..13d822e --- /dev/null +++ b/app/Mail/PaymentReminder.php @@ -0,0 +1,50 @@ +kind) { + self::BALANCE_REQUEST => "Restzahlung für Ihre Buchung {$this->booking->reference}", + default => "Zahlungserinnerung zu Ihrer Buchung {$this->booking->reference}", + }, + replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))], + bcc: $this->kind === self::BALANCE_REQUEST ? [] : [new Address(config('fewo.notification_email'))], + ); + } + + public function content(): Content + { + return new Content( + markdown: 'mail.payment-reminder', + with: [ + 'amount' => $this->kind === self::DEPOSIT_OVERDUE && ! $this->booking->requiresFullPayment() ? $this->booking->openDeposit() : $this->booking->openAmount(), + 'dueOn' => $this->kind === self::DEPOSIT_OVERDUE ? $this->booking->deposit_due_on : $this->booking->balance_due_on, + ], + ); + } +} diff --git a/app/Models/Booking.php b/app/Models/Booking.php index 192378b..7e5dcf1 100644 --- a/app/Models/Booking.php +++ b/app/Models/Booking.php @@ -14,6 +14,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; /** @@ -38,13 +39,19 @@ 'quote', 'total', 'deposit', + 'deposit_due_on', 'balance_due_on', + 'contract_path', 'hold_expires_at', 'message', 'internal_notes', 'confirmed_at', 'cancelled_at', 'review_requested_at', + 'deposit_reminded_at', + 'balance_requested_at', + 'balance_reminded_at', + 'arrival_info_sent_at', ])] class Booking extends Model { @@ -72,11 +79,16 @@ protected function casts(): array 'departure' => 'immutable_date', 'extras' => 'array', 'quote' => 'array', + 'deposit_due_on' => 'immutable_date', 'balance_due_on' => 'immutable_date', 'hold_expires_at' => 'immutable_datetime', 'confirmed_at' => 'immutable_datetime', 'cancelled_at' => 'immutable_datetime', 'review_requested_at' => 'immutable_datetime', + 'deposit_reminded_at' => 'immutable_datetime', + 'balance_requested_at' => 'immutable_datetime', + 'balance_reminded_at' => 'immutable_datetime', + 'arrival_info_sent_at' => 'immutable_datetime', ]; } @@ -132,6 +144,40 @@ public function review(): HasOne return $this->hasOne(Review::class); } + /** + * @return HasMany + */ + public function payments(): HasMany + { + return $this->hasMany(Payment::class)->orderBy('paid_on'); + } + + /** + * Sum of all payments in cents (refunds are negative). + */ + public function paidAmount(): int + { + return (int) ($this->relationLoaded('payments') ? $this->payments->sum('amount') : $this->payments()->sum('amount')); + } + + public function openAmount(): int + { + return max(0, $this->total - $this->paidAmount()); + } + + public function openDeposit(): int + { + return max(0, $this->deposit - $this->paidAmount()); + } + + /** + * When the balance is already due at confirmation (short-term booking), the guest pays everything at once. + */ + public function requiresFullPayment(): bool + { + return $this->deposit_due_on !== null && $this->balance_due_on->lessThanOrEqualTo($this->deposit_due_on); + } + public function nights(): int { return (int) $this->arrival->diffInDays($this->departure); diff --git a/app/Models/Payment.php b/app/Models/Payment.php new file mode 100644 index 0000000..abee8ac --- /dev/null +++ b/app/Models/Payment.php @@ -0,0 +1,41 @@ + */ + use HasFactory; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'paid_on' => 'immutable_date', + 'method' => PaymentMethod::class, + ]; + } + + /** + * @return BelongsTo + */ + public function booking(): BelongsTo + { + return $this->belongsTo(Booking::class); + } +} diff --git a/config/content.php b/config/content.php index 0f38c63..1c179ec 100644 --- a/config/content.php +++ b/config/content.php @@ -62,6 +62,15 @@ ], ], + 'contract' => [ + 'label' => 'Mietvertrag', + 'fields' => [ + 'contract.intro' => ['label' => 'Einleitung', 'type' => 'textarea', 'default' => 'Zwischen Vermieter und Mieter wird folgender Mietvertrag über die Ferienwohnung geschlossen. Der Vertrag kommt mit der Buchungsbestätigung des Vermieters zustande.'], + 'contract.terms' => ['label' => 'Mietbedingungen', 'type' => 'richtext', 'default' => '

[MUSTER – bitte durch Ihre geprüften Mietbedingungen ersetzen]

  1. Die Wohnung darf nur von den im Vertrag genannten Personen genutzt werden.
  2. Der Mieter behandelt die Wohnung und das Inventar pfleglich und meldet Schäden unverzüglich.
  3. Die Kurtaxe ist nicht im Mietpreis enthalten und wird vor Ort entrichtet.
'], + 'contract.closing' => ['label' => 'Schlusstext', 'type' => 'textarea', 'default' => 'Wir freuen uns auf Ihren Besuch und wünschen Ihnen schon jetzt einen erholsamen Aufenthalt an der Ostsee.'], + ], + ], + 'legal' => [ 'label' => 'Rechtliches', 'fields' => [ diff --git a/config/dompdf.php b/config/dompdf.php new file mode 100644 index 0000000..51a2e6c --- /dev/null +++ b/config/dompdf.php @@ -0,0 +1,301 @@ + false, // Throw an Exception on warnings from dompdf + + 'public_path' => null, // Override the public path if needed + + /* + * Dejavu Sans font is missing glyphs for converted entities, turn it off if you need to show € and £. + */ + 'convert_entities' => true, + + 'options' => [ + /** + * The location of the DOMPDF font directory + * + * The location of the directory where DOMPDF will store fonts and font metrics + * Note: This directory must exist and be writable by the webserver process. + * *Please note the trailing slash.* + * + * Notes regarding fonts: + * Additional .afm font metrics can be added by executing load_font.php from command line. + * + * Only the original "Base 14 fonts" are present on all pdf viewers. Additional fonts must + * be embedded in the pdf file or the PDF may not display correctly. This can significantly + * increase file size unless font subsetting is enabled. Before embedding a font please + * review your rights under the font license. + * + * Any font specification in the source HTML is translated to the closest font available + * in the font directory. + * + * The pdf standard "Base 14 fonts" are: + * Courier, Courier-Bold, Courier-BoldOblique, Courier-Oblique, + * Helvetica, Helvetica-Bold, Helvetica-BoldOblique, Helvetica-Oblique, + * Times-Roman, Times-Bold, Times-BoldItalic, Times-Italic, + * Symbol, ZapfDingbats. + */ + 'font_dir' => storage_path('fonts'), // advised by dompdf (https://github.com/dompdf/dompdf/pull/782) + + /** + * The location of the DOMPDF font cache directory + * + * This directory contains the cached font metrics for the fonts used by DOMPDF. + * This directory can be the same as DOMPDF_FONT_DIR + * + * Note: This directory must exist and be writable by the webserver process. + */ + 'font_cache' => storage_path('fonts'), + + /** + * The location of a temporary directory. + * + * The directory specified must be writeable by the webserver process. + * The temporary directory is required to download remote images and when + * using the PDFLib back end. + */ + 'temp_dir' => sys_get_temp_dir(), + + /** + * ==== IMPORTANT ==== + * + * dompdf's "chroot": Prevents dompdf from accessing system files or other + * files on the webserver. All local files opened by dompdf must be in a + * subdirectory of this directory. DO NOT set it to '/' since this could + * allow an attacker to use dompdf to read any files on the server. This + * should be an absolute path. + * This is only checked on command line call by dompdf.php, but not by + * direct class use like: + * $dompdf = new DOMPDF(); $dompdf->load_html($htmldata); $dompdf->render(); $pdfdata = $dompdf->output(); + */ + 'chroot' => realpath(base_path()), + + /** + * Protocol whitelist + * + * Protocols and PHP wrappers allowed in URIs, and the validation rules + * that determine if a resouce may be loaded. Full support is not guaranteed + * for the protocols/wrappers specified + * by this array. + * + * @var array + */ + 'allowed_protocols' => [ + 'data://' => ['rules' => []], + 'file://' => ['rules' => []], + 'http://' => ['rules' => []], + 'https://' => ['rules' => []], + ], + + /** + * Operational artifact (log files, temporary files) path validation + */ + 'artifactPathValidation' => null, + + /** + * @var string + */ + 'log_output_file' => null, + + /** + * Whether to enable font subsetting or not. + */ + 'enable_font_subsetting' => true, + + /** + * The PDF rendering backend to use + * + * Valid settings are 'PDFLib', 'CPDF' (the bundled R&OS PDF class), 'GD' and + * 'auto'. 'auto' will look for PDFLib and use it if found, or if not it will + * fall back on CPDF. 'GD' renders PDFs to graphic files. + * {@link * Canvas_Factory} ultimately determines which rendering class to + * instantiate based on this setting. + * + * Both PDFLib & CPDF rendering backends provide sufficient rendering + * capabilities for dompdf, however additional features (e.g. object, + * image and font support, etc.) differ between backends. Please see + * {@link PDFLib_Adapter} for more information on the PDFLib backend + * and {@link CPDF_Adapter} and lib/class.pdf.php for more information + * on CPDF. Also see the documentation for each backend at the links + * below. + * + * The GD rendering backend is a little different than PDFLib and + * CPDF. Several features of CPDF and PDFLib are not supported or do + * not make any sense when creating image files. For example, + * multiple pages are not supported, nor are PDF 'objects'. Have a + * look at {@link GD_Adapter} for more information. GD support is + * experimental, so use it at your own risk. + * + * @link http://www.pdflib.com + * @link http://www.ros.co.nz/pdf + * @link http://www.php.net/image + */ + 'pdf_backend' => 'CPDF', + + /** + * html target media view which should be rendered into pdf. + * List of types and parsing rules for future extensions: + * http://www.w3.org/TR/REC-html40/types.html + * screen, tty, tv, projection, handheld, print, braille, aural, all + * Note: aural is deprecated in CSS 2.1 because it is replaced by speech in CSS 3. + * Note, even though the generated pdf file is intended for print output, + * the desired content might be different (e.g. screen or projection view of html file). + * Therefore allow specification of content here. + */ + 'default_media_type' => 'screen', + + /** + * The default paper size. + * + * North America standard is "letter"; other countries generally "a4" + * + * @see CPDF_Adapter::PAPER_SIZES for valid sizes ('letter', 'legal', 'A4', etc.) + */ + 'default_paper_size' => 'a4', + + /** + * The default paper orientation. + * + * The orientation of the page (portrait or landscape). + * + * @var string + */ + 'default_paper_orientation' => 'portrait', + + /** + * The default font family + * + * Used if no suitable fonts can be found. This must exist in the font folder. + * + * @var string + */ + 'default_font' => 'DejaVu Sans', + + /** + * Image DPI setting + * + * This setting determines the default DPI setting for images and fonts. The + * DPI may be overridden for inline images by explictly setting the + * image's width & height style attributes (i.e. if the image's native + * width is 600 pixels and you specify the image's width as 72 points, + * the image will have a DPI of 600 in the rendered PDF. The DPI of + * background images can not be overridden and is controlled entirely + * via this parameter. + * + * For the purposes of DOMPDF, pixels per inch (PPI) = dots per inch (DPI). + * If a size in html is given as px (or without unit as image size), + * this tells the corresponding size in pt. + * This adjusts the relative sizes to be similar to the rendering of the + * html page in a reference browser. + * + * In pdf, always 1 pt = 1/72 inch + * + * Rendering resolution of various browsers in px per inch: + * Windows Firefox and Internet Explorer: + * SystemControl->Display properties->FontResolution: Default:96, largefonts:120, custom:? + * Linux Firefox: + * about:config *resolution: Default:96 + * (xorg screen dimension in mm and Desktop font dpi settings are ignored) + * + * Take care about extra font/image zoom factor of browser. + * + * In images, size in pixel attribute, img css style, are overriding + * the real image dimension in px for rendering. + * + * @var int + */ + 'dpi' => 96, + + /** + * Enable embedded PHP + * + * If this setting is set to true then DOMPDF will automatically evaluate embedded PHP contained + * within tags. + * + * ==== IMPORTANT ==== Enabling this for documents you do not trust (e.g. arbitrary remote html pages) + * is a security risk. + * Embedded scripts are run with the same level of system access available to dompdf. + * Set this option to false (recommended) if you wish to process untrusted documents. + * This setting may increase the risk of system exploit. + * Do not change this settings without understanding the consequences. + * Additional documentation is available on the dompdf wiki at: + * https://github.com/dompdf/dompdf/wiki + * + * @var bool + */ + 'enable_php' => false, + + /** + * Enable inline JavaScript + * + * If this setting is set to true then DOMPDF will automatically insert JavaScript code contained + * within tags as written into the PDF. + * NOTE: This is PDF-based JavaScript to be executed by the PDF viewer, + * not browser-based JavaScript executed by Dompdf. + * + * @var bool + */ + 'enable_javascript' => true, + + /** + * Enable remote file access + * + * If this setting is set to true, DOMPDF will access remote sites for + * images and CSS files as required. + * + * ==== IMPORTANT ==== + * This can be a security risk, in particular in combination with isPhpEnabled and + * allowing remote html code to be passed to $dompdf = new DOMPDF(); $dompdf->load_html(...); + * This allows anonymous users to download legally doubtful internet content which on + * tracing back appears to being downloaded by your server, or allows malicious php code + * in remote html pages to be executed by your server with your account privileges. + * + * This setting may increase the risk of system exploit. Do not change + * this settings without understanding the consequences. Additional + * documentation is available on the dompdf wiki at: + * https://github.com/dompdf/dompdf/wiki + * + * @var bool + */ + 'enable_remote' => false, + + /** + * List of allowed remote hosts + * + * Each value of the array must be a valid hostname. + * + * This will be used to filter which resources can be loaded in combination with + * isRemoteEnabled. If enable_remote is FALSE, then this will have no effect. + * + * Leave to NULL to allow any remote host. + * + * @var array|null + */ + 'allowed_remote_hosts' => null, + + /** + * A ratio applied to the fonts height to be more like browsers' line height + */ + 'font_height_ratio' => 1.1, + + /** + * Use the HTML5 Lib parser + * + * @deprecated This feature is now always on in dompdf 2.x + * + * @var bool + */ + 'enable_html5_parser' => true, + ], + +]; diff --git a/database/factories/PaymentFactory.php b/database/factories/PaymentFactory.php new file mode 100644 index 0000000..add4bfa --- /dev/null +++ b/database/factories/PaymentFactory.php @@ -0,0 +1,29 @@ + + */ +class PaymentFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'booking_id' => Booking::factory(), + 'amount' => 10000, + 'paid_on' => now()->toDateString(), + 'method' => PaymentMethod::Transfer, + ]; + } +} diff --git a/database/migrations/2026_10_22_132242_create_payments_table.php b/database/migrations/2026_10_22_132242_create_payments_table.php new file mode 100644 index 0000000..5344597 --- /dev/null +++ b/database/migrations/2026_10_22_132242_create_payments_table.php @@ -0,0 +1,33 @@ +id(); + $table->foreignId('booking_id')->constrained()->cascadeOnDelete(); + $table->integer('amount'); + $table->date('paid_on'); + $table->string('method')->default('transfer'); + $table->string('note')->nullable(); + $table->string('recorded_by')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('payments'); + } +}; diff --git a/database/migrations/2026_10_22_132245_add_payment_workflow_fields_to_bookings_table.php b/database/migrations/2026_10_22_132245_add_payment_workflow_fields_to_bookings_table.php new file mode 100644 index 0000000..dec7435 --- /dev/null +++ b/database/migrations/2026_10_22_132245_add_payment_workflow_fields_to_bookings_table.php @@ -0,0 +1,33 @@ +date('deposit_due_on')->nullable()->after('deposit'); + $table->string('contract_path')->nullable()->after('balance_due_on'); + $table->dateTime('deposit_reminded_at')->nullable()->after('review_requested_at'); + $table->dateTime('balance_requested_at')->nullable()->after('deposit_reminded_at'); + $table->dateTime('balance_reminded_at')->nullable()->after('balance_requested_at'); + $table->dateTime('arrival_info_sent_at')->nullable()->after('balance_reminded_at'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('bookings', function (Blueprint $table) { + $table->dropColumn(['deposit_due_on', 'contract_path', 'deposit_reminded_at', 'balance_requested_at', 'balance_reminded_at', 'arrival_info_sent_at']); + }); + } +}; diff --git a/docs/KONZEPT.md b/docs/KONZEPT.md index d48e4e6..b058177 100644 --- a/docs/KONZEPT.md +++ b/docs/KONZEPT.md @@ -148,7 +148,7 @@ ## 10. Umsetzungsphasen 1. **Fundament:** Laravel + Filament, Datenmodell, Saisons/Preise, Preisberechnung (mit Tests). ✅ 2. **Kalender & Anfrage:** Belegung, Anfrageformular, Auto-Angebot per Mail, Vorreservierung mit Haltezeit, Sonderangebote, Sperrzeiten, Buchungsverwaltung. ✅ -3. **Buchungsworkflow:** Bestätigung, Mietvertrag-PDF, Zahlungsfristen & Erinnerungen. +3. **Buchungsworkflow:** Bestätigung, Mietvertrag-PDF, Zahlungsfristen & Erinnerungen, Anreiseinfos. ✅ (Mietbedingungen/Storno noch als Muster) 4. **Webseite:** Design, Inhalte, Galerie, SEO, Barrierefreiheit. 5. **Connectoren:** iCal-Import/-Export, Sync-Log, Konfliktwarnung. 6. **Go-Live:** Strato-Deployment, Umleitungen, Inhalte/Rechtstexte, Testbuchungen. diff --git a/resources/views/mail/arrival-information.blade.php b/resources/views/mail/arrival-information.blade.php new file mode 100644 index 0000000..f365908 --- /dev/null +++ b/resources/views/mail/arrival-information.blade.php @@ -0,0 +1,34 @@ + +# Bald sind Sie an der Ostsee! + +Guten Tag {{ $booking->guest->full_name }}, + +in wenigen Tagen beginnt Ihr Aufenthalt in der **{{ $booking->property->name }}**. Hier die wichtigsten Informationen: + +**Adresse:** {{ $booking->property->address }}
+**Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_in_time) ab {{ substr($booking->property->check_in_time, 0, 5) }} Uhr @endif
+**Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_out_time) bis {{ substr($booking->property->check_out_time, 0, 5) }} Uhr @endif + +@if (\App\Support\Content::get('stay.arrival_info')) +{{ \App\Support\Content::html('stay.arrival_info') }} +@else +Zur Schlüsselübergabe melden wir uns noch persönlich bei Ihnen. +@endif + +@if (\App\Support\Content::get('stay.house_rules')) +## Hausregeln + +{{ \App\Support\Content::html('stay.house_rules') }} +@endif + +@if ($booking->openAmount() > 0) + +Noch offen: **{{ \App\Support\Money::format($booking->openAmount()) }}** – bitte überweisen Sie den Betrag vor Ihrer Anreise. + +@endif + +Bei Fragen erreichen Sie uns unter {{ config('fewo.owner.phone') }}. Gute Anreise! + +Herzliche Grüße
+{{ config('fewo.owner.name') }} +
diff --git a/resources/views/mail/booking-confirmed.blade.php b/resources/views/mail/booking-confirmed.blade.php index 20d4752..cef70e3 100644 --- a/resources/views/mail/booking-confirmed.blade.php +++ b/resources/views/mail/booking-confirmed.blade.php @@ -14,20 +14,17 @@ ## Zahlung -Bitte überweisen Sie die Anzahlung von **{{ \App\Support\Money::format($booking->deposit) }}** innerhalb von {{ config('fewo.deposit_due_days') }} Tagen und den Restbetrag von **{{ \App\Support\Money::format($booking->total - $booking->deposit) }}** bis zum {{ $booking->balance_due_on->format('d.m.Y') }}. - -@if (config('fewo.bank.iban')) - -Kontoinhaber: {{ config('fewo.bank.account_holder') }}
-IBAN: {{ config('fewo.bank.iban') }}
-@if (config('fewo.bank.bic')) -BIC: {{ config('fewo.bank.bic') }}
-@endif -Verwendungszweck: {{ $booking->reference }} -
+@if ($booking->requiresFullPayment()) +Da Ihre Anreise kurz bevorsteht, überweisen Sie bitte den **Gesamtbetrag von {{ \App\Support\Money::format($booking->total) }}** bis zum **{{ $booking->deposit_due_on->format('d.m.Y') }}**. +@else +Bitte überweisen Sie die **Anzahlung von {{ \App\Support\Money::format($booking->deposit) }}** bis zum **{{ $booking->deposit_due_on?->format('d.m.Y') }}** und den **Restbetrag von {{ \App\Support\Money::format($booking->total - $booking->deposit) }}** bis zum **{{ $booking->balance_due_on->format('d.m.Y') }}**. An die Restzahlung erinnern wir Sie rechtzeitig. @endif -Rechtzeitig vor Ihrer Anreise erhalten Sie von uns alle Informationen zu Schlüsselübergabe, Parken und WLAN. +@include('mail.partials.bank') + +Ihren **Mietvertrag** finden Sie als PDF im Anhang. + +Eine Woche vor Ihrer Anreise erhalten Sie von uns alle Informationen zu Schlüsselübergabe, Parken und WLAN. Herzliche Grüße
{{ config('fewo.owner.name') }} diff --git a/resources/views/mail/partials/bank.blade.php b/resources/views/mail/partials/bank.blade.php new file mode 100644 index 0000000..d0de38e --- /dev/null +++ b/resources/views/mail/partials/bank.blade.php @@ -0,0 +1,10 @@ +@if (config('fewo.bank.iban')) + +Kontoinhaber: {{ config('fewo.bank.account_holder') }}
+IBAN: {{ config('fewo.bank.iban') }}
+@if (config('fewo.bank.bic')) +BIC: {{ config('fewo.bank.bic') }}
+@endif +Verwendungszweck: {{ $booking->reference }} +
+@endif diff --git a/resources/views/mail/partials/quote.blade.php b/resources/views/mail/partials/quote.blade.php index 9c0ed07..dcea250 100644 --- a/resources/views/mail/partials/quote.blade.php +++ b/resources/views/mail/partials/quote.blade.php @@ -1,7 +1,7 @@ | Leistung | Betrag | |:---------|-------:| -@foreach ($booking->quote['lines'] as $line) +@foreach ($booking->quote['lines'] ?? [] as $line) | {{ $line['label'] }} | {{ \App\Support\Money::format($line['amount']) }} | @endforeach | **Gesamtpreis** | **{{ \App\Support\Money::format($booking->total) }}** | diff --git a/resources/views/mail/payment-reminder.blade.php b/resources/views/mail/payment-reminder.blade.php new file mode 100644 index 0000000..99cddb5 --- /dev/null +++ b/resources/views/mail/payment-reminder.blade.php @@ -0,0 +1,26 @@ + +@if ($kind === \App\Mail\PaymentReminder::BALANCE_REQUEST) +# Ihre Restzahlung + +Guten Tag {{ $booking->guest->full_name }}, + +Ihr Aufenthalt in der **{{ $booking->property->name }}** vom {{ $booking->arrival->format('d.m.Y') }} bis {{ $booking->departure->format('d.m.Y') }} rückt näher – wir freuen uns schon auf Sie! + +Bitte überweisen Sie den **Restbetrag von {{ \App\Support\Money::format($amount) }}** bis zum **{{ $dueOn->format('d.m.Y') }}**. +@else +# Zahlungserinnerung + +Guten Tag {{ $booking->guest->full_name }}, + +zu Ihrer Buchung **{{ $booking->reference }}** ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}) konnten wir bis heute keinen Zahlungseingang über **{{ \App\Support\Money::format($amount) }}** feststellen (fällig am {{ $dueOn->format('d.m.Y') }}). + +Sicher ist das nur ein Versehen. Bitte holen Sie die Überweisung in den nächsten Tagen nach. Sollten Sie bereits gezahlt haben, betrachten Sie diese Nachricht bitte als gegenstandslos. +@endif + +@include('mail.partials.bank') + +Bei Fragen antworten Sie einfach auf diese E-Mail. + +Herzliche Grüße
+{{ config('fewo.owner.name') }} +
diff --git a/resources/views/pdf/contract.blade.php b/resources/views/pdf/contract.blade.php new file mode 100644 index 0000000..1e0c852 --- /dev/null +++ b/resources/views/pdf/contract.blade.php @@ -0,0 +1,97 @@ +@php($money = fn (int $cents): string => \App\Support\Money::format($cents)) + + + + + Mietvertrag {{ $booking->reference }} + + + + + +

Mietvertrag Ferienwohnung

+

Buchungsnummer {{ $booking->reference }} · ausgestellt am {{ ($booking->confirmed_at ?? now())->format('d.m.Y') }}

+ +

{{ \App\Support\Content::get('contract.intro') }}

+ + + + + + +
+

Vermieter

+ {{ config('fewo.owner.name') }}
+ {{ config('fewo.owner.street') }}
+ {{ config('fewo.owner.city') }}
+ Tel. {{ config('fewo.owner.phone') }} · {{ config('fewo.owner.email') }} +
+

Mieter

+ {{ $booking->guest->full_name }}
+ @if ($booking->guest->street){{ $booking->guest->street }}
@endif + @if ($booking->guest->city){{ $booking->guest->postal_code }} {{ $booking->guest->city }}
@endif + {{ $booking->guest->email }}@if ($booking->guest->phone) · {{ $booking->guest->phone }}@endif +
+ +

Mietobjekt und Mietzeit

+ + + + + + +
Objekt{{ $booking->property->name }}, {{ $booking->property->address }}@if ($booking->property->size_sqm), {{ $booking->property->size_sqm }} m²@endif
Anreise{{ $booking->arrival->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_in_time) ab {{ substr($booking->property->check_in_time, 0, 5) }} Uhr @endif
Abreise{{ $booking->departure->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_out_time) bis {{ substr($booking->property->check_out_time, 0, 5) }} Uhr @endif
Übernachtungen{{ $booking->nights() }}
Personen{{ $booking->guests }}
+ +

Mietpreis

+ + @foreach ($booking->quote['lines'] ?? [] as $line) + + @endforeach + +
{{ $line['label'] }}{{ $money($line['amount']) }}
Gesamtpreis{{ $money($booking->total) }}
+

Die Kurtaxe ist nicht enthalten und wird vor Ort entrichtet.

+ +

Zahlung

+ @if ($booking->requiresFullPayment()) +

Der Gesamtbetrag von {{ $money($booking->total) }} ist bis zum {{ $booking->deposit_due_on->format('d.m.Y') }} zu überweisen.

+ @else +

Anzahlung {{ $money($booking->deposit) }} bis zum {{ $booking->deposit_due_on?->format('d.m.Y') }}, + Restbetrag {{ $money($booking->total - $booking->deposit) }} bis zum {{ $booking->balance_due_on->format('d.m.Y') }}.

+ @endif + @if (config('fewo.bank.iban')) +

Bankverbindung: {{ config('fewo.bank.account_holder') }} · IBAN {{ config('fewo.bank.iban') }}@if (config('fewo.bank.bic')) · BIC {{ config('fewo.bank.bic') }}@endif · Verwendungszweck: {{ $booking->reference }}

+ @endif + +

Mietbedingungen

+
{{ \App\Support\Content::html('contract.terms') }}
+ + @if (\App\Support\Content::get('stay.cancellation')) +

Rücktritt / Stornierung

+
{{ \App\Support\Content::html('stay.cancellation') }}
+ @endif + + @if (\App\Support\Content::get('stay.house_rules')) +

Hausordnung

+
{{ \App\Support\Content::html('stay.house_rules') }}
+ @endif + +

{{ \App\Support\Content::get('contract.closing') }}

+

{{ config('fewo.owner.name') }}

+ + diff --git a/routes/console.php b/routes/console.php index e909f5e..c1ffcfd 100644 --- a/routes/console.php +++ b/routes/console.php @@ -4,6 +4,7 @@ use App\Actions\MonitorChannels; use App\Actions\RemindChannelTasks; use App\Actions\RequestReviews; +use App\Actions\SendBookingReminders; use Illuminate\Support\Facades\Schedule; Schedule::command('bookings:expire-holds')->everyFiveMinutes()->withoutOverlapping(); @@ -22,6 +23,11 @@ ->everyFifteenMinutes() ->withoutOverlapping(); +Schedule::call(fn (SendBookingReminders $sendBookingReminders) => $sendBookingReminders->handle()) + ->name('bookings:reminders') + ->dailyAt('09:00') + ->withoutOverlapping(); + Schedule::call(fn (RequestReviews $requestReviews) => $requestReviews->handle()) ->name('reviews:request') ->dailyAt('10:00') diff --git a/tests/Feature/PaymentWorkflowTest.php b/tests/Feature/PaymentWorkflowTest.php new file mode 100644 index 0000000..3c274a3 --- /dev/null +++ b/tests/Feature/PaymentWorkflowTest.php @@ -0,0 +1,141 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + Storage::fake('local'); + Mail::fake(); + $this->seed(PropertySeeder::class); + $this->property = Property::sole(); + } + + public function test_confirmation_fixes_due_dates_and_sends_the_contract(): void + { + $booking = $this->confirmed('2026-12-01', '2026-12-05'); + + $this->assertSame('2026-10-29', $booking->deposit_due_on->toDateString()); + $this->assertFalse($booking->requiresFullPayment()); + Storage::disk('local')->assertExists($booking->contract_path); + $this->assertStringStartsWith('%PDF', Storage::disk('local')->get($booking->contract_path)); + Mail::assertSent(BookingConfirmed::class, fn (BookingConfirmed $mail): bool => count($mail->attachments()) === 1); + } + + public function test_short_term_booking_requires_full_payment(): void + { + $booking = $this->confirmed('2026-11-07', '2026-11-10'); + + $this->assertTrue($booking->requiresFullPayment()); + $this->assertStringContainsString('Gesamtbetrag', (new BookingConfirmed($booking))->render()); + } + + public function test_payments_move_the_booking_through_its_statuses(): void + { + $booking = $this->confirmed('2026-12-01', '2026-12-05'); + $record = new RecordPayment; + + $record->handle($booking, $booking->deposit, today()); + $this->assertSame(BookingStatus::DepositPaid, $booking->fresh()->status); + + $record->handle($booking->fresh(), $booking->total - $booking->deposit, today()); + $this->assertSame(BookingStatus::Paid, $booking->fresh()->status); + $this->assertSame(0, $booking->fresh()->openAmount()); + + $record->handle($booking->fresh(), -5000, today(), note: 'Erstattung'); + $this->assertSame(BookingStatus::DepositPaid, $booking->fresh()->status); + } + + public function test_reminders_are_sent_once_at_the_right_time(): void + { + $booking = $this->confirmed('2026-12-01', '2026-12-05'); + $reminders = new SendBookingReminders; + + $this->travelTo(CarbonImmutable::parse('2026-10-30 09:00')); + $this->assertSame(1, $reminders->handle()['deposit_overdue']); + $this->assertSame(0, $reminders->handle()['deposit_overdue']); + Mail::assertSent(PaymentReminder::class, fn (PaymentReminder $mail): bool => $mail->kind === PaymentReminder::DEPOSIT_OVERDUE && $mail->hasBcc(config('fewo.notification_email'))); + + (new RecordPayment)->handle($booking, $booking->deposit, today()); + + $this->travelTo(CarbonImmutable::parse('2026-10-26 09:00')); + $this->assertSame(0, $reminders->handle()['balance_request'], 'balance is due on 03.11.; request 7 days before'); + $this->travelTo(CarbonImmutable::parse('2026-10-27 09:00')); + $this->assertSame(1, $reminders->handle()['balance_request']); + + $this->travelTo(CarbonImmutable::parse('2026-11-04 09:00')); + $this->assertSame(1, $reminders->handle()['balance_overdue']); + + $this->travelTo(CarbonImmutable::parse('2026-11-24 09:00')); + $this->assertSame(1, $reminders->handle()['arrival_info']); + Mail::assertSent(ArrivalInformation::class); + + (new RecordPayment)->handle($booking->fresh(), $booking->fresh()->openAmount(), today()); + $this->travelTo(CarbonImmutable::parse('2026-12-06 09:00')); + $this->assertSame(1, $reminders->handle()['completed']); + $this->assertSame(BookingStatus::Completed, $booking->fresh()->status); + } + + public function test_payment_is_recorded_and_contract_downloaded_in_the_admin(): void + { + $this->actingAs(User::factory()->create()); + $booking = $this->confirmed('2026-12-01', '2026-12-05'); + + Livewire::test(PaymentsRelationManager::class, ['ownerRecord' => $booking, 'pageClass' => ViewBooking::class]) + ->callAction(TestAction::make('record')->table(), [ + 'amount' => number_format($booking->deposit / 100, 2, '.', ''), + 'paid_on' => '2026-10-25', + 'method' => 'transfer', + ]) + ->assertHasNoFormErrors(); + + $this->assertSame(BookingStatus::DepositPaid, $booking->fresh()->status); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction('contract') + ->assertFileDownloaded("Mietvertrag-{$booking->reference}.pdf"); + } + + private function confirmed(string $arrival, string $departure): Booking + { + $booking = app(CreateReservation::class)->handle( + $this->property, + new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), + ['first_name' => 'Anna', 'last_name' => 'Muster', 'email' => 'anna@example.com', 'city' => 'Köln'], + ); + app(ConfirmBooking::class)->handle($booking); + + return $booking->fresh(); + } +}