Pakete 8, 5 und 6: Beträge und Zahlungen, Ändern und Stornieren, A6 im Vorgang
Deploy FeWo mit PipelineManager / deploy (push) Successful in 4m44s

- Paket 8: Zahlungsarten (Gast an uns, laut Portal, Auszahlung, Erstattung),
  Portalbeträge als Angaben mit Quelle, Übersicht nach Zuständigkeit (R09).
- Paket 5: Ändern mit Folgenvorschau, vereinbart oder dem Gast vorgeschlagen
  (signierter Link), ein Stornoweg mit Grund und Erstattung, Portalstorno erst
  nach Bestätigung.
- Paket 6: eigene Nutzung, Besuch und Sperre als Vorgang mit Kurabgabe und
  Aufenthaltsbestätigung; Bestandsübernahme der Sperren mit identischem Export.
- Wirksame Einstellungen (Expertenansicht), Abnahmekatalog T01–T14, Ergebnis-,
  Abnahme- und Konfigurationsdokument.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-01 22:16:47 +01:00
1 parent 33f8f899d6
commit 3bcfc09417
77 files changed
+3638 -122

No files matched your search

+81 -17
View File
@@ -5,11 +5,13 @@
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
use App\Mail\BookingCancelled;
use App\Mail\CancellationRequested;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Process\CaseLog;
use App\Support\CancellationCost;
use App\Support\Money;
use App\Support\Settings;
@@ -19,45 +21,53 @@
use Throwable;
/**
* The landlord cancels a binding booking. The dates are free again; the guest and the landlord are informed by mail
* (the guest mail can be switched off, e.g. when the guest cancelled by phone and was told already) and a task for
* the cancellation costs is created. Open cancellation requests of the guest are completed.
* The one way to cancel a binding booking (package 5). Own bookings: the dates are free again; the guest and the
* landlord are informed by e-mail – the guest's e-mail can be switched off, e.g. when the guest cancelled by phone –, the
* cancellation is recorded with who initiated it, why and who entered it, a task for the cancellation costs and – when
* the guest paid us more than the costs – a refund task are created. Open cancellation requests of the guest are done.
*
* Bookings binding on a portal (A3–A5) are cancelled where the contract was made: here the cancellation is only
* requested (task "Stornierung im Portal veranlassen bzw. prüfen", the dates stay occupied) until somebody confirms that
* it is effective on the portal ({@see confirmOnPortal()}) – nothing is released silently.
*/
class CancelBooking
{
public const INITIATORS = ['guest' => 'vom Gast', 'landlord' => 'vom Vermieter', 'portal' => 'über das Portal'];
/**
* @return bool whether the guest has been informed (true as well when no mail was wanted; false when it failed)
*
* @throws ReservationException
*/
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung', string $initiatedBy = 'landlord'): bool
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung', string $initiatedBy = 'landlord', ?string $reason = null, bool $confirmedOnPortal = false): bool
{
if ($booking->caseType()->isExternallyBinding() && ! $confirmedOnPortal) {
$this->requestOnPortal($booking, $by, $initiatedBy, $reason);
return true;
}
if ($notifyGuest && blank($booking->guest?->email)) {
throw new ReservationException('Der Gast hat keine E-Mail-Adresse – bitte ohne Mail an den Gast stornieren oder die Adresse ergänzen.');
}
DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy): void {
DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy, $reason): void {
$booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
}
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
app(RecordCancellation::class)->handle($booking, $initiatedBy);
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now(), 'portal_cancellation_requested_at' => null]);
app(RecordCancellation::class)->handle($booking, $initiatedBy)->update(['reason' => $reason, 'recorded_by' => $by]);
if ($booking->caseType()->isExternallyBinding()) {
// The contract was made on the portal: the cancellation has to happen (or be checked) there as well.
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::PortalCancellation], [
'status' => BookingTaskStatus::Open,
'due_on' => today(),
'note' => 'Stornierung auch im Portal „'.($booking->processChannel()?->name ?? 'Portal').'“ veranlassen bzw. prüfen, ob sie dort wirksam ist.',
]);
}
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->where('status', BookingTaskStatus::Open)
BookingTask::query()->where('booking_id', $booking->id)
->whereIn('kind', [BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported])
->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
$this->refundTask($booking);
if ($costsTask) {
$cost = CancellationCost::calculate($booking);
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], [
@@ -73,6 +83,60 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa
return $this->notify($booking, $notifyGuest);
}
/**
* A booking binding on a portal was cancelled there (the landlord saw it on the portal, or the portal reported it):
* now the case is cancelled as well. The portal informs the guest; costs are a task only when we collect the money.
*
* @throws ReservationException
*/
public function confirmOnPortal(Booking $booking, string $by, string $initiatedBy = 'portal', ?string $reason = null): bool
{
return $this->handle($booking, notifyGuest: false, costsTask: $booking->process()->payments() === Responsibility::Landlord, by: $by, initiatedBy: $initiatedBy, reason: $reason, confirmedOnPortal: true);
}
/**
* @throws ReservationException
*/
private function requestOnPortal(Booking $booking, string $by, string $initiatedBy, ?string $reason): void
{
DB::transaction(function () use ($booking, $by, $initiatedBy, $reason): void {
$booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
}
$portal = $booking->processChannel()?->name ?? 'Portal';
$booking->update(['portal_cancellation_requested_at' => now()]);
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::PortalCancellation], [
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'completed_by' => null, 'completed_at' => null,
'note' => 'Stornierung im Portal „'.$portal.'“ veranlassen und prüfen, ob sie dort wirksam ist. Erst dann „Stornierung bestätigen“ – bis dahin bleibt der Zeitraum belegt.',
]);
CaseLog::record($booking, 'status', 'Stornierung beim Portal '.$portal.' veranlasst ('.(self::INITIATORS[$initiatedBy] ?? $initiatedBy).') – der Vorgang bleibt gebucht, bis sie bestätigt ist', $reason, actor: $by);
});
}
/**
* When the guest paid us more than the cancellation costs, the difference is a refund to check.
*/
private function refundTask(Booking $booking): void
{
if ($booking->process()->payments() !== Responsibility::Landlord || $booking->paidToUs() <= 0) {
return;
}
$cost = CancellationCost::calculate($booking);
$fee = $cost['fee'] ?? null;
$paid = $booking->paidToUs();
if ($fee !== null && $paid <= $fee) {
return;
}
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::RefundCheck], [
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'completed_by' => null, 'completed_at' => null,
'note' => 'Bezahlt: '.Money::format($paid).($fee !== null ? ' · Stornokosten laut Regel: '.Money::format($fee).' · zu erstatten: '.Money::format($paid - $fee) : ' · Stornokosten von Hand festlegen, den Rest erstatten').'. Erstattung als Zahlung „Erstattung an den Gast“ erfassen.',
]);
}
private function notify(Booking $booking, bool $notifyGuest): bool
{
$informed = true;
+480
View File
@@ -0,0 +1,480 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus;
use App\Enums\QuoteLineType;
use App\Exceptions\ReservationException;
use App\Mail\BookingChanged;
use App\Mail\ChangeProposed;
use App\Models\Booking;
use App\Models\BookingChange;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Pricing\PortalPrice;
use App\Pricing\PriceCalculator;
use App\Pricing\PriceQuote;
use App\Pricing\PrivateStayPrice;
use App\Pricing\QuoteException;
use App\Pricing\QuoteLine;
use App\Pricing\StayRequest;
use App\Process\CaseLog;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* Changes a booking after it became binding (package 5, UMSETZUNGSPLAN §4.6): dates, length of stay, number of guests,
* services and price. Before anything changes the consequences are put together – calendar and portals, price and its
* origin, payment plan, refund or additional payment, confirmation – and the person confirms them.
*
* Two ways, kept strictly apart:
* - **agreed**: the change was already agreed with the guest (phone, e-mail, in person, on the portal); it takes effect
* at once and the case keeps who asked, why, from when and on which basis. An updated confirmation only informs the
* guest – it is not taken as the guest's consent.
* - **proposed**: the guest still has to agree; nothing changes until the guest accepts through the signed link.
*
* Own bookings get their price recalculated (kept adjustments, or an agreed price); bookings binding on a portal take the
* portal's new total; internal cases (A6) keep their agreed rent and recalculate services and tourist tax.
*/
class ChangeBooking
{
public const REQUESTED_BY = ['guest', 'landlord', 'portal'];
public function __construct(
private PriceCalculator $calculator,
private PrivateStayPrice $privateStay,
private AvailabilityChecker $availability,
private PortalPrice $portalPrice,
private RecordPayment $payments,
) {}
/**
* The consequences of a change, without changing anything.
*
* @param array{arrival?: ?string, departure?: ?string, guests?: ?int, extras?: ?array<int, int>, portal_total?: ?int, agreed_total?: ?int, agreed_total_label?: ?string, rent?: ?int, tourist_tax_persons?: ?int} $changes
* @return array{errors: list<string>, before: array<string, mixed>, after: array<string, mixed>, summary: list<string>, calendar: list<string>, portals: list<string>, price: array{before: ?int, after: ?int, difference: ?int, source: string}, payment: list<string>, refund: int, confirmation: bool}
*/
public function preview(Booking $booking, array $changes): array
{
$booking->loadMissing(['property', 'payments', 'guest']);
$errors = [];
$before = self::snapshot($booking);
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
$guests = array_key_exists('guests', $changes) && filled($changes['guests']) ? (int) $changes['guests'] : $booking->guests;
$extras = array_key_exists('extras', $changes) && is_array($changes['extras']) ? array_filter(array_map('intval', $changes['extras'])) : (array) ($booking->extras ?? []);
if ($departure->lessThanOrEqualTo($arrival)) {
$errors[] = 'Die Abreise muss nach der Anreise liegen.';
} elseif (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
$errors[] = 'Der neue Zeitraum ist nicht frei.';
}
if ($guests !== null && $guests > $booking->property->max_guests) {
$errors[] = 'Höchstens '.$booking->property->max_guests.' Personen.';
}
[$quote, $source, $priceError] = $departure->greaterThan($arrival) ? $this->price($booking, $changes, $arrival, $departure, $guests, $extras) : [null, '–', null];
if ($priceError !== null) {
$errors[] = $priceError;
}
$paid = $booking->paidAmount();
$total = $quote !== null ? $quote['total'] : $booking->total;
$depositPaid = $booking->deposit !== null && $paid >= $booking->deposit && $paid > 0;
$deposit = $quote === null ? $booking->deposit : ($depositPaid ? $booking->deposit : ($quote['deposit'] ?? $booking->deposit));
$after = [
'arrival' => $arrival->toDateString(), 'departure' => $departure->toDateString(), 'guests' => $guests, 'extras' => $extras,
'quote' => $quote['quote'] ?? $booking->quote, 'total' => $total, 'deposit' => $deposit,
'balance_due_on' => $quote['balance_due_on'] ?? $booking->balance_due_on?->toDateString(),
'rent' => $changes['rent'] ?? null, 'tourist_tax_persons' => array_key_exists('tourist_tax_persons', $changes) ? $changes['tourist_tax_persons'] : $booking->tourist_tax_persons,
];
[$calendar, $portals] = $this->calendarConsequences($booking, $arrival, $departure);
$difference = $total !== null && $booking->total !== null ? $total - $booking->total : null;
$refund = $total !== null ? max(0, $paid - $total) : 0;
$payment = array_values(array_filter([
$booking->wantsPaymentTasks() || ($total !== null && $total > 0 && $booking->process()->payments()->value === 'landlord' && ! $booking->isInternal()) ? 'Bezahlt bisher: '.Money::format($paid).' · danach offen: '.Money::format(max(0, (int) $total - $paid)) : null,
$refund > 0 ? 'Der Gast hat mehr bezahlt als der neue Preis: '.Money::format($refund).' zu erstatten (Aufgabe wird angelegt).' : null,
$depositPaid ? 'Die Anzahlung ist bezahlt und bleibt unverändert.' : null,
$after['balance_due_on'] !== ($booking->balance_due_on?->toDateString()) && $after['balance_due_on'] !== null && ! $booking->isInternal() ? 'Restzahlung neu fällig am '.CarbonImmutable::parse($after['balance_due_on'])->format('d.m.Y').'.' : null,
$booking->process()->payments()->value === 'portal' ? 'Die Zahlung läuft weiter über das Portal.' : null,
]));
return [
'errors' => $errors,
'before' => $before,
'after' => $after,
'summary' => self::summary($before, $after),
'calendar' => $calendar,
'portals' => $portals,
'price' => ['before' => $booking->total, 'after' => $total, 'difference' => $difference, 'source' => $source],
'payment' => $payment,
'refund' => $refund,
'confirmation' => ! $booking->isInternal() && filled($booking->guest?->email),
];
}
/**
* An agreed change (or a change of an internal case): takes effect at once.
*
* @param array<string, mixed> $changes
* @param array{requested_by: string, reason: string, basis: ChangeBasis, agreed_at?: ?string, effective_on?: ?string, send_confirmation?: bool} $meta
*
* @throws ReservationException
*/
public function apply(Booking $booking, array $changes, array $meta, ?string $by = null): BookingChange
{
$this->guard($booking);
if ($meta['basis'] === ChangeBasis::GuestLink) {
throw new ReservationException('Eine Zustimmung über den Link entsteht nur, wenn der Gast selbst annimmt.');
}
$change = DB::transaction(function () use ($booking, $changes, $meta, $by): BookingChange {
$booking->lockForTransition();
$preview = $this->preview($booking, $changes);
if ($preview['errors'] !== []) {
throw new ReservationException(implode(' ', $preview['errors']));
}
$change = $booking->changes()->create([
'status' => ChangeStatus::Applied, 'requested_by' => $meta['requested_by'], 'basis' => $meta['basis'],
'reason' => trim((string) $meta['reason']), 'effective_on' => $meta['effective_on'] ?? today()->toDateString(),
'agreed_at' => $meta['basis'] === ChangeBasis::NotNeeded ? null : ($meta['agreed_at'] ?? now()),
'agreed_by' => $meta['basis'] === ChangeBasis::NotNeeded ? null : ($booking->guest?->full_name ?? 'Gast'),
'before' => $preview['before'], 'after' => $preview['after'], 'consequences' => self::consequences($preview),
'applied_at' => now(), 'recorded_by' => $by,
]);
$change->tenant_id = $booking->tenant_id;
$change->save();
$this->write($booking, $preview, $meta['reason'], $by, $change);
return $change;
});
if ($meta['send_confirmation'] ?? false) {
$this->confirm($booking->fresh(), $change);
}
return $change->fresh();
}
/**
* A change the guest still has to agree to: nothing changes; the guest gets a link to accept or decline.
*
* @param array<string, mixed> $changes
* @param array{requested_by: string, reason: string, effective_on?: ?string, valid_days?: int} $meta
*
* @throws ReservationException
*/
public function propose(Booking $booking, array $changes, array $meta, ?string $by = null): BookingChange
{
$this->guard($booking);
if ($booking->isInternal() || $booking->caseType()->isExternallyBinding()) {
throw new ReservationException('Ein Vorschlag mit Zustimmungslink ist nur für eigene Buchungen möglich – Portalbuchungen werden im Portal geändert.');
}
if (blank($booking->guest?->email)) {
throw new ReservationException('Für einen Vorschlag wird die E-Mail-Adresse des Gastes benötigt.');
}
if ($booking->changes()->where('status', ChangeStatus::Proposed)->exists()) {
throw new ReservationException('Es liegt schon ein Änderungsvorschlag beim Gast. Bitte zuerst zurückziehen.');
}
$preview = $this->preview($booking, $changes);
if ($preview['errors'] !== []) {
throw new ReservationException(implode(' ', $preview['errors']));
}
$change = $booking->changes()->create([
'status' => ChangeStatus::Proposed, 'requested_by' => $meta['requested_by'], 'reason' => trim((string) $meta['reason']),
'effective_on' => $meta['effective_on'] ?? null, 'before' => $preview['before'], 'after' => $preview['after'],
'consequences' => self::consequences($preview), 'expires_at' => now()->addDays((int) ($meta['valid_days'] ?? 7)), 'recorded_by' => $by,
]);
$change->tenant_id = $booking->tenant_id;
$change->save();
CaseLog::record($booking, 'change', 'Änderung dem Gast vorgeschlagen: '.implode(' · ', $preview['summary']), $meta['reason'], data: ['booking_change_id' => $change->id]);
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ChangeProposed($booking, $change, $this->link($change)));
} catch (Throwable $exception) {
Log::warning('Änderungsvorschlag nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
throw new ReservationException('Der Vorschlag ist gespeichert, aber die E-Mail konnte nicht versendet werden.');
}
return $change;
}
/**
* The guest accepts a proposed change through the signed link: the dates are checked again, then it takes effect.
*
* @throws ReservationException
*/
public function accept(BookingChange $change, ?string $ip = null): BookingChange
{
return DB::transaction(function () use ($change, $ip): BookingChange {
$booking = $change->booking;
$booking->lockForTransition();
$change = BookingChange::query()->whereKey($change->id)->lockForUpdate()->firstOrFail();
if ($change->status !== ChangeStatus::Proposed) {
throw new ReservationException('Dieser Vorschlag ist nicht mehr offen.');
}
if ($change->expires_at !== null && $change->expires_at->isPast()) {
$change->update(['status' => ChangeStatus::Expired]);
throw new ReservationException('Dieser Vorschlag ist abgelaufen. Bitte melden Sie sich bei uns.');
}
$after = (array) $change->after;
$preview = $this->preview($booking, [...$after, 'agreed_total' => $after['total'] ?? null, 'portal_total' => null]);
if ($preview['errors'] !== []) {
throw new ReservationException('Die Änderung ist leider nicht mehr möglich: '.implode(' ', $preview['errors']));
}
$change->update(['status' => ChangeStatus::Applied, 'basis' => ChangeBasis::GuestLink, 'agreed_at' => now(), 'agreed_by' => $booking->guest?->full_name,
'decided_at' => now(), 'decision_ip_hash' => $ip ? hash('sha256', $ip) : null, 'applied_at' => now()]);
CaseLog::context(fn () => $this->write($booking, $preview, (string) $change->reason, CaseLog::GUEST, $change), actor: CaseLog::GUEST);
return $change->fresh();
});
}
public function decline(BookingChange $change, ?string $ip = null): void
{
if ($change->status !== ChangeStatus::Proposed) {
return;
}
$change->update(['status' => ChangeStatus::Declined, 'decided_at' => now(), 'decision_ip_hash' => $ip ? hash('sha256', $ip) : null]);
CaseLog::record($change->booking, 'change', 'Änderungsvorschlag vom Gast abgelehnt', actor: CaseLog::GUEST, data: ['booking_change_id' => $change->id]);
}
public function withdraw(BookingChange $change, ?string $by = null): void
{
if ($change->status === ChangeStatus::Proposed) {
$change->update(['status' => ChangeStatus::Withdrawn, 'decided_at' => now()]);
CaseLog::record($change->booking, 'change', 'Änderungsvorschlag zurückgezogen', actor: $by);
}
}
/**
* The guest's signed link to a proposed change (valid while the proposal is).
*/
public function link(BookingChange $change): string
{
$until = $change->expires_at ?? now()->addDays(7);
return $change->booking->website()?->temporarySignedRoute('changes.show', $until, ['change' => $change])
?? URL::temporarySignedRoute('changes.show', $until, ['change' => $change]);
}
/**
* Sends the updated confirmation of an agreed change (information, not consent).
*/
public function confirm(Booking $booking, BookingChange $change): bool
{
if ($booking->isInternal() || blank($booking->guest?->email)) {
return false;
}
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingChanged($booking, $change));
$change->update(['confirmation_sent_at' => now()]);
return true;
} catch (Throwable $exception) {
Log::warning('Änderungsbestätigung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
return false;
}
}
/**
* @throws ReservationException
*/
private function guard(Booking $booking): void
{
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw new ReservationException('Ändern lässt sich nur eine bestehende Buchung oder Belegung. Ein Angebot wird über „Angebot ändern & neu senden“ geändert.');
}
}
/**
* Writes the new state on the case (inside the transaction of the caller).
*
* @param array<string, mixed> $preview
*/
private function write(Booking $booking, array $preview, string $reason, ?string $by, BookingChange $change): void
{
$after = $preview['after'];
$booking->update([
'arrival' => $after['arrival'], 'departure' => $after['departure'], 'guests' => $after['guests'], 'extras' => $after['extras'],
'quote' => $after['quote'], 'total' => $after['total'], 'deposit' => $after['deposit'], 'balance_due_on' => $after['balance_due_on'],
'tourist_tax_persons' => $after['tourist_tax_persons'],
]);
CaseLog::record($booking, 'change', 'Geändert: '.implode(' · ', $preview['summary']), $reason, data: ['booking_change_id' => $change->id], actor: $by);
$this->payments->updateStatus($booking->fresh());
if ($preview['refund'] > 0) {
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::RefundCheck], [
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(),
'note' => 'Nach der Änderung zu viel bezahlt: '.Money::format($preview['refund']).' an den Gast erstatten (als „Erstattung“ erfassen).',
'completed_by' => null, 'completed_at' => null,
]);
}
}
/**
* The new price and where it comes from.
*
* @param array<string, mixed> $changes
* @param array<int, int> $extras
* @return array{0: ?array{quote: array<string, mixed>, total: int, deposit: ?int, balance_due_on: ?string}, 1: string, 2: ?string}
*/
private function price(Booking $booking, array $changes, CarbonImmutable $arrival, CarbonImmutable $departure, ?int $guests, array $extras): array
{
if ($booking->isInternal()) {
try {
$rent = array_key_exists('rent', $changes) && $changes['rent'] !== null ? (int) $changes['rent'] : PrivateStayPrice::rentOf($booking->quote);
$taxPersons = array_key_exists('tourist_tax_persons', $changes) ? ($changes['tourist_tax_persons'] === null ? null : (int) $changes['tourist_tax_persons']) : $booking->tourist_tax_persons;
$quote = $this->privateStay->quote($booking->property, $arrival, $departure, $guests, $extras, $rent, $taxPersons);
return [['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => null, 'balance_due_on' => null], 'vereinbart (Miete, Leistungen, Kurabgabe)', null];
} catch (QuoteException $exception) {
return [null, '–', $exception->getMessage()];
}
}
if ($booking->caseType()->isExternallyBinding() || ($booking->quote['source'] ?? null) === 'portal') {
$total = filled($changes['portal_total'] ?? null) ? (int) $changes['portal_total'] : $booking->total;
if ($total === null) {
return [null, 'laut Portal – noch nicht bekannt', null];
}
$columns = $this->portalPrice->columns($booking->property, $arrival, $departure, $guests, $total, $booking->processChannel()?->name);
return [['quote' => $columns['quote'], 'total' => (int) $columns['total'], 'deposit' => $columns['deposit'], 'balance_due_on' => $columns['balance_due_on']],
filled($changes['portal_total'] ?? null) ? 'neuer Gesamtpreis laut Portal' : 'Gesamtpreis laut Portal unverändert – bitte neuen Betrag eintragen, falls das Portal ihn geändert hat', null];
}
$agreed = filled($changes['agreed_total'] ?? null) ? (int) $changes['agreed_total'] : null;
try {
$quote = $this->calculator->calculate($booking->property, new StayRequest($arrival, $departure, max(1, (int) $guests), $extras, $booking->promo_code));
foreach ((array) ($booking->quote['lines'] ?? []) as $line) {
if (($line['type'] ?? null) === QuoteLineType::Adjustment->value) {
$quote = $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, (string) $line['label'], 1, (int) $line['amount'], (int) $line['amount']));
}
}
$source = 'aus Ihren Preisen neu berechnet';
} catch (QuoteException $exception) {
if ($agreed === null) {
return [null, '–', 'Preis: '.$exception->getMessage().' Bitte einen vereinbarten Preis eintragen.'];
}
$quote = new PriceQuote($arrival, $departure, (int) $guests, [new QuoteLine(QuoteLineType::Accommodation, 'Vereinbarter Preis', 1, $agreed, $agreed)], $booking->property->deposit_percent, $arrival->subDays($booking->property->balance_due_days_before_arrival));
$source = 'vereinbarter Preis';
}
if ($agreed !== null && $agreed !== $quote->total()) {
$label = trim((string) ($changes['agreed_total_label'] ?? '')) ?: 'Vereinbarte Preisanpassung';
$quote = $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, $label, 1, $agreed - $quote->total(), $agreed - $quote->total()));
$source = 'vereinbarter Preis';
}
return [['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => $quote->deposit(), 'balance_due_on' => $quote->balanceDueOn->toDateString()], $source, null];
}
/**
* What happens in the calendar and on the portals that are blocked by hand.
*
* @return array{0: list<string>, 1: list<string>}
*/
private function calendarConsequences(Booking $booking, CarbonImmutable $arrival, CarbonImmutable $departure): array
{
$oldStart = $booking->arrival;
$oldEnd = $booking->departure;
if ($arrival->equalTo($oldStart) && $departure->equalTo($oldEnd)) {
return [['Kalender unverändert.'], []];
}
$added = array_values(array_filter([
$arrival->lessThan($oldStart) ? [$arrival, $oldStart->min($departure)] : null,
$departure->greaterThan($oldEnd) ? [$oldEnd->max($arrival), $departure] : null,
]));
$freed = array_values(array_filter([
$oldStart->lessThan($arrival) ? [$oldStart, $arrival->min($oldEnd)] : null,
$oldEnd->greaterThan($departure) ? [$departure->max($oldStart), $oldEnd] : null,
]));
$range = fn (array $pair): string => $pair[0]->format('d.m.').'–'.$pair[1]->format('d.m.Y');
$calendar = [
...array_map(fn (array $pair): string => 'Neu belegt: '.$range($pair), $added),
...array_map(fn (array $pair): string => 'Wieder frei: '.$range($pair), $freed),
'Die Kalender für die Portale zeigen den neuen Zeitraum beim nächsten Abruf.',
];
$origin = $booking->origin_channel_id ?? $booking->import_channel_id;
$portals = $booking->property->channels()->active()->where('requires_manual_blocking', true)->get()
->filter(fn (Channel $channel): bool => $channel->exportsOccupations() && $channel->id !== $origin)
->map(fn (Channel $channel): string => 'Aufgabe für '.$channel->name.': '.implode(', ', [...array_map(fn (array $pair): string => 'sperren '.$range($pair), $added), ...array_map(fn (array $pair): string => 'freigeben '.$range($pair), $freed)]))
->values()->all();
if ($booking->caseType()->isExternallyBinding()) {
$portals[] = 'Die Änderung selbst muss im Portal „'.($booking->processChannel()?->name ?? 'Portal').'“ vorliegen – hier wird sie nur nachgetragen.';
}
return [$calendar, $portals];
}
/**
* @return array<string, mixed>
*/
private static function snapshot(Booking $booking): array
{
return [
'arrival' => $booking->arrival->toDateString(), 'departure' => $booking->departure->toDateString(), 'guests' => $booking->guests,
'extras' => (array) ($booking->extras ?? []), 'quote' => $booking->quote, 'total' => $booking->total, 'deposit' => $booking->deposit,
'balance_due_on' => $booking->balance_due_on?->toDateString(), 'tourist_tax_persons' => $booking->tourist_tax_persons,
];
}
/**
* @param array<string, mixed> $before
* @param array<string, mixed> $after
* @return list<string>
*/
private static function summary(array $before, array $after): array
{
$date = fn (?string $value): string => $value ? CarbonImmutable::parse($value)->format('d.m.Y') : '–';
$lines = [];
if ($before['arrival'] !== $after['arrival'] || $before['departure'] !== $after['departure']) {
$lines[] = 'Zeitraum '.$date($before['arrival']).'–'.$date($before['departure']).' → '.$date($after['arrival']).'–'.$date($after['departure']);
}
if ($before['guests'] !== $after['guests']) {
$lines[] = 'Personen '.($before['guests'] ?? '?').' → '.($after['guests'] ?? '?');
}
if ((array) $before['extras'] != (array) $after['extras']) {
$lines[] = 'Zusatzleistungen geändert';
}
if ($before['total'] !== $after['total']) {
$lines[] = 'Preis '.($before['total'] === null ? '–' : Money::format($before['total'])).' → '.($after['total'] === null ? '–' : Money::format($after['total']));
}
return $lines === [] ? ['keine inhaltliche Änderung'] : $lines;
}
/**
* @param array<string, mixed> $preview
* @return array<string, mixed>
*/
private static function consequences(array $preview): array
{
return ['summary' => $preview['summary'], 'calendar' => $preview['calendar'], 'portals' => $preview['portals'], 'price' => $preview['price'], 'payment' => $preview['payment'], 'refund' => $preview['refund']];
}
}
+6 -1
View File
@@ -12,6 +12,7 @@
use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\BookingConfirmed;
use App\Mail\BookingDocumentation;
use App\Mail\StayConfirmed;
use App\Models\Booking;
use App\Process\CaseLog;
use App\Support\Inbox;
@@ -108,7 +109,11 @@ public function deliver(Booking $booking, bool $notifyGuest = true, ?DocumentKin
return true;
}
Mail::to($booking->guest->email, $booking->guest->full_name)->send($kind === DocumentKind::ExternalRecord ? new BookingDocumentation($booking) : new BookingConfirmed($booking));
Mail::to($booking->guest->email, $booking->guest->full_name)->send(match ($kind) {
DocumentKind::ExternalRecord => new BookingDocumentation($booking),
DocumentKind::StayConfirmation => new StayConfirmed($booking),
default => new BookingConfirmed($booking),
});
$booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->save();
return true;
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\PrivateStayPrice;
use App\Pricing\QuoteException;
use App\Process\CaseLog;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* Own use, a private stay or a block as a case (A6, package 6): the dates are occupied at once and the portals are
* blocked like for any booking. A block has nothing but dates and an occasion; own use and private stays may have
* guests, services, an agreed rent (0 by default), the tourist tax and payments – but never a rental contract, payment
* reminders, reviews or marketing (the A6 profile switches them off).
*/
class CreateInternalCase
{
public function __construct(private AvailabilityChecker $availability, private PrivateStayPrice $price) {}
/**
* @param array{occasion?: ?string, guest?: ?array<string, ?string>, guests?: ?int, extras?: ?array<int, int>, rent?: ?int, tourist_tax_persons?: ?int, tourist_tax_note?: ?string, notes?: ?string} $data
*
* @throws ReservationException
* @throws QuoteException
*/
public function handle(Property $property, InternalKind $kind, CarbonImmutable $arrival, CarbonImmutable $departure, array $data = []): Booking
{
if ($departure->lessThanOrEqualTo($arrival)) {
throw new ReservationException('Das Ende muss nach dem Beginn liegen.');
}
return DB::transaction(function () use ($property, $kind, $arrival, $departure, $data): Booking {
Property::query()->whereKey($property->id)->lockForUpdate()->firstOrFail();
if (! $this->availability->isAvailable($property, $arrival, $departure)) {
throw ReservationException::notAvailable();
}
$guests = $kind === InternalKind::Block ? null : (filled($data['guests'] ?? null) ? (int) $data['guests'] : null);
$extras = $kind === InternalKind::Block ? [] : array_filter(array_map('intval', (array) ($data['extras'] ?? [])));
$taxPersons = $kind === InternalKind::Block ? null : (filled($data['tourist_tax_persons'] ?? null) ? (int) $data['tourist_tax_persons'] : null);
$quote = $kind === InternalKind::Block ? null : $this->price->quote($property, $arrival, $departure, $guests, $extras, (int) ($data['rent'] ?? 0), $taxPersons);
$guest = $kind->hasGuests() ? $this->guest((array) ($data['guest'] ?? [])) : null;
$booking = $property->bookings()->create([
'guest_id' => $guest?->id,
'status' => BookingStatus::Confirmed,
'source' => 'internal',
'intake' => IntakeKind::Internal,
'internal_kind' => $kind,
'occasion' => filled($data['occasion'] ?? null) ? trim((string) $data['occasion']) : null,
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'guests' => $guests,
'extras' => $extras,
'quote' => $quote?->toArray(),
'total' => $quote?->total(),
'tourist_tax_persons' => $taxPersons,
'tourist_tax_note' => filled($data['tourist_tax_note'] ?? null) ? trim((string) $data['tourist_tax_note']) : null,
'confirmed_at' => now(),
'internal_notes' => filled($data['notes'] ?? null) ? trim((string) $data['notes']) : null,
]);
CaseLog::record($booking, 'intake', $kind->getLabel().' eingetragen'.($booking->occasion ? ': '.$booking->occasion : ''));
return $booking;
});
}
/**
* The guest of a private stay – only with a real name; a known e-mail address finds the existing guest.
*
* @param array<string, ?string> $data
*/
private function guest(array $data): ?Guest
{
$data = array_map(fn ($value) => filled($value) ? trim((string) $value) : null, Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']));
if (blank($data['first_name'] ?? null) || blank($data['last_name'] ?? null)) {
return null;
}
$email = filled($data['email'] ?? null) ? mb_strtolower($data['email']) : null;
if ($email !== null && ($known = Guest::query()->where('email', $email)->whereNull('anonymized_at')->first()) !== null) {
return $known;
}
return Guest::query()->create([...array_filter($data, fn ($value) => $value !== null), 'email' => $email ?? '']);
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\InternalKind;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Process\CaseLog;
use Illuminate\Support\Facades\DB;
/**
* Lifts a block or calls off an own use / private stay (A6). It is no cancellation: no costs, no refund rule, no mails –
* the dates are free again and the portals are released like for any booking that ends.
*/
class EndInternalCase
{
/**
* @throws ReservationException
*/
public function handle(Booking $booking, string $reason, ?string $by = null): void
{
if (! $booking->isInternal()) {
throw new ReservationException('Nur eigene Nutzung, private Aufenthalte und Sperren werden so beendet.');
}
DB::transaction(function () use ($booking, $reason, $by): void {
$booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'aufgehoben');
}
CaseLog::context(fn () => $booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]), actor: $by, reason: $reason);
CaseLog::record($booking, 'status', self::label($booking), $reason, actor: $by);
});
}
public static function label(Booking $booking): string
{
return $booking->internal_kind === InternalKind::Block ? 'Sperre aufgehoben' : 'Aufenthalt abgesagt';
}
}
+10 -4
View File
@@ -3,6 +3,7 @@
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod;
use App\Models\Booking;
use App\Models\Payment;
@@ -10,20 +11,25 @@
use Illuminate\Support\Facades\DB;
/**
* Records a received payment (or a refund with a negative amount) and moves the booking along:
* Bestätigt → Anzahlung erhalten → Bezahlt.
* Records a payment of a case with its kind (package 8): the guest paid us, the portal reports the guest paid it, the
* portal paid out to us, or we refunded the guest. Only the guest's payments move the booking along
* (Bestätigt → Anzahlung erhalten → Bezahlt); a refund is stored as a negative amount.
*/
class RecordPayment
{
public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null): Payment
public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null, PaymentKind $kind = PaymentKind::Guest, ?string $source = null): Payment
{
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy): Payment {
$amount = $kind === PaymentKind::Refund ? -abs($amount) : $amount;
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy, $kind, $source): Payment {
$payment = $booking->payments()->create([
'amount' => $amount,
'paid_on' => $paidOn->toDateString(),
'method' => $method,
'note' => $note,
'recorded_by' => $recordedBy,
'kind' => $kind,
'source' => $source,
]);
$booking->unsetRelation('payments');
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Actions;
use App\Enums\AmountKind;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod;
use App\Models\Booking;
use App\Pricing\PortalPrice;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/**
* Takes over what a portal shows about a booking (package 8): the guest's total as the agreed price ("Gesamtpreis laut
* Portal"), and – as far as the portal shows them – price positions, collective amounts, commission, announced payouts,
* instalments and what the guest has paid to the portal. Every value is stored with its source and date as stated; the
* total is never recalculated from the positions, and a statement entered twice is stored once.
*/
class RecordPortalAmounts
{
public function __construct(private PortalPrice $price, private RecordPayment $payments) {}
/**
* @param list<array{kind: AmountKind|string, label?: ?string, amount: int, due_on?: ?string, note?: ?string}> $amounts
* @param list<array{amount: int, paid_on: string}> $paidViaPortal instalments the portal shows as paid by the guest
*/
public function handle(Booking $booking, ?int $guestTotal, array $amounts, array $paidViaPortal, string $source, ?CarbonImmutable $statedOn = null, ?string $by = null): void
{
$statedOn ??= CarbonImmutable::today();
DB::transaction(function () use ($booking, $guestTotal, $amounts, $paidViaPortal, $source, $statedOn, $by): void {
if ($guestTotal !== null && $guestTotal !== $booking->total) {
$before = $booking->total;
$booking->update($this->price->columns($booking->property, $booking->arrival, $booking->departure, $booking->guests, $guestTotal, $source));
CaseLog::record($booking, 'price', 'Gesamtpreis laut '.$source.': '.Money::format($guestTotal).($before !== null ? ' (vorher '.Money::format($before).')' : ''));
}
foreach ($amounts as $row) {
$kind = $row['kind'] instanceof AmountKind ? $row['kind'] : AmountKind::from((string) $row['kind']);
$label = filled($row['label'] ?? null) ? trim((string) $row['label']) : null;
$exists = $booking->amounts()->where('kind', $kind)->where('amount', (int) $row['amount'])->where('source', $source)
->where(fn ($query) => $label === null ? $query->whereNull('label') : $query->where('label', $label))->exists();
if ($exists) {
continue;
}
$booking->amounts()->create([
'kind' => $kind, 'label' => $label, 'amount' => (int) $row['amount'], 'source' => $source,
'stated_on' => $statedOn->toDateString(), 'due_on' => filled($row['due_on'] ?? null) ? $row['due_on'] : null,
'note' => filled($row['note'] ?? null) ? trim((string) $row['note']) : null, 'recorded_by' => $by,
]);
}
foreach ($paidViaPortal as $row) {
$paidOn = CarbonImmutable::parse($row['paid_on']);
$known = $booking->payments()->where('kind', PaymentKind::GuestViaPortal)->where('amount', (int) $row['amount'])->whereDate('paid_on', $paidOn)->exists();
if (! $known) {
$this->payments->handle($booking, (int) $row['amount'], $paidOn, PaymentMethod::Other, 'laut '.$source, $by, PaymentKind::GuestViaPortal, $source);
}
}
});
app(CaseAutomation::class)->advance($booking->fresh());
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ public static function kindFor(Booking $booking): DocumentKind
{
$kind = DocumentKind::forCase($booking);
return in_array($kind, [DocumentKind::Confirmation, DocumentKind::ExternalRecord], true) ? $kind : DocumentKind::Confirmation;
return in_array($kind, [DocumentKind::Confirmation, DocumentKind::ExternalRecord, DocumentKind::StayConfirmation], true) ? $kind : DocumentKind::Confirmation;
}
private function send(Booking $booking, DocumentComposition $composition, bool $acknowledged, bool $automatic): bool
+10
View File
@@ -41,6 +41,16 @@ public function properties(Channel $channel, Booking|BlockedPeriod $occupation):
/** @return array<string, string|null> */
public function context(Booking|BlockedPeriod $occupation): array
{
// Own use, private stays and blocks (A6) are exported exactly like the manual blocks they replace: no reference;
// a guest's name only where the channel exports names at all.
if ($occupation instanceof Booking && $occupation->isInternal()) {
$guest = $occupation->guest?->anonymized_at === null ? $occupation->guest : null;
return ['occupation_label' => 'Belegt', 'property_name' => $occupation->property->name, 'arrival' => $occupation->arrival->format('d.m.Y'),
'departure' => $occupation->departure->format('d.m.Y'), 'nights' => (string) (int) $occupation->arrival->diffInDays($occupation->departure), 'channel_name' => null,
...($guest !== null ? ['guest_first_name' => $guest->first_name, 'guest_full_name' => filled($guest->last_name) ? $guest->full_name : null] : [])];
}
$booking = $occupation instanceof Booking;
$start = $booking ? $occupation->arrival : $occupation->starts_on;
$end = $booking ? $occupation->departure : $occupation->ends_on;
+2 -1
View File
@@ -33,7 +33,8 @@ public function build(Channel $channel): string
}
foreach ($bookings->with(['guest', 'property'])->orderBy('id')->get() as $booking) {
/** @var Booking $booking */
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at, (new ICalExportFields)->properties($channel, $booking));
// A block taken over as a case keeps the identity the portals already know.
$events[] = $this->event(($booking->export_uid ?? "booking-{$booking->id}").$suffix, $booking->arrival, $booking->departure, $booking->updated_at, (new ICalExportFields)->properties($channel, $booking));
}
$blocks = $property->blockedPeriods()
+159
View File
@@ -0,0 +1,159 @@
<?php
namespace App\Console\Commands;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Tenant;
use App\Process\CaseLog;
use App\Process\ProcessSettings;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
#[Signature('cases:adopt-blocks
{--apply : Wirklich übernehmen (ohne: nur Vorschau)}
{--revert= : Eine frühere Übernahme anhand ihres Berichts zurücknehmen}')]
#[Description('Bisherige manuelle Sperren als A6-Vorgänge übernehmen (Vorschau, Bericht, wiederholbar, rücknehmbar); der Kalenderexport für die Portale bleibt gleich')]
class AdoptManualBlocks extends Command
{
private const DIRECTORY = 'block-adoptions';
private const ADOPTED = 'übernommen';
public function handle(TenantRunner $runner, ProcessSettings $settings): int
{
if (filled($this->option('revert'))) {
return $this->revert((string) $this->option('revert'));
}
$apply = (bool) $this->option('apply');
$report = ['run' => now()->format('Ymd-His'), 'apply' => $apply, 'entries' => []];
$succeeded = $runner->each(function (Tenant $tenant) use ($apply, $settings, &$report): void {
$blocks = BlockedPeriod::query()->with(['property', 'guest'])->where('source', 'manual')->whereNull('linked_booking_id')->orderBy('starts_on')->get();
foreach ($blocks as $block) {
$kind = $block->guest_id !== null ? InternalKind::PrivateStay : InternalKind::fromPurpose($block->block_purpose);
$entry = [
'tenant' => $tenant->id, 'blocked_period_id' => $block->id, 'property' => $block->property?->name,
'period' => $block->starts_on->format('d.m.Y').'–'.$block->ends_on->format('d.m.Y'), 'kind' => $kind->value,
'occasion' => $block->block_note ?: $block->reason, 'booking_id' => null, 'result' => 'neu',
];
if (Booking::query()->where('export_uid', 'block-'.$block->id)->exists()) {
$entry['result'] = 'schon übernommen';
} elseif (Booking::query()->occupying()->where('property_id', $block->property_id)->overlapping($block->starts_on, $block->ends_on)->exists()) {
$entry['result'] = 'unklar: überschneidet sich mit einem Vorgang – nicht übernommen';
} elseif ($apply) {
$entry['booking_id'] = $this->adopt($block, $kind, $settings)->id;
$entry['result'] = self::ADOPTED;
}
$report['entries'][] = $entry;
}
});
$this->table(['Wohnung', 'Zeitraum', 'Art', 'Anlass', 'Ergebnis', 'Vorgang'], array_map(fn (array $entry): array => [
$entry['property'], $entry['period'], InternalKind::from($entry['kind'])->getLabel(), $entry['occasion'], $entry['result'], $entry['booking_id'] ? '#'.$entry['booking_id'] : '–',
], $report['entries']));
$suffix = $apply ? '' : '-vorschau';
$path = self::DIRECTORY.'/'.$report['run'].$suffix.'.json';
for ($number = 2; Storage::disk('local')->exists($path); $number++) {
$path = self::DIRECTORY.'/'.$report['run'].$suffix.'-'.$number.'.json';
}
Storage::disk('local')->put($path, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
$counts = collect($report['entries'])->countBy('result')->map(fn (int $count, string $result): string => $result.' '.$count)->implode(', ');
$this->info(($apply ? 'Übernommen' : 'Vorschau – nichts geändert').': '.($counts ?: 'keine manuellen Sperren'));
$this->line('Bericht: storage/app/private/'.$path.($apply ? ' (Rücknahme: --revert='.$path.')' : ''));
if ($succeeded < $runner->tenants()->count()) {
$this->error('Bei mindestens einem Vermieter ist ein Fehler aufgetreten – Details im Protokoll (storage/logs).');
return self::FAILURE;
}
return self::SUCCESS;
}
/**
* The block becomes a case without any side effect: no portal tasks and no mails (the portals have the dates
* already), the same export identity and time stamp; the block is kept (deleted softly) for a revert.
*/
private function adopt(BlockedPeriod $block, InternalKind $kind, ProcessSettings $settings): Booking
{
return DB::transaction(function () use ($block, $kind, $settings): Booking {
$profile = $settings->resolve($block->property, null, IntakeKind::Internal)->withOrigin('migration');
$booking = Model::withoutEvents(function () use ($block, $kind, $profile): Booking {
$booking = new Booking([
'status' => BookingStatus::Confirmed, 'source' => 'internal', 'intake' => IntakeKind::Internal, 'internal_kind' => $kind,
'occasion' => $block->block_note ?: $block->reason, 'arrival' => $block->starts_on->toDateString(), 'departure' => $block->ends_on->toDateString(),
'export_uid' => 'block-'.$block->id, 'confirmed_at' => $block->created_at,
]);
$booking->forceFill([
'tenant_id' => $block->tenant_id, 'property_id' => $block->property_id, 'guest_id' => $block->guest_id,
'case_type' => $profile->caseType, 'profile' => $profile->toArray(),
'created_at' => $block->created_at, 'updated_at' => $block->updated_at,
]);
$booking->timestamps = false;
$booking->save();
// Dates are only cast while timestamps are on; the reference counts by the year of creation.
$booking->timestamps = true;
$reference = $booking->refresh()->nextReference();
$booking->timestamps = false;
$booking->forceFill(['reference' => $reference])->save();
$block->forceFill(['linked_booking_id' => $booking->id, 'review_note' => 'In Vorgang übernommen (A6).'])->saveQuietly();
$block->deleteQuietly();
return $booking;
});
CaseLog::record($booking, 'intake', 'Aus der bisherigen Sperrzeitenliste übernommen'.($booking->occasion ? ': '.$booking->occasion : ''), actor: CaseLog::SYSTEM, data: ['blocked_period_id' => $block->id]);
return $booking;
});
}
/**
* Takes an adoption back: the block comes back as it was and the case created by the run goes – unless somebody has
* worked on the case since (then it is reported and kept).
*/
private function revert(string $path): int
{
if (! Storage::disk('local')->exists($path)) {
$this->error('Bericht nicht gefunden: '.$path);
return self::FAILURE;
}
$report = json_decode((string) Storage::disk('local')->get($path), true);
$kept = [];
foreach ((array) ($report['entries'] ?? []) as $entry) {
if (($entry['result'] ?? null) !== self::ADOPTED) {
continue;
}
$booking = Booking::query()->withoutGlobalScopes()->find($entry['booking_id']);
if ($booking !== null && $booking->events()->where('type', '!=', 'intake')->exists()) {
$kept[] = $booking->reference;
continue;
}
Model::withoutEvents(function () use ($entry, $booking): void {
$block = BlockedPeriod::query()->withoutGlobalScopes()->withTrashed()->find($entry['blocked_period_id']);
$block?->forceFill(['linked_booking_id' => null, 'review_note' => null, 'deleted_at' => null])->saveQuietly();
$booking?->delete();
});
}
$this->info('Zurückgenommen.'.($kept === [] ? '' : ' Nicht entfernt, weil seitdem bearbeitet: '.implode(', ', $kept)));
return self::SUCCESS;
}
}
@@ -38,7 +38,7 @@ public function handle(TenantRunner $runner, PortalIntake $intake): int
$report = ['run' => now()->format('Ymd-His'), 'apply' => $apply, 'entries' => [], 'channel_task_ids' => []];
$firstTask = (int) ChannelTask::query()->withoutGlobalScopes()->max('id');
$runner->each(function (Tenant $tenant) use ($intake, $apply, &$report): void {
$succeeded = $runner->each(function (Tenant $tenant) use ($intake, $apply, &$report): void {
$channels = Channel::query()->when($this->option('channel'), fn ($query, $ids) => $query->whereKey($ids))->orderBy('id')->get();
foreach ($channels as $channel) {
$entries = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id')
@@ -75,6 +75,12 @@ public function handle(TenantRunner $runner, PortalIntake $intake): int
$this->info(($apply ? 'Übernommen' : 'Vorschau – nichts geändert').': '.$counts->map(fn (int $count, string $outcome): string => IntakeOutcome::from($outcome)->getLabel().' '.$count)->implode(', '));
$this->line('Bericht: storage/app/private/'.$path.($apply ? ' (Rücknahme: --revert='.$path.')' : ''));
if ($succeeded < $runner->tenants()->count()) {
$this->error('Bei mindestens einem Vermieter ist ein Fehler aufgetreten – Details im Protokoll (storage/logs).');
return self::FAILURE;
}
return self::SUCCESS;
}
+1
View File
@@ -62,6 +62,7 @@ public function compose(Booking $booking, ?DocumentKind $kind = null, array $cha
$frozen = $kind !== DocumentKind::Offer && ($booking->contract_path !== null || ($booking->offer_version > 0 && is_array($booking->offer_terms)));
$explicitTemplate = ! $frozen && filled($changes['contract_template_id'] ?? null);
$template = match (true) {
$kind === DocumentKind::StayConfirmation => null,
$frozen => isset($booking->offer_terms['template']['id']) ? ContractTemplate::query()->find($booking->offer_terms['template']['id']) : null,
default => OfferTerms::templateFor($booking, $explicitTemplate ? $changes['contract_template_id'] : null),
};
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* A stated amount of a case as a portal or another source shows it (package 8, K01): stored as stated, never derived.
* Positions of the guest's price, what the landlord pays the portal, and what the portal announces to pay out stay
* apart; an unexplained collective amount stays unexplained.
*/
enum AmountKind: string implements HasLabel
{
case Accommodation = 'accommodation';
case Service = 'service';
case Discount = 'discount';
case Fee = 'fee';
case Unexplained = 'unexplained';
case Commission = 'commission';
case PayoutAnnounced = 'payout_announced';
case InstallmentDue = 'installment_due';
public function getLabel(): string
{
return match ($this) {
self::Accommodation => 'Übernachtung',
self::Service => 'Leistung / Zusatzleistung',
self::Discount => 'Rabatt (mit Minus)',
self::Fee => 'Gebühr oder Steuer',
self::Unexplained => 'Sammelposten, nicht aufgeschlüsselt',
self::Commission => 'Provision / an das Portal gezahlt',
self::PayoutAnnounced => 'Angekündigte Auszahlung an uns',
self::InstallmentDue => 'Rate des Gastes laut Portal fällig',
};
}
/**
* Whether the amount is part of the guest's price (and adds up to the guest total).
*/
public function isPricePosition(): bool
{
return in_array($this, [self::Accommodation, self::Service, self::Discount, self::Fee, self::Unexplained], true);
}
}
+4 -2
View File
@@ -19,6 +19,7 @@ enum BookingTaskKind: string implements HasLabel
case PortalCancellation = 'portal_cancellation';
case PortalCancellationReported = 'portal_cancel_reported';
case PortalChangeReported = 'portal_change_reported';
case RefundCheck = 'refund_check';
public function getLabel(): string
{
@@ -31,12 +32,13 @@ public function getLabel(): string
self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen',
self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen',
self::PortalChangeReported => 'Das Portal meldet eine Änderung – bitte prüfen',
self::RefundCheck => 'Erstattung an den Gast prüfen',
};
}
public function isPayment(): bool
{
return ! in_array($this, [self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported], true);
return ! in_array($this, [self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported, self::RefundCheck], true);
}
/**
@@ -50,7 +52,7 @@ public function reminder(): ?array
self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'],
self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'],
self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'],
self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported => null,
self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported, self::RefundCheck => null,
};
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* How a change of a booking was agreed with the guest – the evidence the case keeps (package 5). Sending an updated
* confirmation is none of these: it informs the guest, it does not show the guest's consent.
*/
enum ChangeBasis: string implements HasLabel
{
case Phone = 'phone';
case Email = 'email';
case InPerson = 'in_person';
case Portal = 'portal';
case GuestLink = 'guest_link';
case NotNeeded = 'not_needed';
public function getLabel(): string
{
return match ($this) {
self::Phone => 'am Telefon vereinbart',
self::Email => 'per E-Mail / schriftlich vereinbart',
self::InPerson => 'persönlich vereinbart',
self::Portal => 'im Portal geändert',
self::GuestLink => 'vom Gast über den Link angenommen',
self::NotNeeded => 'keine Zustimmung nötig (eigener Vorgang)',
};
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum ChangeStatus: string implements HasColor, HasLabel
{
/** Sent to the guest, waiting for the guest's answer; nothing has changed yet. */
case Proposed = 'proposed';
/** In force. */
case Applied = 'applied';
case Declined = 'declined';
case Withdrawn = 'withdrawn';
case Expired = 'expired';
public function getLabel(): string
{
return match ($this) {
self::Proposed => 'dem Gast vorgeschlagen',
self::Applied => 'wirksam',
self::Declined => 'vom Gast abgelehnt',
self::Withdrawn => 'zurückgezogen',
self::Expired => 'nicht beantwortet',
};
}
public function getColor(): string
{
return match ($this) {
self::Proposed => 'warning',
self::Applied => 'success',
default => 'gray',
};
}
}
+2 -2
View File
@@ -43,7 +43,7 @@ public function description(): string
self::Information => 'Für Anfragen ohne Reservierung: Preis und Verfügbarkeit ohne Zusage; der Gast kann die Buchung anfragen. Folgt mit Paket 7.',
self::Confirmation => 'Nach der Annahme eines Angebots oder einer direkt vereinbarten Buchung: Bestätigung mit dem Mietvertrag.',
self::ExternalRecord => 'Für Buchungen, die beim Portal bereits verbindlich sind: Buchungsdaten und – falls hinterlegt – Ihre Vorlage, ohne erneute Annahme durch den Gast.',
self::StayConfirmation => 'Für private Überlassungen (Familie, Freunde): Bestätigung des Aufenthalts ohne Mietvertrag. Folgt mit Paket 6.',
self::StayConfirmation => 'Für private Überlassungen (Familie, Freunde): Bestätigung des Aufenthalts ohne Mietvertrag, nur auf Wunsch.',
self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.',
};
}
@@ -84,7 +84,7 @@ public function containsContract(): bool
*/
public function isAvailable(): bool
{
return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord], true);
return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord, self::StayConfirmation], true);
}
/**
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* The kinds of internal cases (A6): the landlord's own use, a private stay of family or friends, or a block without a
* guest (maintenance and the like). None of them has a rental contract, payment reminders, reviews or marketing.
*/
enum InternalKind: string implements HasLabel
{
case OwnUse = 'own_use';
case PrivateStay = 'private_stay';
case Block = 'block';
public function getLabel(): string
{
return match ($this) {
self::OwnUse => 'Eigene Nutzung',
self::PrivateStay => 'Private Überlassung (Familie, Freunde)',
self::Block => 'Sperre (z. B. Wartung)',
};
}
public function hasGuests(): bool
{
return $this === self::PrivateStay;
}
public static function fromPurpose(?BlockedPeriodPurpose $purpose): self
{
return $purpose === BlockedPeriodPurpose::OwnUse ? self::OwnUse : self::Block;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* What a payment is (package 8): only the guest's payments count towards what the guest owes; a portal's payout is
* money on our account but no payment of the guest, and "paid to the portal" is the portal's statement, not money we
* received. Nothing is counted twice.
*/
enum PaymentKind: string implements HasLabel
{
/** The guest paid us (transfer, cash). */
case Guest = 'guest';
/** The portal reports that the guest paid it (no money on our account). */
case GuestViaPortal = 'guest_via_portal';
/** The portal paid out to us. */
case PortalPayout = 'portal_payout';
/** We paid money back to the guest (entered as a positive amount, counted negative). */
case Refund = 'refund';
public function getLabel(): string
{
return match ($this) {
self::Guest => 'Gast hat an uns gezahlt',
self::GuestViaPortal => 'Gast hat laut Portal ans Portal gezahlt',
self::PortalPayout => 'Auszahlung vom Portal erhalten',
self::Refund => 'Erstattung an den Gast',
};
}
/**
* Whether it counts towards what the guest has paid of the agreed total.
*/
public function countsAsGuestPayment(): bool
{
return $this !== self::PortalPayout;
}
/**
* Whether the money moved through our account.
*/
public function isOnOurAccount(): bool
{
return $this !== self::GuestViaPortal;
}
}
+7 -1
View File
@@ -13,11 +13,17 @@ enum QuoteLineType: string
/** Manual price change by the landlord in an offer (negative = reduction). */
case Adjustment = 'adjustment';
/** The agreed rent of an internal case (A6), e.g. 0 for family. */
case Rent = 'rent';
/** The tourist tax (Kurabgabe) as its own position: persons × nights × the landlord's rate. */
case TouristTax = 'tourist_tax';
/**
* Whether the line counts towards the rent on which the deposit is calculated.
*/
public function isRent(): bool
{
return in_array($this, [self::Accommodation, self::ExtraGuest, self::Discount, self::Adjustment], true);
return in_array($this, [self::Accommodation, self::ExtraGuest, self::Discount, self::Adjustment, self::Rent], true);
}
}
+4
View File
@@ -12,11 +12,15 @@ enum Responsibility: string implements HasLabel
case Landlord = 'landlord';
case Portal = 'portal';
/** Nobody: internal cases (A6) have no rental documents, payment reminders or guest mails. */
case Nobody = 'none';
public function getLabel(): string
{
return match ($this) {
self::Landlord => 'Wir',
self::Portal => 'Das Portal',
self::Nobody => 'Entfällt',
};
}
}
@@ -10,6 +10,7 @@
use App\Mail\BookingConfirmed;
use App\Mail\BookingDocumentation;
use App\Mail\OfferMade;
use App\Mail\StayConfirmed;
use App\Models\Booking;
use App\Models\User;
use Closure;
@@ -86,6 +87,7 @@ private static function mailPreview(DocumentComposition $composition): string
return match ($composition->kind) {
DocumentKind::Offer => (new OfferMade($draft, '#'))->render(),
DocumentKind::ExternalRecord => (new BookingDocumentation($draft))->render(),
DocumentKind::StayConfirmation => (new StayConfirmed($draft))->render(),
default => (new BookingConfirmed($draft))->render(),
};
} catch (Throwable $exception) {
+1 -1
View File
@@ -36,7 +36,7 @@ public static function field(string $name, ProcessSetting $setting, string $inhe
->helperText('Automatisch: Das System sendet Angebote bzw. Unterlagen selbst, sobald alle Angaben da sind. Sonst bereitet es alles vor und Sie geben frei.'),
ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – eine Anfrage reserviert nichts'])->placeholder($placeholder),
ProcessSetting::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder),
ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages => Select::make($name)->options(Responsibility::class)->placeholder($placeholder),
ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages => Select::make($name)->options([Responsibility::Landlord->value => Responsibility::Landlord->getLabel(), Responsibility::Portal->value => Responsibility::Portal->getLabel()])->placeholder($placeholder),
ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder),
ProcessSetting::ContractTemplate => Select::make($name)
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
+120
View File
@@ -0,0 +1,120 @@
<?php
namespace App\Filament\Pages;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ContractTemplate;
use App\Models\Property;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use UnitEnum;
/**
* "Wirksame Einstellungen" (expert view, KONFIGURATION_UND_WIRKSAMKEIT): for every property, every way a case can come
* in (direct request, each portal for requests and for binding bookings, own use) the value of every process setting
* that applies right now and the level it comes from – and for one chosen case the profile that really was applied.
* Read only: settings are changed where they belong ("So arbeite ich", the property, the portal).
*/
class EffectiveSettings extends Page
{
use FollowsAdminMode;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsHorizontal;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?string $navigationLabel = 'Wirksame Einstellungen';
protected static ?string $title = 'Wirksame Einstellungen';
protected static ?string $slug = 'wirksame-einstellungen';
protected static ?int $navigationSort = 3;
protected string $view = 'filament.pages.effective-settings';
public ?int $bookingId = null;
public static function canAccess(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin);
}
public function mount(): void
{
$this->bookingId = is_numeric(request()->query('vorgang')) ? (int) request()->query('vorgang') : null;
}
/**
* Every way a case of a property can come in, with the profile that would apply now.
*
* @return list<array{property: Property, columns: list<array{label: string, profile: ProcessProfile}>}>
*/
public function matrix(): array
{
$settings = app(ProcessSettings::class);
return Property::query()->orderBy('name')->get()->map(function (Property $property) use ($settings): array {
$columns = [['label' => 'Direkte Anfrage (Webseite, Telefon)', 'profile' => $settings->resolve($property, null, IntakeKind::Inquiry)]];
foreach (Channel::query()->where('property_id', $property->id)->orderBy('name')->get() as $channel) {
$columns[] = ['label' => $channel->name.' – Anfrage', 'profile' => $settings->resolve($property, $channel, IntakeKind::Inquiry)];
$columns[] = ['label' => $channel->name.' – feste Buchung', 'profile' => $settings->resolve($property, $channel, IntakeKind::Booking)];
}
$columns[] = ['label' => 'Eigene Nutzung / Sperre (A6)', 'profile' => $settings->resolve($property, null, IntakeKind::Internal)];
return ['property' => $property, 'columns' => $columns];
})->all();
}
/**
* @return list<ProcessSetting>
*/
public function settings(): array
{
return ProcessSetting::cases();
}
public function describe(ProcessSetting $setting, ProcessProfile $profile): string
{
$value = $profile->value($setting);
if ($setting === ProcessSetting::ContractTemplate) {
return $value === null ? 'Texte der Webseite' : (ContractTemplate::query()->find($value)?->label() ?? 'Vorlage Nr. '.$value);
}
return $setting->describe($value);
}
/**
* Where a setting is changed in the application.
*/
public static function where(ProcessSetting $setting): string
{
return $setting === ProcessSetting::ContractTemplate
? 'Wohnung › Abweichende Abwicklung (Experte) bzw. Portal › Anfragen / Feste Buchungen'
: 'System › So arbeite ich; Abweichung: Wohnung (Experte), Portal je Anfrage/feste Buchung'.($setting->channelIntakes() === [] ? ' (kein Portal)' : '');
}
/**
* Recent cases to check.
*
* @return array<int, string>
*/
public function cases(): array
{
return Booking::query()->with('guest')->latest('id')->limit(60)->get()
->mapWithKeys(fn (Booking $booking): array => [$booking->id => $booking->reference.' · '.$booking->guestName().' · '.$booking->caseType()->value])->all();
}
public function booking(): ?Booking
{
return $this->bookingId ? Booking::query()->find($this->bookingId) : null;
}
}
@@ -4,8 +4,10 @@
use App\Filament\Concerns\ListsCurrentProperty;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use Filament\Actions\CreateAction;
use App\Filament\Resources\Bookings\BookingResource;
use Filament\Actions\Action;
use Filament\Resources\Pages\ManageRecords;
use Filament\Support\Icons\Heroicon;
class ManageBlockedPeriods extends ManageRecords
{
@@ -16,7 +18,8 @@ class ManageBlockedPeriods extends ManageRecords
protected function getHeaderActions(): array
{
return [
CreateAction::make()->label('Zeitraum sperren')->mutateDataUsing(fn (array $data): array => [...$data, 'source' => 'manual']),
// New blocks are cases (A6) with their own page, history and portal tasks; this list keeps the old ones.
Action::make('createCase')->label('Zeitraum sperren')->icon(Heroicon::OutlinedPlus)->url(BookingResource::getUrl('create', ['kind' => 'block'])),
];
}
}
@@ -3,11 +3,12 @@
namespace App\Filament\Resources\Bookings\Pages;
use App\Actions\ConfirmBooking;
use App\Actions\CreateInternalCase;
use App\Actions\CreateReservation;
use App\Actions\SendBookingDocuments;
use App\Actions\TakeOverExternalBooking;
use App\Enums\InternalKind;
use App\Exceptions\ReservationException;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Models\Booking;
@@ -37,9 +38,8 @@ class CreateBooking extends CreateRecord
*/
protected function handleRecordCreation(array $data): Model
{
if (($data['kind'] ?? null) === BookingForm::OWN_USE) {
$this->redirect(BlockedPeriodResource::getUrl());
$this->halt();
if (in_array($data['kind'] ?? null, [BookingForm::OWN_USE, BookingForm::BLOCK], true)) {
return $this->createInternal($data);
}
try {
@@ -88,6 +88,58 @@ protected function handleRecordCreation(array $data): Model
return $booking;
}
/**
* Pre-filled from the calendar or the block list (?kind=block&von=…&bis=…&wohnung=…).
*/
protected function afterFill(): void
{
$kind = request()->query('kind');
if (in_array($kind, [BookingForm::INQUIRY, BookingForm::EXTERNAL, BookingForm::OWN_USE, BookingForm::BLOCK], true)) {
$this->data['kind'] = $kind;
}
foreach (['von' => 'arrival', 'bis' => 'departure'] as $parameter => $field) {
$value = request()->query($parameter);
if (is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) === 1) {
$this->data[$field] = $value;
}
}
if (is_numeric(request()->query('wohnung')) && Property::query()->whereKey((int) request()->query('wohnung'))->exists()) {
$this->data['property_id'] = (int) request()->query('wohnung');
}
}
/**
* Own use, a private stay or a block as a case (A6).
*
* @param array<string, mixed> $data
*/
private function createInternal(array $data): Model
{
$kind = $data['kind'] === BookingForm::BLOCK ? InternalKind::Block : InternalKind::from((string) ($data['internal_kind'] ?? InternalKind::OwnUse->value));
$extras = [];
foreach ((array) ($data['items'] ?? []) as $item) {
if (filled($item['extra_id'] ?? null)) {
$extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) ($item['quantity'] ?? 1));
}
}
try {
return app(CreateInternalCase::class)->handle(Property::query()->findOrFail($data['property_id']), $kind, CarbonImmutable::parse($data['arrival']), CarbonImmutable::parse($data['departure']), [
'occasion' => $data['occasion'] ?? null,
'guest' => ['first_name' => $data['stay_first_name'] ?? null, 'last_name' => $data['stay_last_name'] ?? null, 'email' => $data['stay_email'] ?? null, 'phone' => $data['stay_phone'] ?? null],
'guests' => $data['guests'] ?? null,
'extras' => $extras,
'rent' => (int) ($data['rent'] ?? 0),
'tourist_tax_persons' => filled($data['tourist_tax_persons'] ?? null) ? (int) $data['tourist_tax_persons'] : null,
'tourist_tax_note' => $data['tourist_tax_note'] ?? null,
'notes' => $data['internal_notes'] ?? null,
]);
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
$this->halt();
}
}
protected function getRedirectUrl(): string
{
/** @var Booking $record */
@@ -3,18 +3,27 @@
namespace App\Filament\Resources\Bookings\Pages;
use App\Actions\CancelBooking;
use App\Actions\ChangeBooking;
use App\Actions\ConfirmBooking;
use App\Actions\DeclineBooking;
use App\Actions\EndInternalCase;
use App\Actions\ProvideGuestContact;
use App\Actions\RecordPortalAmounts;
use App\Actions\SendBookingDocuments;
use App\Actions\SendOffer;
use App\Actions\SetBookingStatus;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\AdminMode;
use App\Enums\AmountKind;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Enums\ProcessingMode;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
@@ -23,18 +32,22 @@
use App\Filament\Forms\DocumentCompositionFields;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\Booking;
use App\Models\BookingChange;
use App\Models\BookingTask;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Models\Extra;
use App\Models\User;
use App\Pricing\PortalPrice;
use App\Pricing\PrivateStayPrice;
use App\Pricing\QuoteException;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Hidden;
@@ -50,6 +63,7 @@
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Components\View;
use Filament\Support\Icons\Heroicon;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr;
@@ -91,6 +105,9 @@ protected function getHeaderActions(): array
$this->sendDocumentsAction(),
$this->resendConfirmationAction(),
$this->portalPriceAction(),
$this->changeAction(),
$this->confirmPortalCancellationAction(),
$this->withdrawChangeAction(),
$this->extendHoldAction(),
$this->servicesAction(),
$this->offerPdfAction(),
@@ -191,7 +208,8 @@ private function sendDocumentsAction(): Action
return Action::make('sendDocuments')
->label(fn (): string => SendBookingDocuments::kindFor($this->record) === DocumentKind::ExternalRecord ? 'Buchungsunterlagen prüfen und senden' : 'Bestätigung prüfen und senden')
->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => $this->record->isBinding() && $this->record->confirmation_sent_at === null && $this->record->confirmation_failed_at === null && $this->record->process()->documents() === Responsibility::Landlord)
->visible(fn (): bool => $this->record->isBinding() && $this->record->confirmation_sent_at === null && $this->record->confirmation_failed_at === null
&& ($this->record->process()->documents() === Responsibility::Landlord || ($this->record->isInternal() && $this->record->internal_kind !== InternalKind::Block && filled($this->record->guest?->email))))
->modalHeading(fn (): string => SendBookingDocuments::kindFor($this->record)->getLabel())
->modalDescription('So gehen die Unterlagen an den Gast. „Anpassen“ nur bei Bedarf.')
->modalSubmitActionLabel('Senden')
@@ -239,7 +257,7 @@ private function provideContactAction(): Action
return Action::make('provideContact')
->label(fn (): string => $this->record->guest === null ? 'Gast eintragen' : 'Kontaktdaten eintragen')
->icon(Heroicon::OutlinedUserPlus)
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Kontaktdaten des Gastes')
->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Nur eintragen, was bekannt ist.')
->modalWidth('3xl')
@@ -286,7 +304,7 @@ private function requestContactAction(): Action
return Action::make('requestContact')
->label('Gast um Kontaktdaten bitten')
->icon(Heroicon::OutlinedChatBubbleLeftEllipsis)
->visible(fn (): bool => blank($this->record->guest?->email) && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->visible(fn (): bool => ! $this->record->isInternal() && blank($this->record->guest?->email) && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Gast um Kontaktdaten bitten')
->modalDescription('Den Text im Nachrichtenfenster des Portals einfügen (Sie senden ihn selbst). „Als angefragt vermerken“ hält fest, dass die Daten erfragt sind.')
->modalSubmitActionLabel('Als angefragt vermerken')
@@ -361,28 +379,204 @@ private function resendConfirmationAction(): Action
});
}
/**
* What the portal shows about the booking (package 8): the guest's total as the agreed price and – optional, folded
* away – its positions, commission, announced payouts, instalments and what the guest paid to the portal.
*/
private function portalPriceAction(): Action
{
return Action::make('portalPrice')
->label('Gesamtpreis laut Portal eintragen')
->label('Preis laut Portal eintragen')
->icon(Heroicon::OutlinedCurrencyEuro)
->visible(fn (): bool => $this->record->intake === IntakeKind::Booking && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined], true))
->modalDescription('Der Betrag, den der Gast beim Portal gebucht hat (Gesamtpreis). Er wird so übernommen und nicht in eigene Positionen zerlegt.')
->fillForm(fn (): array => ['portal_total' => $this->record->total, 'guests' => $this->record->guests])
->modalHeading(fn (): string => 'Beträge laut '.($this->record->processChannel()?->name ?? 'Portal'))
->modalDescription('Der Gesamtpreis, den der Gast beim Portal gebucht hat, wird so übernommen und nicht neu berechnet. Einzelheiten nur eintragen, wenn das Portal sie zeigt – nichts schätzen. Abweichende Angaben (z. B. zwei verschiedene Auszahlungsbeträge) einfach beide eintragen.')
->modalWidth('4xl')
->fillForm(fn (): array => ['portal_total' => $this->record->total, 'guests' => $this->record->guests, 'stated_on' => today()->toDateString(), 'amounts' => [], 'paid' => []])
->schema([
EuroInput::make('portal_total')->label('Gesamtpreis laut Portal')->required(),
TextInput::make('guests')->label('Personen (falls bekannt)')->integer()->minValue(1),
Section::make()->columns(3)->schema([
EuroInput::make('portal_total')->label('Gesamtpreis des Gastes laut Portal')->required(),
TextInput::make('guests')->label('Personen (falls bekannt)')->integer()->minValue(1),
DatePicker::make('stated_on')->label('Stand der Angaben')->required(),
]),
Section::make('Einzelheiten laut Portal (optional)')->collapsed()->schema([
Repeater::make('amounts')->label('Positionen und Angaben')->addActionLabel('Angabe hinzufügen')->columns(4)->defaultItems(0)->schema([
Select::make('kind')->label('Art')->options(AmountKind::class)->required()->columnSpan(2),
TextInput::make('label')->label('Bezeichnung laut Portal')->placeholder('z. B. Gebühren und Steuern')->maxLength(150),
EuroInput::make('amount')->label('Betrag')->minValue(null)->required(),
DatePicker::make('due_on')->label('fällig am (bei Raten)'),
TextInput::make('note')->label('Notiz')->maxLength(500)->columnSpan(3),
]),
Repeater::make('paid')->label('Vom Gast laut Portal bereits bezahlt')->addActionLabel('Zahlung laut Portal hinzufügen')->columns(2)->defaultItems(0)->schema([
EuroInput::make('amount')->label('Betrag')->required(),
DatePicker::make('paid_on')->label('bezahlt am')->required(),
]),
]),
])
->action(function (array $data, PortalPrice $price): void {
$guests = filled($data['guests'] ?? null) ? (int) $data['guests'] : $this->record->guests;
$this->record->update(['guests' => $guests, ...$price->columns($this->record->property, $this->record->arrival, $this->record->departure, $guests, (int) $data['portal_total'], $this->record->processChannel()?->name)]);
CaseLog::record($this->record, 'price', 'Gesamtpreis laut Portal eingetragen: '.Money::format((int) $data['portal_total']));
$blockers = app(CaseAutomation::class)->advance($this->record->fresh());
->action(function (array $data, RecordPortalAmounts $amounts): void {
if (filled($data['guests'] ?? null)) {
$this->record->update(['guests' => (int) $data['guests']]);
}
$amounts->handle(
$this->record->fresh(),
(int) $data['portal_total'],
array_map(fn (array $row): array => [...$row, 'amount' => (int) $row['amount']], array_values((array) ($data['amounts'] ?? []))),
array_map(fn (array $row): array => ['amount' => (int) $row['amount'], 'paid_on' => (string) $row['paid_on']], array_values((array) ($data['paid'] ?? []))),
$this->record->processChannel()?->name ?? 'Portal',
CarbonImmutable::parse($data['stated_on']),
auth()->user()?->name,
);
$this->record->refresh();
Notification::make()->title('Preis gespeichert')->body($blockers === [] ? null : implode(' ', $blockers))->success()->send();
$blockers = app(CaseAutomation::class)->documentBlockers($this->record);
Notification::make()->title('Beträge gespeichert')->body($blockers === [] ? null : implode(' ', $blockers))->success()->send();
});
}
/**
* "Ändern" of a booking or internal case (package 5): dates, guests, services and price with the consequences shown
* before saving; either recorded as already agreed with the guest, or proposed to the guest for consent.
*/
private function changeAction(): Action
{
$own = fn (): bool => ! $this->record->isInternal() && ! $this->record->caseType()->isExternallyBinding();
return Action::make('change')
->label(fn (): string => $this->record->isInternal() ? 'Ändern oder verlängern …' : 'Buchung ändern …')
->icon(Heroicon::OutlinedPencil)
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true) && $this->record->portal_cancellation_requested_at === null)
->modalHeading(fn (): string => $this->record->isInternal() ? 'Zeitraum oder Angaben ändern' : 'Buchung ändern')
->modalDescription('Tragen Sie ein, was sich ändert. Unten sehen Sie vor dem Speichern, was daraus folgt.')
->modalSubmitActionLabel('Speichern')
->modalWidth('4xl')
->fillForm(fn (): array => [
'arrival' => $this->record->arrival->toDateString(),
'departure' => $this->record->departure->toDateString(),
'guests' => $this->record->guests,
'items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all(),
'rent' => $this->record->isInternal() ? PrivateStayPrice::rentOf($this->record->quote) : null,
'tourist_tax_persons' => $this->record->tourist_tax_persons,
'way' => 'agreed',
'requested_by' => $this->record->caseType()->isExternallyBinding() ? 'portal' : 'guest',
'basis' => $this->record->caseType()->isExternallyBinding() ? ChangeBasis::Portal->value : ChangeBasis::Phone->value,
'agreed_at' => now()->format('Y-m-d H:i'),
'effective_on' => today()->toDateString(),
'send_confirmation' => false,
])
->schema(fn (): array => [
Section::make()->columns(3)->schema([
DatePicker::make('arrival')->label('Anreise / Beginn')->required()->live(onBlur: true),
DatePicker::make('departure')->label('Abreise / Ende')->after('arrival')->required()->live(onBlur: true),
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->live(onBlur: true)->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block),
]),
Repeater::make('items')->label('Zusatzleistungen')->columns(2)->defaultItems(0)->addActionLabel('Leistung hinzufügen')->live()
->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! $this->record->caseType()->isExternallyBinding())
->schema([
Select::make('extra_id')->label('Leistung')->options(fn (): array => Extra::query()->where('property_id', $this->record->property_id)->orderBy('name')->pluck('name', 'id')->all())->required(),
TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(),
]),
Section::make('Preis')->columns(2)->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block)->schema([
EuroInput::make('portal_total')->label('Neuer Gesamtpreis laut Portal')->helperText('Leer lassen, wenn das Portal den Preis nicht geändert hat.')->live(onBlur: true)
->visible(fn (): bool => $this->record->caseType()->isExternallyBinding()),
EuroInput::make('agreed_total')->label('Vereinbarter Gesamtpreis (optional)')->helperText('Leer lassen: Der Preis wird aus Ihren Preisen neu berechnet.')->live(onBlur: true)
->visible($own),
EuroInput::make('rent')->label('Vereinbarte Miete')->live(onBlur: true)->visible(fn (): bool => $this->record->isInternal()),
TextInput::make('tourist_tax_persons')->label('Kurabgabe: Personen')->integer()->minValue(0)->live(onBlur: true)->visible(fn (): bool => $this->record->isInternal()),
]),
View::make('filament.change-preview')->viewData(fn (Get $get): array => ['preview' => app(ChangeBooking::class)->preview($this->record, $this->changeData(self::formState($get, ['arrival', 'departure', 'guests', 'items', 'portal_total', 'agreed_total', 'rent', 'tourist_tax_persons'])))]),
Section::make('Grundlage')->columns(2)->visible(fn (): bool => ! $this->record->isInternal())->schema([
Radio::make('way')->label('Wie kommt die Änderung zustande?')->columnSpanFull()->live()->required()->options(fn (): array => array_filter([
'agreed' => 'Mit dem Gast bereits vereinbart – jetzt eintragen',
'propose' => $own() && filled($this->record->guest?->email) ? 'Dem Gast vorschlagen – wird erst mit seiner Zustimmung wirksam' : null,
])),
Select::make('requested_by')->label('Wer möchte die Änderung?')->options(BookingChange::REQUESTERS)->required(),
Select::make('basis')->label('Wie vereinbart?')->options(collect(ChangeBasis::cases())->reject(fn (ChangeBasis $basis): bool => in_array($basis, [ChangeBasis::GuestLink, ChangeBasis::NotNeeded], true))->mapWithKeys(fn (ChangeBasis $basis): array => [$basis->value => $basis->getLabel()])->all())
->visible(fn (Get $get): bool => $get('way') === 'agreed')->required(fn (Get $get): bool => $get('way') === 'agreed'),
DateTimePicker::make('agreed_at')->label('Vereinbart am')->seconds(false)->visible(fn (Get $get): bool => $get('way') === 'agreed'),
DatePicker::make('effective_on')->label('Wirksam ab'),
Toggle::make('send_confirmation')->label('Bestätigung der Änderung an den Gast senden')->visible(fn (Get $get): bool => $get('way') === 'agreed' && filled($this->record->guest?->email)),
]),
Textarea::make('reason')->label('Grund')->required()->rows(2),
])
->action(function (array $data, ChangeBooking $changes): void {
$meta = [
'requested_by' => $this->record->isInternal() ? 'landlord' : ($data['requested_by'] ?? 'landlord'),
'reason' => (string) $data['reason'],
'basis' => $this->record->isInternal() ? ChangeBasis::NotNeeded : ChangeBasis::from((string) ($data['basis'] ?? ChangeBasis::Phone->value)),
'agreed_at' => $data['agreed_at'] ?? null,
'effective_on' => $data['effective_on'] ?? null,
'send_confirmation' => (bool) ($data['send_confirmation'] ?? false),
];
$this->runWorkflow(fn () => ($data['way'] ?? 'agreed') === 'propose' && ! $this->record->isInternal()
? $changes->propose($this->record, $this->changeData($data), $meta, auth()->user()?->name)
: $changes->apply($this->record, $this->changeData($data), $meta, auth()->user()?->name), ($data['way'] ?? 'agreed') === 'propose' ? 'Vorschlag an den Gast gesendet' : 'Änderung gespeichert');
});
}
/**
* A booking binding on a portal is only cancelled here once the cancellation is effective on the portal.
*/
private function confirmPortalCancellationAction(): Action
{
$reported = fn (): bool => BookingTask::query()->where('booking_id', $this->record->id)->where('kind', BookingTaskKind::PortalCancellationReported)->where('status', BookingTaskStatus::Open)->exists();
return Action::make('confirmPortalCancellation')
->label(fn (): string => $reported() ? 'Stornierung übernehmen …' : 'Stornierung bestätigen …')
->icon(Heroicon::OutlinedCheckBadge)
->color('danger')
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true) && $this->record->caseType()->isExternallyBinding()
&& ($this->record->portal_cancellation_requested_at !== null || $reported()))
->modalHeading('Ist die Stornierung im Portal wirksam?')
->modalDescription(fn (): string => 'Erst jetzt wird der Vorgang storniert und der Zeitraum frei. Bitte vorher im Portal „'.($this->record->processChannel()?->name ?? 'Portal').'“ nachsehen. Bleibt die Buchung im Portal bestehen, die Aufgabe einfach im Reiter „Aufgaben“ erledigen.')
->modalSubmitActionLabel('Storniert – übernehmen')
->fillForm(fn (): array => ['initiated_by' => $reported() ? 'portal' : 'landlord'])
->schema([
Radio::make('initiated_by')->label('Wer hat storniert?')->options(CancelBooking::INITIATORS)->required(),
Textarea::make('reason')->label('Grund / Hinweis')->rows(2),
Checkbox::make('effective')->label('Die Stornierung ist im Portal wirksam (geprüft).')->accepted(),
])
->action(fn (array $data, CancelBooking $cancel) => $this->runWorkflow(fn () => $cancel->confirmOnPortal($this->record, (string) auth()->user()?->name, $data['initiated_by'], $data['reason'] ?? null), 'Buchung storniert'));
}
private function withdrawChangeAction(): Action
{
return Action::make('withdrawChange')
->label('Änderungsvorschlag zurückziehen')
->icon(Heroicon::OutlinedArrowUturnLeft)
->visible(fn (): bool => $this->record->changes()->where('status', ChangeStatus::Proposed)->exists())
->requiresConfirmation()
->action(function (ChangeBooking $changes): void {
$changes->withdraw($this->record->changes()->where('status', ChangeStatus::Proposed)->firstOrFail(), auth()->user()?->name);
Notification::make()->title('Vorschlag zurückgezogen')->success()->send();
});
}
/**
* Form data of the change dialog as changes for {@see ChangeBooking}.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function changeData(array $data): array
{
$extras = [];
foreach ((array) ($data['items'] ?? []) as $item) {
if (filled($item['extra_id'] ?? null)) {
$extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) ($item['quantity'] ?? 1));
}
}
return array_filter([
'arrival' => $data['arrival'] ?? null,
'departure' => $data['departure'] ?? null,
'guests' => filled($data['guests'] ?? null) ? (int) $data['guests'] : null,
'extras' => $this->record->internal_kind === InternalKind::Block || $this->record->caseType()->isExternallyBinding() ? null : $extras,
'portal_total' => filled($data['portal_total'] ?? null) ? (int) $data['portal_total'] : null,
'agreed_total' => filled($data['agreed_total'] ?? null) ? (int) $data['agreed_total'] : null,
'rent' => $this->record->isInternal() && filled($data['rent'] ?? null) ? (int) $data['rent'] : null,
'tourist_tax_persons' => $this->record->isInternal() && filled($data['tourist_tax_persons'] ?? null) ? (int) $data['tourist_tax_persons'] : null,
], fn ($value): bool => $value !== null);
}
private function extendHoldAction(): Action
{
return Action::make('extendHold')
@@ -402,7 +596,7 @@ private function servicesAction(): Action
return Action::make('services')
->label('Zusatzleistungen erfassen')
->icon(Heroicon::OutlinedPlusCircle)
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true))
->visible(fn (): bool => ! $this->record->isInternal() && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true))
->modalDescription('Gebuchte Zusatzleistungen (z. B. aus einer Portalbuchung). Sie bestimmen, welche Vertragsanlagen angehängt werden. Der Preis ändert sich dadurch nicht.')
->fillForm(fn (): array => ['items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all()])
->schema([
@@ -525,7 +719,8 @@ private function setStatusAction(): Action
*/
private function automationAction(): ?Action
{
if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
// Own use, private stays and blocks have nothing that could run by itself.
if ($this->record->isInternal() || in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
return null;
}
@@ -554,11 +749,28 @@ private function automationAction(): ?Action
*/
private function endAction(): ?Action
{
if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)
|| $this->record->portal_cancellation_requested_at !== null) {
return null;
}
if ($this->record->isInternal()) {
$label = EndInternalCase::label($this->record);
return Action::make('end')
->label($this->record->internal_kind === InternalKind::Block ? 'Sperre aufheben …' : 'Aufenthalt absagen …')
->icon(Heroicon::OutlinedStopCircle)
->color('danger')
->outlined()
->modalHeading($label)
->modalDescription('Keine Stornierung: Es entstehen keine Kosten und keine Mails. Der Zeitraum wird frei, die Portale werden wieder freigegeben.')
->modalSubmitActionLabel($this->record->internal_kind === InternalKind::Block ? 'Aufheben' : 'Absagen')
->schema([Textarea::make('reason')->label('Grund')->required()->rows(2)])
->action(fn (array $data, EndInternalCase $end) => $this->runWorkflow(fn () => $end->handle($this->record, trim((string) $data['reason']), auth()->user()?->name), $label));
}
$binding = $this->record->isBinding();
$external = $binding && $this->record->caseType()->isExternallyBinding();
$hasEmail = filled($this->record->guest?->email);
return Action::make('end')
@@ -567,22 +779,25 @@ private function endAction(): ?Action
->color('danger')
->outlined()
->modalHeading($binding ? 'Gebuchten Vorgang stornieren' : 'Vorgang ohne Buchung beenden')
->modalDescription($binding
? 'Die Buchung ist verbindlich. Sie wird storniert, der Zeitraum frei. Stornokosten nach der vereinbarten Regel bleiben als Aufgabe offen.'.($this->record->caseType()->isExternallyBinding() ? ' Gebucht wurde beim Portal – dafür entsteht zusätzlich die Aufgabe, die Stornierung dort zu veranlassen bzw. zu prüfen.' : '')
: 'Es ist noch keine verbindliche Buchung zustande gekommen. Der reservierte Zeitraum wird wieder frei.')
->modalSubmitActionLabel($binding ? 'Stornieren' : 'Beenden')
->modalDescription(match (true) {
$external => 'Gebucht wurde beim Portal „'.($this->record->processChannel()?->name ?? 'Portal').'“ – storniert wird dort. Hier entsteht die Aufgabe, die Stornierung im Portal zu veranlassen; der Vorgang bleibt gebucht, bis Sie bestätigen, dass sie dort wirksam ist. Nichts wird still gelöscht.',
$binding => 'Die Buchung ist verbindlich. Sie wird storniert, der Zeitraum frei. Stornokosten nach der vereinbarten Regel und eine mögliche Erstattung bleiben als Aufgaben offen.',
default => 'Es ist noch keine verbindliche Buchung zustande gekommen. Der reservierte Zeitraum wird wieder frei.',
})
->modalSubmitActionLabel($external ? 'Stornierung veranlassen' : ($binding ? 'Stornieren' : 'Beenden'))
->schema(array_values(array_filter([
$binding ? Radio::make('initiated_by')->label('Wer storniert?')->options(['guest' => 'Der Gast', 'landlord' => 'Wir (Vermieter)'])->required() : null,
$binding ? Radio::make('initiated_by')->label('Wer storniert?')->options($external ? CancelBooking::INITIATORS : ['guest' => 'Der Gast', 'landlord' => 'Wir (Vermieter)'])->required() : null,
Textarea::make('reason')->label('Grund')->required()->rows(2),
Toggle::make('notify')->label('Den Gast per E-Mail informieren')->default($hasEmail)->disabled(! $hasEmail),
$binding ? Toggle::make('costs_task')->label('Aufgabe „Stornokosten prüfen“ anlegen')->default(true) : null,
$external ? null : Toggle::make('notify')->label('Den Gast per E-Mail informieren')->default($hasEmail)->disabled(! $hasEmail),
$binding && ! $external ? Toggle::make('costs_task')->label('Aufgabe „Stornokosten prüfen“ anlegen')->default(true) : null,
])))
->action(function (array $data, CancelBooking $cancel, DeclineBooking $decline) use ($binding, $hasEmail): void {
$notify = $hasEmail && (bool) ($data['notify'] ?? false);
->action(function (array $data, CancelBooking $cancel, DeclineBooking $decline) use ($binding, $external, $hasEmail): void {
$notify = ! $external && $hasEmail && (bool) ($data['notify'] ?? false);
$reason = trim((string) $data['reason']);
try {
$informed = CaseLog::context(fn () => $binding
? $cancel->handle($this->record, $notify, (bool) ($data['costs_task'] ?? true), auth()->user()->name, $data['initiated_by'])
: $decline->handle($this->record, $notify), reason: trim((string) $data['reason']));
? $cancel->handle($this->record, $notify, (bool) ($data['costs_task'] ?? true), auth()->user()->name, $data['initiated_by'], $reason)
: $decline->handle($this->record, $notify), reason: $reason);
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
@@ -590,7 +805,11 @@ private function endAction(): ?Action
}
$this->record->refresh();
$notification = Notification::make()->title($binding ? 'Buchung storniert' : 'Vorgang beendet');
$notification = Notification::make()->title(match (true) {
$external => 'Stornierung im Portal veranlassen',
$binding => 'Buchung storniert',
default => 'Vorgang beendet',
});
($informed === false ? $notification->warning()->body('Die Mail an den Gast konnte nicht gesendet werden – bitte selbst informieren.') : $notification->success())->send();
});
}
@@ -3,15 +3,19 @@
namespace App\Filament\Resources\Bookings\RelationManagers;
use App\Actions\RecordPayment;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod;
use App\Enums\Responsibility;
use App\Filament\Forms\Components\EuroInput;
use App\Models\Booking;
use App\Models\Payment;
use App\Pricing\CaseMoney;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
@@ -38,11 +42,13 @@ public function table(Table $table): Table
{
return $table
->recordTitleAttribute('amount')
->description(fn (): string => 'Bezahlt: '.Money::format($this->ownerRecord->paidAmount()).' · offen: '.Money::format($this->ownerRecord->openAmount()))
->description(fn (): string => 'Vom Gast bezahlt: '.Money::format($this->ownerRecord->paidAmount()).' (davon an uns '.Money::format($this->ownerRecord->paidToUs()).', laut Portal ans Portal '.Money::format($this->ownerRecord->paidViaPortal()).') · Auszahlungen vom Portal: '.Money::format($this->ownerRecord->payoutsReceived()).' · offen bei uns: '.Money::format(CaseMoney::of($this->ownerRecord)->openForUs()))
->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('kind')->label('Was')->badge()->state(fn (Payment $record): PaymentKind => $record->kind ?? PaymentKind::Guest),
TextColumn::make('method')->label('Zahlweg'),
TextColumn::make('source')->label('Quelle')->placeholder('–')->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('note')->label('Notiz')->placeholder('–'),
TextColumn::make('recorded_by')->label('Erfasst von')->placeholder('–'),
])
@@ -54,9 +60,11 @@ public function table(Table $table): Table
'amount' => number_format(($this->ownerRecord->openDeposit() ?: $this->ownerRecord->openAmount()) / 100, 2, '.', ''),
'paid_on' => today(),
'method' => PaymentMethod::Transfer,
'kind' => $this->ownerRecord->process()->payments() === Responsibility::Portal ? PaymentKind::PortalPayout->value : PaymentKind::Guest->value,
])
->schema([
EuroInput::make('amount')->label('Betrag')->helperText('Erstattungen mit Minus erfassen.')->minValue(null)->required(),
Radio::make('kind')->label('Was ist passiert?')->options(PaymentKind::class)->required(),
EuroInput::make('amount')->label('Betrag')->helperText('Immer den Betrag ohne Vorzeichen; eine Erstattung wird automatisch abgezogen.')->required(),
DatePicker::make('paid_on')->label('Zahlungseingang')->required(),
Select::make('method')->label('Art')->options(PaymentMethod::class)->required(),
TextInput::make('note')->label('Notiz')->maxLength(255),
@@ -69,6 +77,8 @@ public function table(Table $table): Table
$data['method'] instanceof PaymentMethod ? $data['method'] : PaymentMethod::from($data['method']),
$data['note'] ?: null,
auth()->user()?->name,
$data['kind'] instanceof PaymentKind ? $data['kind'] : PaymentKind::from($data['kind']),
in_array($data['kind'] instanceof PaymentKind ? $data['kind']->value : $data['kind'], [PaymentKind::GuestViaPortal->value, PaymentKind::PortalPayout->value], true) ? ($this->ownerRecord->processChannel()?->name ?? 'Portal') : null,
);
Notification::make()->title('Zahlung erfasst – Status: '.$this->ownerRecord->fresh()->status->getLabel())->success()->send();
@@ -2,22 +2,23 @@
namespace App\Filament\Resources\Bookings\Schemas;
use App\Enums\InternalKind;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Models\Channel;
use App\Models\Extra;
use App\Models\Property;
use App\Support\CurrentProperty;
use App\Support\Money;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Illuminate\Support\HtmlString;
/**
* "Neu": one entry for everything that arrives outside the website. The first question is what it is – a request,
@@ -32,10 +33,14 @@ class BookingForm
public const OWN_USE = 'own_use';
public const BLOCK = 'block';
public static function configure(Schema $schema): Schema
{
$is = fn (string $kind): \Closure => fn (Get $get): bool => $get('kind') === $kind;
$isCase = fn (Get $get): bool => in_array($get('kind'), [self::INQUIRY, self::EXTERNAL], true);
$isInternal = fn (Get $get): bool => in_array($get('kind'), [self::OWN_USE, self::BLOCK], true);
$hasGuests = fn (Get $get): bool => $get('kind') === self::OWN_USE && $get('internal_kind') === InternalKind::PrivateStay->value;
return $schema
->components([
@@ -46,17 +51,25 @@ public static function configure(Schema $schema): Schema
->options([
self::INQUIRY => 'Eine Anfrage – per Telefon, E-Mail oder Nachricht über ein Portal',
self::EXTERNAL => 'Eine Buchung, die bei einem Portal schon fest gebucht ist',
self::OWN_USE => 'Eigene Nutzung oder eine Sperre (z. B. Wartung)',
self::OWN_USE => 'Eigene Nutzung oder Besuch von Familie und Freunden',
self::BLOCK => 'Eine Sperre ohne Gäste (z. B. Wartung, Renovierung)',
])
->default(self::INQUIRY)
->required()
->live(),
Text::make(new HtmlString('Eigene Nutzung und Sperren tragen Sie bis auf Weiteres unter <a class="underline" href="'.e(BlockedPeriodResource::getUrl()).'">Sperrzeiten</a> ein.'))
->visible($is(self::OWN_USE)),
Radio::make('internal_kind')
->label('Wer wohnt in der Wohnung?')
->options([InternalKind::OwnUse->value => 'Wir selbst (eigene Nutzung)', InternalKind::PrivateStay->value => 'Familie oder Freunde (private Überlassung, ohne Mietvertrag)'])
->default(InternalKind::OwnUse->value)
->visible($is(self::OWN_USE))
->live(),
TextInput::make('occasion')->label(fn (Get $get): string => $get('kind') === self::BLOCK ? 'Grund der Sperre' : 'Anlass')
->placeholder(fn (Get $get): string => $get('kind') === self::BLOCK ? 'z. B. Malerarbeiten im Bad' : 'z. B. Besuch von Tochter Anna')
->maxLength(255)->required($is(self::BLOCK))->visible($isInternal),
]),
Section::make('Zeitraum')
->columns(2)
->visible($isCase)
->visible(fn (Get $get): bool => $isCase($get) || $isInternal($get))
->schema([
Select::make('property_id')
->label('Wohnung')
@@ -69,9 +82,36 @@ public static function configure(Schema $schema): Schema
->integer()
->minValue(1)
->helperText(fn (Get $get): ?string => $get('kind') === self::EXTERNAL ? 'Leer lassen, wenn nicht bekannt.' : null)
->visible(fn (Get $get): bool => $get('kind') !== self::BLOCK)
->live(onBlur: true)
->required($is(self::INQUIRY)),
DatePicker::make('arrival')->label('Anreise')->required(),
DatePicker::make('departure')->label('Abreise')->after('arrival')->required(),
DatePicker::make('arrival')->label(fn (Get $get): string => $isInternal($get) ? 'Beginn' : 'Anreise')->required(),
DatePicker::make('departure')->label(fn (Get $get): string => $isInternal($get) ? 'Ende (erster freier Tag)' : 'Abreise')->after('arrival')->required(),
]),
Section::make('Gäste')
->description('Nur eintragen, was Sie brauchen – z. B. für eine Aufenthaltsbestätigung.')
->columns(2)
->visible($hasGuests)
->schema([
TextInput::make('stay_first_name')->label('Vorname')->maxLength(255),
TextInput::make('stay_last_name')->label('Nachname')->maxLength(255),
TextInput::make('stay_email')->label('E-Mail (für eine Bestätigung)')->email()->maxLength(255),
TextInput::make('stay_phone')->label('Telefon')->tel()->maxLength(50),
]),
Section::make('Leistungen und Kosten (optional)')
->description('Miete ist bei Familie meist 0 €. Zahlungen lassen sich später erfassen; es gibt keine Zahlungserinnerungen.')
->columns(2)
->visible($is(self::OWN_USE))
->collapsed(fn (Get $get): bool => $get('internal_kind') !== InternalKind::PrivateStay->value)
->schema([
EuroInput::make('rent')->label('Vereinbarte Miete')->default(0),
TextInput::make('tourist_tax_persons')->label('Kurabgabe: Personen')->integer()->minValue(0)
->helperText(fn (Get $get): string => ($rate = Property::query()->find($get('property_id'))?->tourist_tax_rate) ? 'Satz je Person und Nacht: '.Money::format((int) $rate).' (Wohnung › Kurabgabe)' : 'Kein Satz hinterlegt (Wohnung › Kurabgabe) – es wird nichts berechnet.'),
TextInput::make('tourist_tax_note')->label('Befreiungen / Hinweis zur Kurabgabe')->maxLength(255)->columnSpanFull(),
Repeater::make('items')->label('Zusatzleistungen')->columns(2)->defaultItems(0)->addActionLabel('Leistung hinzufügen')->columnSpanFull()->schema([
Select::make('extra_id')->label('Leistung')->options(fn (Get $get): array => Extra::query()->where('property_id', $get('../../property_id'))->orderBy('name')->pluck('name', 'id')->all())->required(),
TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(),
]),
]),
Section::make('Portal')
->columns(2)
@@ -113,7 +153,7 @@ public static function configure(Schema $schema): Schema
TextInput::make('promo_code')->label('Aktionscode')->maxLength(50),
]),
Section::make('Notiz')
->visible($isCase)
->visible(fn (Get $get): bool => $isCase($get) || $isInternal($get))
->collapsed()
->schema([
Textarea::make('internal_notes')->hiddenLabel()->placeholder('Interne Notiz (nur für Sie sichtbar)'),
@@ -13,6 +13,7 @@
use App\Models\Booking;
use App\Models\IntakeObservation;
use App\Models\User;
use App\Pricing\CaseMoney;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\ProcessProfile;
@@ -66,14 +67,10 @@ public static function configure(Schema $schema): Schema
TextEntry::make('label'),
TextEntry::make('amount')->formatStateUsing(fn (int $state): string => Money::format($state))->alignEnd(),
]),
Grid::make(4)->visible(fn (Booking $record): bool => $record->total !== null)->schema([
TextEntry::make('total')->label('Gesamtpreis')->money('EUR', divideBy: 100, locale: 'de')->weight('bold'),
TextEntry::make('paid')->label('Bezahlt')->state(fn (Booking $record): string => Money::format($record->paidAmount())),
TextEntry::make('open')->label('Offen')
->state(fn (Booking $record): string => $record->process()->payments() === Responsibility::Portal ? 'über das Portal' : Money::format($record->openAmount()))
->color(fn (Booking $record): string => $record->process()->payments() === Responsibility::Landlord && $record->openAmount() > 0 ? 'danger' : 'success'),
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y')->placeholder('–'),
]),
TextEntry::make('money')->hiddenLabel()->html()
->state(fn (Booking $record): HtmlString => new HtmlString(view('filament.case-money', ['money' => CaseMoney::of($record), 'booking' => $record])->render())),
TextEntry::make('balance_due_on')->label('Restzahlung fällig am')->date('d.m.Y')
->visible(fn (Booking $record): bool => $record->wantsPaymentTasks() && $record->balance_due_on !== null),
]),
Section::make('Verlauf')
->collapsible()
@@ -107,7 +104,7 @@ public static function configure(Schema $schema): Schema
->schema([
TextEntry::make('documents')->hiddenLabel()->html()->state(fn (Booking $record): HtmlString => self::documents($record)),
TextEntry::make('document_kind')->label('Vorgesehen')->state(fn (Booking $record): string => DocumentKind::forCase($record)?->getLabel() ?? 'Unterlagen schickt das Portal'),
TextEntry::make('template')->label('Vorlage')->state(fn (Booking $record): string => isset($record->offer_terms['template']) && ($record->contract_path !== null || $record->offer_path !== null)
TextEntry::make('template')->label('Vorlage')->visible(fn (Booking $record): bool => ! $record->isInternal())->state(fn (Booking $record): string => isset($record->offer_terms['template']) && ($record->contract_path !== null || $record->offer_path !== null)
? $record->offer_terms['template']['name'].' (Version '.$record->offer_terms['template']['version'].', festgeschrieben)'
: (OfferTerms::templateFor($record)?->label() ?? 'Texte der Webseite').' (vorgesehen)'),
]),
@@ -95,6 +95,9 @@ public static function configure(Schema $schema): Schema
->label('Endreinigung & Service (einmalig)')
->required()
->default(0),
EuroInput::make('tourist_tax_rate')
->label('Kurabgabe je Person und Nacht')
->helperText('Ihr Satz laut Gemeinde. Wird bei eigener Nutzung und privaten Aufenthalten als eigene Position berechnet; Befreiungen tragen Sie im Vorgang ein. Leer lassen: keine Berechnung.'),
]),
Section::make('Zahlungsbedingungen')
->columns(2)
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers;
use App\Actions\ChangeBooking;
use App\Enums\ChangeStatus;
use App\Exceptions\ReservationException;
use App\Mail\ChangeAnswered;
use App\Models\BookingChange;
use App\Support\Settings;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
/**
* The guest's page for a proposed change of a booking (signed link): see it, accept it or decline it. Only the acceptance
* here makes the change binding; it is recorded with time and (hashed) address.
*/
class ChangeController extends Controller
{
public function show(BookingChange $change): View
{
return view('change', ['change' => $change, 'booking' => $change->booking]);
}
public function accept(Request $request, BookingChange $change, ChangeBooking $changes): RedirectResponse
{
$request->validate(['agree' => ['accepted']], ['agree.accepted' => 'Bitte bestätigen Sie, dass Sie mit der Änderung einverstanden sind.']);
try {
$changes->accept($change, $request->ip());
} catch (ReservationException $exception) {
return back()->with('change.error', $exception->getMessage());
}
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChangeAnswered($change->fresh(), accepted: true)));
return back()->with('change.success', 'Vielen Dank – die Änderung ist jetzt verbindlich.');
}
public function decline(BookingChange $change, ChangeBooking $changes): RedirectResponse
{
if ($change->status === ChangeStatus::Proposed) {
$changes->decline($change, request()->ip());
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChangeAnswered($change->fresh(), accepted: false)));
}
return back()->with('change.success', 'Sie haben die Änderung abgelehnt. Ihre Buchung bleibt unverändert.');
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use App\Models\BookingChange;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Confirms a change that was already agreed with the guest – information about what now applies, not a request for
* consent (package 5).
*/
class BookingChanged extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking, public BookingChange $change) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Änderung Ihrer Buchung '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.booking-changed');
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Mail;
use App\Models\BookingChange;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Tells the landlord how the guest answered a proposed change.
*/
class ChangeAnswered extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public BookingChange $change, public bool $accepted) {}
public function envelope(): Envelope
{
return new Envelope(subject: ($this->accepted ? 'Änderung angenommen: ' : 'Änderung abgelehnt: ').$this->change->booking->reference);
}
public function content(): Content
{
return new Content(markdown: 'mail.change-answered');
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use App\Models\BookingChange;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Proposes a change to the guest: nothing has changed yet; the guest accepts or declines through the signed link
* (package 5). Only the guest's acceptance makes it binding.
*/
class ChangeProposed extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking, public BookingChange $change, public string $url) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Vorschlag zur Änderung Ihrer Buchung '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.change-proposed');
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
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;
/**
* The confirmation of a private stay (A6, on request): the stay, no rental contract (package 6).
*/
class StayConfirmed extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Bestätigung Ihres Aufenthalts '.$this->booking->reference,
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.stay-confirmed');
}
/**
* @return list<Attachment>
*/
public function attachments(): array
{
$path = app(RentalContract::class)->absolutePath($this->booking);
return $path ? [Attachment::fromPath($path)->as("Aufenthaltsbestaetigung-{$this->booking->reference}.pdf")->withMime('application/pdf')] : [];
}
}
+80 -3
View File
@@ -7,6 +7,8 @@
use App\Enums\BookingTaskKind;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Enums\PaymentKind;
use App\Enums\ProcessingMode;
use App\Enums\ReferralSource;
use App\Enums\Responsibility;
@@ -91,13 +93,19 @@
'balance_requested_at',
'balance_reminded_at',
'arrival_info_sent_at',
'internal_kind',
'occasion',
'tourist_tax_persons',
'tourist_tax_note',
'portal_cancellation_requested_at',
'export_uid',
])]
class Booking extends Model
{
/** @use HasFactory<BookingFactory> */
use BelongsToTenant, HasChannelProvenance, HasFactory;
public const DIRECT_SOURCES = ['website', 'manual', 'phone', 'direct', 'email'];
public const DIRECT_SOURCES = ['website', 'manual', 'phone', 'direct', 'email', 'internal'];
public function isDirect(): bool
{
@@ -177,6 +185,8 @@ protected function casts(): array
'contact_requested_at' => 'immutable_datetime',
'guest_confirmed_at' => 'immutable_datetime',
'archived_at' => 'immutable_datetime',
'internal_kind' => InternalKind::class,
'portal_cancellation_requested_at' => 'immutable_datetime',
];
}
@@ -267,6 +277,7 @@ public function bookingChannelLabel(): string
'phone' => 'Telefon',
'email' => 'E-Mail',
'direct' => 'Direkt',
'internal' => 'Eigene Belegung',
default => $this->source,
};
}
@@ -336,7 +347,73 @@ public function payments(): HasMany
*/
public function paidAmount(): int
{
return (int) ($this->relationLoaded('payments') ? $this->payments->sum('amount') : $this->payments()->sum('amount'));
return $this->sumOfPayments([PaymentKind::Guest, PaymentKind::GuestViaPortal, PaymentKind::Refund]);
}
/**
* What the guest paid us directly, less refunds (money on our account from the guest).
*/
public function paidToUs(): int
{
return $this->sumOfPayments([PaymentKind::Guest, PaymentKind::Refund]);
}
/**
* What the guest paid to the portal according to the portal (no money on our account).
*/
public function paidViaPortal(): int
{
return $this->sumOfPayments([PaymentKind::GuestViaPortal]);
}
/**
* What the portal paid out to us.
*/
public function payoutsReceived(): int
{
return $this->sumOfPayments([PaymentKind::PortalPayout]);
}
/**
* @param list<PaymentKind> $kinds
*/
private function sumOfPayments(array $kinds): int
{
$payments = $this->relationLoaded('payments') ? $this->payments : $this->payments()->get();
return (int) $payments->filter(fn (Payment $payment): bool => in_array($payment->kind ?? PaymentKind::Guest, $kinds, true))->sum('amount');
}
/**
* @return HasOne<Cancellation, $this>
*/
public function cancellation(): HasOne
{
return $this->hasOne(Cancellation::class);
}
/**
* @return HasMany<CaseAmount, $this>
*/
public function amounts(): HasMany
{
return $this->hasMany(CaseAmount::class)->orderBy('id');
}
/**
* @return HasMany<BookingChange, $this>
*/
public function changes(): HasMany
{
return $this->hasMany(BookingChange::class)->orderBy('id');
}
/**
* Own use, private stay or block (A6).
*/
public function isInternal(): bool
{
return $this->intake === IntakeKind::Internal;
}
/**
@@ -366,7 +443,7 @@ public function requiresFullPayment(): bool
*/
public function wantsPaymentTasks(): bool
{
return $this->process()->payments() === Responsibility::Landlord && $this->total !== null && $this->total > 0;
return ! $this->isInternal() && $this->process()->payments() === Responsibility::Landlord && $this->total !== null && $this->total > 0;
}
/**
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Models;
use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One change of a booking (package 5): what it was before and after, who asked and why, from when, and on which basis
* the guest agreed – or, as long as it is only proposed, that the guest still has to agree.
*/
#[Fillable(['booking_id', 'status', 'requested_by', 'basis', 'reason', 'effective_on', 'agreed_at', 'agreed_by', 'before', 'after', 'consequences', 'expires_at', 'decided_at', 'decision_ip_hash', 'applied_at', 'confirmation_sent_at', 'recorded_by'])]
class BookingChange extends Model
{
use BelongsToTenant;
public const REQUESTERS = ['guest' => 'Der Gast', 'landlord' => 'Wir (Vermieter)', 'portal' => 'Das Portal'];
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'status' => ChangeStatus::class,
'basis' => ChangeBasis::class,
'effective_on' => 'immutable_date',
'agreed_at' => 'immutable_datetime',
'before' => 'array',
'after' => 'array',
'consequences' => 'array',
'expires_at' => 'immutable_datetime',
'decided_at' => 'immutable_datetime',
'applied_at' => 'immutable_datetime',
'confirmation_sent_at' => 'immutable_datetime',
];
}
/** @return BelongsTo<Booking, $this> */
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
/**
* The change in one line, e.g. "07.11.–10.11.2026 → 07.11.–12.11.2026 · 2 → 3 Personen · 368,00 € → 450,00 €".
*/
public function summary(): string
{
return implode(' · ', (array) ($this->consequences['summary'] ?? []));
}
}
+1 -1
View File
@@ -11,7 +11,7 @@
* 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'])]
#[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', 'reason', 'recorded_by'])]
class Cancellation extends Model
{
use BelongsToTenant;
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Models;
use App\Enums\AmountKind;
use App\Models\Concerns\BelongsToTenant;
use App\Process\CaseLog;
use App\Support\Money;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* An amount of a case as a source states it (package 8): the portal's price positions, what it keeps as commission,
* what it announces to pay out, instalments of the guest. Stored as stated – contradicting statements stand side by
* side, and nothing is derived from them.
*/
#[Fillable(['booking_id', 'kind', 'label', 'amount', 'source', 'stated_on', 'due_on', 'note', 'recorded_by'])]
class CaseAmount extends Model
{
use BelongsToTenant;
protected static function booted(): void
{
static::created(function (CaseAmount $amount): void {
if ($amount->booking !== null) {
CaseLog::record($amount->booking, 'amount', ($amount->label ?: $amount->kind->getLabel()).': '.Money::format($amount->amount).($amount->source ? ' laut '.$amount->source : ''), data: ['case_amount_id' => $amount->id]);
}
});
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return ['kind' => AmountKind::class, 'amount' => 'integer', 'stated_on' => 'immutable_date', 'due_on' => 'immutable_date'];
}
/** @return BelongsTo<Booking, $this> */
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
public function title(): string
{
return $this->label ?: $this->kind->getLabel();
}
}
+6 -3
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod;
use App\Models\Concerns\BelongsToTenant;
use App\Process\CaseLog;
@@ -13,9 +14,10 @@
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A received payment (negative amount = refund), in euro cents.
* A payment in euro cents (negative amount = refund) and its kind: the guest paid us, the portal reports the guest paid
* it, the portal paid out to us, or we refunded the guest ({@see PaymentKind}).
*/
#[Fillable(['booking_id', 'amount', 'paid_on', 'method', 'note', 'recorded_by'])]
#[Fillable(['booking_id', 'amount', 'paid_on', 'method', 'note', 'recorded_by', 'kind', 'source'])]
class Payment extends Model
{
/** @use HasFactory<PaymentFactory> */
@@ -25,7 +27,7 @@ protected static function booted(): void
{
static::created(function (Payment $payment): void {
if ($payment->booking !== null) {
CaseLog::record($payment->booking, 'payment', ($payment->amount < 0 ? 'Erstattung ' : 'Zahlung ').Money::format(abs($payment->amount)).' erfasst', data: ['payment_id' => $payment->id]);
CaseLog::record($payment->booking, 'payment', ($payment->kind ?? PaymentKind::Guest)->getLabel().': '.Money::format(abs($payment->amount)).($payment->source ? ' ('.$payment->source.')' : ''), data: ['payment_id' => $payment->id]);
}
});
}
@@ -40,6 +42,7 @@ protected function casts(): array
return [
'paid_on' => 'immutable_date',
'method' => PaymentMethod::class,
'kind' => PaymentKind::class,
];
}
+1
View File
@@ -28,6 +28,7 @@
'included_guests',
'extra_guest_fee_per_night',
'cleaning_fee',
'tourist_tax_rate',
'deposit_percent',
'balance_due_days_before_arrival',
'hold_hours',
+138
View File
@@ -0,0 +1,138 @@
<?php
namespace App\Pricing;
use App\Enums\AmountKind;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Models\CaseAmount;
use Illuminate\Support\Collection;
/**
* The money of a case as four separate questions (package 8, K01): what the guest owes and to whom, what the guest has
* paid (to us or – according to the portal – to the portal), what the portal still has to pay out to us, and what has
* really arrived on our account. Every figure comes from a stated amount or a recorded payment; nothing is split up,
* estimated or counted twice, and contradicting statements are shown side by side with their difference.
*/
final class CaseMoney
{
private function __construct(private Booking $booking) {}
public static function of(Booking $booking): self
{
$booking->loadMissing(['payments', 'amounts']);
return new self($booking);
}
/**
* Who collects the guest's money (us, the portal, nobody for internal cases).
*/
public function collector(): Responsibility
{
return $this->booking->process()->payments();
}
public function total(): ?int
{
return $this->booking->total;
}
public function totalSource(): string
{
return match (true) {
$this->booking->total === null => 'noch nicht bekannt',
($this->booking->quote['source'] ?? null) === 'portal' => 'laut '.($this->booking->processChannel()?->name ?? 'Portal'),
$this->booking->isInternal() => 'vereinbart',
default => 'aus Ihren Preisen berechnet',
};
}
/**
* What the guest still owes us – only when we collect the money.
*/
public function openForUs(): int
{
return $this->collector() === Responsibility::Landlord ? $this->booking->openAmount() : 0;
}
/**
* What the guest still owes the portal according to the portal's statements (informational; the portal collects it).
*/
public function openAtPortal(): ?int
{
if ($this->collector() !== Responsibility::Portal || $this->booking->total === null) {
return null;
}
return max(0, $this->booking->total - $this->booking->paidViaPortal());
}
/**
* Instalments of the guest that the portal still shows as due.
*
* @return Collection<int, CaseAmount>
*/
public function installmentsDue(): Collection
{
return $this->amounts(AmountKind::InstallmentDue);
}
/**
* The price positions as stated, with their sum and whether they add up to the agreed total.
*
* @return array{positions: Collection<int, CaseAmount>, sum: int, difference: ?int}
*/
public function positions(): array
{
$positions = $this->booking->amounts->filter(fn (CaseAmount $amount): bool => $amount->kind->isPricePosition())->values();
$sum = (int) $positions->sum('amount');
return ['positions' => $positions, 'sum' => $sum, 'difference' => $positions->isEmpty() || $this->booking->total === null ? null : $this->booking->total - $sum];
}
/**
* @return Collection<int, CaseAmount>
*/
public function commissions(): Collection
{
return $this->amounts(AmountKind::Commission);
}
/**
* Payout announcements of the portal. Several different values are kept as they are; the difference is shown.
*
* @return array{announcements: Collection<int, CaseAmount>, values: list<int>, difference: int, received: int, outstanding: ?int}
*/
public function payout(): array
{
$announcements = $this->amounts(AmountKind::PayoutAnnounced);
$values = array_values(array_unique($announcements->pluck('amount')->map(fn ($value): int => (int) $value)->all()));
$received = $this->booking->payoutsReceived();
return [
'announcements' => $announcements,
'values' => $values,
'difference' => $values === [] ? 0 : max($values) - min($values),
'received' => $received,
// Only a single, consistent announcement gives an outstanding amount; contradicting ones are left to the person.
'outstanding' => count($values) === 1 ? max(0, $values[0] - $received) : null,
];
}
/**
* Money that really arrived on our account for this case: the guest's own payments (less refunds) and payouts.
*/
public function receivedOnAccount(): int
{
return $this->booking->paidToUs() + $this->booking->payoutsReceived();
}
/**
* @return Collection<int, CaseAmount>
*/
private function amounts(AmountKind $kind): Collection
{
return $this->booking->amounts->filter(fn (CaseAmount $amount): bool => $amount->kind === $kind)->values();
}
}
+1 -1
View File
@@ -209,7 +209,7 @@ private function bestOffers(Collection $offers, array $nightSeasons): array
* @param array<int, int> $extraQuantities
* @return list<QuoteLine>
*/
private function extraLines(Property $property, array $extraQuantities, int $nights): array
public function extraLines(Property $property, array $extraQuantities, int $nights): array
{
$extraQuantities = array_filter($extraQuantities, fn (int $quantity): bool => $quantity > 0);
if ($extraQuantities === []) {
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Pricing;
use App\Enums\QuoteLineType;
use App\Models\Property;
use Carbon\CarbonImmutable;
/**
* The price of an internal case (A6, package 6): the rent agreed for this stay (often 0 for family), the services
* booked with their usual prices, and the tourist tax (Kurabgabe) as a position of its own – the persons liable ×
* nights × the rate the landlord keeps on the property. Exemptions are noted by hand; there is no municipal rule logic.
*/
class PrivateStayPrice
{
public function __construct(private PriceCalculator $calculator) {}
/**
* @param array<int, int> $extras extra id => quantity
*
* @throws QuoteException
*/
public function quote(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure, ?int $guests, array $extras, int $rent, ?int $taxPersons): PriceQuote
{
$nights = (int) $arrival->diffInDays($departure);
$lines = [new QuoteLine(QuoteLineType::Rent, 'Miete (vereinbart)', 1, $rent, $rent)];
array_push($lines, ...$this->calculator->extraLines($property, $extras, $nights));
$tax = self::touristTax($property, $nights, $taxPersons);
if ($tax !== null) {
$lines[] = $tax;
}
return new PriceQuote($arrival, $departure, (int) $guests, $lines, 0, $arrival);
}
/**
* The tourist tax line, or null when no rate is kept or nobody is liable.
*/
public static function touristTax(Property $property, int $nights, ?int $persons): ?QuoteLine
{
$rate = (int) ($property->tourist_tax_rate ?? 0);
if ($rate <= 0 || (int) $persons <= 0 || $nights <= 0) {
return null;
}
$units = (int) $persons * $nights;
return new QuoteLine(QuoteLineType::TouristTax, 'Kurabgabe ('.$persons.' '.((int) $persons === 1 ? 'Person' : 'Personen').' × '.$nights.' Nächte)', $units, $rate, $units * $rate);
}
/**
* The agreed rent of an existing internal case (its rent line), 0 when none.
*
* @param array<string, mixed>|null $quote
*/
public static function rentOf(?array $quote): int
{
foreach ((array) ($quote['lines'] ?? []) as $line) {
if (($line['type'] ?? null) === QuoteLineType::Rent->value) {
return (int) $line['amount'];
}
}
return 0;
}
}
+70 -2
View File
@@ -2,12 +2,16 @@
namespace App\Process;
use App\Actions\EndInternalCase;
use App\Actions\SendBookingDocuments;
use App\Enums\ActivityState;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\ChangeStatus;
use App\Enums\ChannelTaskStatus;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Enums\ProcessingMode;
use App\Enums\Responsibility;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
@@ -28,7 +32,7 @@ class CaseActivities
private const LISTED_SEPARATELY = ['channel_block'];
/** Activities that are the next step whatever else is open. */
private const URGENT = ['task_portal_cancel_reported', 'task_portal_change_reported'];
private const URGENT = ['task_portal_cancel_reported', 'task_portal_change_reported', 'task_portal_cancellation'];
/**
* @return list<Activity>
@@ -44,6 +48,10 @@ public static function for(Booking $booking): array
$later = fn (ActivityState $state): ActivityState => $closed && ! in_array($state, [ActivityState::Done, ActivityState::External], true) ? ActivityState::NotApplicable : $state;
$activities = [];
if ($booking->isInternal()) {
return self::internal($booking, $closed, $later);
}
$activities[] = new Activity('intake', $inquiry ? 'Anfrage eingegangen' : 'Buchung beim Portal eingegangen', ActivityState::Done, $booking->created_at?->format('d.m.Y').' · '.$booking->bookingChannelLabel());
$needsContact = $inquiry || $profile->documents() === Responsibility::Landlord || $profile->guestMessages() === Responsibility::Landlord || $profile->payments() === Responsibility::Landlord;
@@ -135,7 +143,11 @@ public static function for(Booking $booking): array
}
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) {
$activities[] = new Activity('task_'.$task->kind->value, $task->kind->getLabel(), ActivityState::Open, $task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : null, $task->kind->isPayment() ? null : 'end');
$activities[] = self::task($task);
}
foreach ($booking->changes()->where('status', ChangeStatus::Proposed)->get() as $change) {
$activities[] = new Activity('change_proposed', 'Änderungsvorschlag liegt beim Gast', ActivityState::Waiting, $change->summary().($change->expires_at ? ' · bis '.$change->expires_at->format('d.m.Y') : ''));
}
$arrived = $binding && $booking->arrival <= $today;
@@ -155,6 +167,52 @@ public static function for(Booking $booking): array
return $activities;
}
/**
* Own use, private stay or block (A6): only what such a case has – no contract, no reminders, no reviews.
*
* @param callable(ActivityState): ActivityState $later
* @return list<Activity>
*/
private static function internal(Booking $booking, bool $closed, callable $later): array
{
$kind = $booking->internal_kind;
$activities = [new Activity('intake', ($kind?->getLabel() ?? 'Eigene Belegung').' eingetragen', ActivityState::Done, $booking->occasion)];
foreach (self::channelTasks($booking) as $task) {
$activities[] = new Activity('channel_block', ($task->action->value === 'block' ? 'In ' : 'Freigeben in ').$task->channel?->name.($task->action->value === 'block' ? ' sperren' : ''), $task->status === ChannelTaskStatus::Open ? ActivityState::Open : ActivityState::Done, $task->period().' · '.$task->proofLabel(), url: ChannelTaskResource::getUrl());
}
if ($kind !== InternalKind::Block && filled($booking->guest?->email)) {
$activities[] = new Activity('documents', 'Aufenthaltsbestätigung an die Gäste (optional)', $later($booking->confirmation_sent_at !== null ? ActivityState::Done : ActivityState::Later),
$booking->confirmation_sent_at ? 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y') : 'nur bei Bedarf', $booking->confirmation_sent_at === null && ! $closed ? 'sendDocuments' : null);
}
if ($booking->total !== null && $booking->total > 0) {
$paid = $booking->paidAmount();
$activities[] = new Activity('payment', 'Zahlung (ohne Erinnerungen)', $later($paid >= $booking->total ? ActivityState::Done : ActivityState::Later), Money::format($paid).' von '.Money::format($booking->total).' bezahlt');
}
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) {
$activities[] = self::task($task);
}
$activities[] = new Activity('stay', $kind === InternalKind::Block ? 'Sperrzeit' : 'Aufenthalt', $closed ? ActivityState::NotApplicable : ($booking->departure <= CarbonImmutable::today() ? ActivityState::Done : ActivityState::Later), $booking->arrival->format('d.m.Y').' – '.$booking->departure->format('d.m.Y'));
return $activities;
}
/**
* An open task of the case and the action that settles it.
*/
private static function task(BookingTask $task): Activity
{
$action = match ($task->kind) {
BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported => 'confirmPortalCancellation',
BookingTaskKind::PortalChangeReported => 'change',
BookingTaskKind::RefundCheck => null,
default => $task->kind->isPayment() ? null : 'end',
};
return new Activity('task_'.$task->kind->value, $task->kind->getLabel(), ActivityState::Open, trim(($task->due_on ? 'fällig '.$task->due_on->format('d.m.Y') : '').($task->note ? ' · '.$task->note : ''), ' ·'), $action);
}
/**
* What the landlord should do next on this case, or null when nothing is up to him.
*/
@@ -179,6 +237,16 @@ public static function next(Booking $booking): ?Activity
public static function situation(Booking $booking): string
{
$today = CarbonImmutable::today();
if ($booking->isInternal()) {
return implode(' · ', array_filter([
$booking->internal_kind?->getLabel() ?? 'Eigene Belegung',
$booking->occasion,
$booking->status === BookingStatus::Cancelled ? EndInternalCase::label($booking) : ($booking->departure <= $today ? 'beendet am '.$booking->departure->format('d.m.Y') : $booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y')),
]));
}
if ($booking->portal_cancellation_requested_at !== null && $booking->isBinding()) {
return 'Gebucht über '.($booking->processChannel()?->name ?? 'ein Portal').' · Stornierung beim Portal veranlasst – bleibt gebucht, bis sie bestätigt ist';
}
$channel = $booking->processChannel()?->name;
$kind = $booking->intake === IntakeKind::Booking ? 'Gebucht über '.($channel ?? 'ein Portal') : ($channel ? 'Anfrage über '.$channel : ($booking->source === 'website' ? 'Anfrage über die Webseite' : 'Anfrage'));
+4
View File
@@ -23,6 +23,9 @@ final class ProcessProfile
public const CHANNEL = 'channel';
/** Fixed by the case type (A6), not settable. */
public const CASE_TYPE = 'case_type';
/** Settings resolved when they are used instead of being frozen (documents capture their own template). */
public const LIVE = [ProcessSetting::ContractTemplate];
@@ -117,6 +120,7 @@ public static function sourceLabel(string $source): string
self::TENANT => 'Ihre Standardeinstellung',
self::PROPERTY => 'Abweichung der Wohnung',
self::CHANNEL => 'Abweichung des Portals',
self::CASE_TYPE => 'fest für diese Vorgangsart',
'migration' => 'aus dem bisherigen Stand übernommen',
default => 'Grundeinstellung',
};
+8 -1
View File
@@ -49,7 +49,14 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak
}
}
if ($intake !== IntakeKind::Booking) {
if ($intake === IntakeKind::Internal) {
// Own use, private stays and blocks (A6): no rental documents, no payment reminders, no guest mails – fixed by
// the case type, not by a setting.
foreach ([ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages] as $setting) {
$values[$setting->value] = Responsibility::Nobody->value;
$sources[$setting->value] = ProcessProfile::CASE_TYPE;
}
} elseif ($intake !== IntakeKind::Booking) {
// A request is answered with our own offer and an internal case is ours anyway: the documents are ours.
$values[ProcessSetting::Documents->value] = Responsibility::Landlord->value;
$sources[ProcessSetting::Documents->value] = ProcessProfile::SYSTEM;
@@ -0,0 +1,94 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Packages 8, 5 and 6 of UMSETZUNGSPLAN_v0.10:
* - external amounts of a case with kind, source and date (case_amounts) and the kind of every payment – a payment of
* the guest to us, one the portal reports as paid to it, a payout of the portal, a refund (package 8);
* - changes of a booking with who asked, why, from when and on which basis, agreed or proposed to the guest (package 5);
* a cancellation records its reason and who entered it; a portal cancellation can wait for the portal's confirmation;
* - own use, private stays and blocks as cases (package 6): their kind, occasion, tourist tax and – for blocks taken over
* from the old block list – the calendar identity the portals already know.
* Purely additive; existing payments count as payments of the guest to us.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('payments', function (Blueprint $table): void {
$table->string('kind', 20)->default('guest');
$table->string('source', 120)->nullable();
});
Schema::create('case_amounts', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
$table->foreignId('booking_id')->constrained()->cascadeOnDelete();
$table->string('kind', 20);
$table->string('label', 150)->nullable();
$table->integer('amount');
$table->string('source', 120)->nullable();
$table->date('stated_on')->nullable();
$table->date('due_on')->nullable();
$table->string('note', 500)->nullable();
$table->string('recorded_by', 120)->nullable();
$table->timestamps();
$table->index(['booking_id', 'kind']);
});
Schema::create('booking_changes', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
$table->foreignId('booking_id')->constrained()->cascadeOnDelete();
$table->string('status', 12);
$table->string('requested_by', 12);
$table->string('basis', 20)->nullable();
$table->text('reason')->nullable();
$table->date('effective_on')->nullable();
$table->timestamp('agreed_at')->nullable();
$table->string('agreed_by', 120)->nullable();
$table->json('before');
$table->json('after');
$table->json('consequences')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamp('decided_at')->nullable();
$table->string('decision_ip_hash', 64)->nullable();
$table->timestamp('applied_at')->nullable();
$table->timestamp('confirmation_sent_at')->nullable();
$table->string('recorded_by', 120)->nullable();
$table->timestamps();
$table->index(['booking_id', 'status']);
});
Schema::table('cancellations', function (Blueprint $table): void {
$table->text('reason')->nullable();
$table->string('recorded_by', 120)->nullable();
});
Schema::table('bookings', function (Blueprint $table): void {
$table->string('internal_kind', 16)->nullable();
$table->string('occasion', 255)->nullable();
$table->string('export_uid', 120)->nullable();
$table->unsignedTinyInteger('tourist_tax_persons')->nullable();
$table->string('tourist_tax_note', 255)->nullable();
$table->timestamp('portal_cancellation_requested_at')->nullable();
});
Schema::table('properties', function (Blueprint $table): void {
$table->unsignedInteger('tourist_tax_rate')->nullable();
});
}
public function down(): void
{
Schema::table('properties', fn (Blueprint $table) => $table->dropColumn('tourist_tax_rate'));
Schema::table('bookings', fn (Blueprint $table) => $table->dropColumn(['internal_kind', 'occasion', 'export_uid', 'tourist_tax_persons', 'tourist_tax_note', 'portal_cancellation_requested_at']));
Schema::table('cancellations', fn (Blueprint $table) => $table->dropColumn(['reason', 'recorded_by']));
Schema::dropIfExists('booking_changes');
Schema::dropIfExists('case_amounts');
Schema::table('payments', fn (Blueprint $table) => $table->dropColumn(['kind', 'source']));
}
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 254 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 453 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

@@ -0,0 +1,69 @@
# Fachliche End-to-End-Abnahme
Wiederverwendbarer Katalog repräsentativer Geschäftsfälle. Jeder Fall ist aus Sicht der Vermieterin beschrieben und hat zwei Nachweise:
- einen automatisierten Durchgang über die echten Dialoge, Aktionen und Gast-Links, im Test `tests/Feature/EndToEndAcceptanceTest.php`, Methode `test_tNN_…`;
- wo sinnvoll eine Sichtprüfung im Browser, Screenshots unter `Abnahme/<Datum>/`.
Für weitere Pakete werden Fälle ergänzt und der Abschnitt „Durchführung“ neu datiert.
**Durchführung 01.11.2026**
- Stand: Branch `feature/abwicklung`, Pakete 1–6 und 8.
- Automatisiert: 15 Fälle, alle bestanden (Teil der Suite mit 685 grünen Tests).
- Browser: lokale Datenbankkopie mit Testdaten (Gäste `@example.test`), Testbetrieb aktiv, Versandweg „log“, Anmeldung mit Zwei-Faktor-Code.
- Testsystem: nicht genutzt, keine Deployment-Freigabe.
- Echte Gastnachrichten oder Portalbelegungen: keine.
**Status:** ✅ erfolgreich · ◐ teilweise · ✗ fehlgeschlagen · – noch nicht ausführbar
---
## Testfälle
| ID | Fall | Ausgangslage und Konfiguration | Anwenderhandlungen | Soll | Ist | Status | Nachweis |
|---|---|---|---|---|---|---|---|
| T01 | Eigene Anfrage, automatisch | Vermieterstandard „automatisch“, Vertragstexte und Bank hinterlegt | Gast fragt über die Webseite an | Angebot geht ohne Klick hinaus; Vorgang wartet auf den Gast; nichts unter „Zu erledigen“ | wie Soll (A1, Angebot gesendet, Aktivität „Gast nimmt an“ wartet) | ✅ | `test_t01_…` |
| T02 | Eigene Anfrage, manuell | Standard „Sie geben frei“; Portal „Ostseeklar“ mit Handsperre | „Neu → Anfrage“; „Angebot prüfen und senden“; Gast nimmt per Link an | Zu erledigen „Angebot prüfen und senden“; nach Annahme gebucht, Vertrag, Bestätigung, Sperraufgabe | wie Soll | ✅ | `test_t02_…` |
| T03 | Fehlende Gastdaten | automatisch; Anfrage per Telefon ohne E-Mail | „E-Mail-Adresse eintragen“ mit „automatisch weitermachen“ | verständliche Aufgabe, danach Angebot automatisch | wie Soll | ✅ | `test_t03_…` |
| T04 | FeWo-direkt-Direktbuchung | Kanal „Anlegen“, Zahlung über Portal | Buchungsmail kommt an; „Preis laut Portal eintragen“ 979,51 € | ein Vorgang A4, Portalpreis, keine eigenen Mahnungen | wie Soll | ✅ | `test_t04_…` |
| T05 | Destination Solutions | Portal ohne Automatik, Zahlung durch uns | „Neu → Buchung von einem Portal“ mit Nummer, Preis, Gast | A3 gebucht ohne Angebot; Unterlagen und Zahlungsplan durch uns; Anzahlung bewegt den Status | wie Soll | ✅ | `test_t05_…` |
| T06 | Doppelte Portalmeldungen | Kanal mit iCal-Regel und Mail-Absender | Mail, danach zweimal Kalenderabgleich | genau ein Vorgang, Kalendereintrag zugeordnet | wie Soll | ✅ | `test_t06_…` |
| T07 | Buchungsänderung | gebuchte eigene Buchung 07.–10.11. | „Buchung ändern …“ bis 12.11., vereinbart am Telefon | Vorschau zeigt Folgen; danach Zeitraum, Preis, Zahlungsplan, Portalaufgabe, Verlauf | wie Soll (Preis +130 €, „Neu belegt“, Aufgabe Ostseeklar) | ✅ | `test_t07_…`, `T07-aendern-folgen.png` |
| T08 | Stornierung | eigene Buchung mit 100 € Zahlung; Portalbuchung; offene Anfrage | „Stornieren …“ bzw. „Beenden …“; bei Portal „Stornierung bestätigen …“ | eigene: storniert mit Initiator, Grund, Kosten- und Erstattungsaufgabe; Portal: erst nach Bestätigung storniert; Anfrage: ohne Buchung beendet, kein Storno | wie Soll | ✅ | `test_t08_…`, `T08-zu-erledigen-portalstorno.png` |
| T09 | Familienbesuch | Kurabgabe 2,50 €; Leistung Wäschepaket 18 € | „Neu → Eigene Nutzung oder Besuch → Familie“, 5 Nächte, 3 Personen, Miete 0, 3 Wäschepakete, Kurabgabe 2 Personen | A6 mit 54 € + 25 € Kurabgabe = 79 €; Portale gesperrt; kein Vertrag, keine Mahnung, keine Bewertung | wie Soll | ✅ | `test_t09_…`, `T09-neu-besuch.png`, `T09-familienbesuch.png` |
| T10 | Wartungssperre | – | Belegungsplan „+ eintragen“ → Sperre; „Ändern oder verlängern …“; „Sperre aufheben …“ | ohne Gast, Vertrag, Zahlung; Verlängerung passt Portale an; Aufheben ist keine Stornierung, Portale werden freigegeben | wie Soll | ✅ | `test_t10_…`, `T10-sperre-aufheben.png` |
| T11 | Externe Zahlungen (R09) | FeWo-direkt-Buchung | Beträge laut Portal: 840 / −42 / 181,51 Sammelposten / 979,51 / −84,82 / 894,69 und 900,20 / Rate 588,90 fällig / 390,61 laut Portal bezahlt; später Auszahlung 894,69 € erfasst | Summe = Gesamtpreis; Abweichung 5,51 € ungeklärt angezeigt; offen bei uns 0; Konto erst nach Auszahlung; keine Doppelzählung | wie Soll | ✅ | `test_t11_…`, `T11-betraege-r09.png` |
| T12 | Einstellungshierarchie | Standard automatisch / 48 h; Wohnung 24 h; FeWo-direkt Anfrage „manuell“, Buchung Zahlung Portal | Anfrage über FeWo-direkt; im Vorgang auf „automatisch“ umstellen; Seite „Wirksame Einstellungen“ | jede Ebene wirkt mit richtiger Herkunft; die Vorgangsentscheidung gewinnt; Übersicht zeigt beides | wie Soll | ✅ | `test_t12_…`, `T12-wirksame-einstellungen.png` |
| T13 | Testbetrieb | Testbetrieb mit Testadresse, echter Mailer | ganzer Ablauf: Anfrage, Angebot, Annahme, Änderung mit Bestätigung, Storno mit Mail | jede tatsächlich versendete Nachricht geht nur an die Testadresse | wie Soll (≥ 6 Nachrichten, alle an test@example.com) | ✅ | `test_t13_…`, zusätzlich `MailTestModeGateTest` |
| T14 | Änderungen mit Zustimmung | gebuchte eigene Buchung | Vorschlag an den Gast; Gast nimmt per Link an; danach vereinbarte Änderung mit Bestätigung | Vorschlag ändert nichts bis zur Annahme; Annahme mit Zeitpunkt; Bestätigung einer vereinbarten Änderung ist keine Zustimmung | wie Soll | ✅ | `test_t14_…`, `T14-gast-aenderungsvorschlag.png` |
| T15 | Bestandsübernahme Sperren (6.3) | zwei manuelle Sperren, Exportkanal | `cases:adopt-blocks` Vorschau, `--apply`, nochmals `--apply` | zwei A6-Vorgänge, keine Dublette, Export identisch, keine Aufgaben oder Mails | wie Soll | ✅ | `test_existing_manual_blocks_…` |
---
## Nicht ausführbare oder nur teilweise geprüfte Punkte
| Punkt | Grund |
|---|---|
| Durchführung auf dem Testsystem stommer.info | keine Deployment-Freigabe; geprüft wurde auf einer lokalen Datenbankkopie |
| Echte FeWo-direkt-Mails und -Feeds | nur synthetische Muster (siehe Beobachtungsmodus aus Paket 4) |
| Darstellung auf Tablet und Smartphone | nicht geprüft |
| Bedienprobe mit der Vermieterin | steht aus (Abnahme 2.5) |
| Änderung extern (5.2) als eigener Durchgang | durch die Preislogik und T04/T11 abgedeckt, kein eigener Testfall |
---
## Erkannte Bedienungsprobleme
| Problem | Stand |
|---|---|
| Bei A6 erschien „Über: internal“, dazu der Schalter „Sie geben frei“ und eine Vorlagenangabe | behoben |
| Ein Portal mit Buchungsmodell „gemischt“ (Sofortbuchung), dessen Kalenderexport nie abgeholt wurde, hält automatische Angebote und sogar Gastannahmen an („Verfügbarkeit nicht sicher“). Das ist fachlich richtig, für Testdaten aber überraschend. | dokumentiert; bei Einrichtung eines Portals das Buchungsmodell bewusst wählen |
| Bei Portalzahlung zeigt der Status „Anzahlung erhalten“, der Verlauf „Anzahlung eingegangen“, obwohl nur laut Portal bezahlt ist | offen (Entscheidung, siehe Ergebnisdokument §7) |
| Der Dialog „Buchung ändern“ ist lang (Termin, Leistungen, Preis, Folgen, Grundlage) | offen – Vorschlag: Grundlage oben, Leistungen zuklappen |
| „Wirksame Einstellungen“: die Spalte „Wo einstellen?“ wiederholt sich je Zeile | offen, rein kosmetisch |
## Offene Arbeiten
1. Abnahme auf dem Testsystem nach Freigabe (Migration MariaDB, `cases:adopt-blocks` Vorschau mit echten Daten).
2. Bedienprobe mit der Vermieterin mit T02, T07, T09 und T10 als Drehbuch.
3. Statusbezeichnung bei Portalzahlung klären (mit B4 / Paket 9).
4. Texte Änderungsbestätigung, Änderungsvorschlag und Aufenthaltsbestätigung freigeben.
@@ -0,0 +1,88 @@
# Konfiguration und Wirksamkeit
Welche fachlichen Einstellungen es gibt, wo man sie vornimmt, wie sie sich vererben und wie man nachprüft, dass sie in einem konkreten Vorgang wirklich angewandt wurden. Stand 01.11.2026, Pakete 1–6 und 8.
---
## 1. Wo man die Wirksamkeit sieht
| Werkzeug | Zeigt |
|---|---|
| **System › Wirksame Einstellungen** (Expertenansicht) | Je Wohnung und Eingangsweg (direkte Anfrage, jedes Portal getrennt nach Anfrage und fester Buchung, A6) den Wert jeder Prozesseinstellung, der für einen **neuen** Vorgang gilt, mit Herkunft und dem Ort, an dem man ihn ändert. „Einen Vorgang prüfen“ zeigt das tatsächlich angewandte Profil eines Vorgangs und eine Umstellung im Vorgang. Direktaufruf: `…/admin/wirksame-einstellungen?vorgang=<ID>`. |
| **Vorgang › Technische Angaben** (Expertenansicht) | eingefrorenes Abwicklungsprofil mit Herkunft je Wert, Quellen und Kalenderdarstellungen |
| **Vorgang › Zusammenstellung** (Paket 3) | Vorlage mit Herkunft („eingestellt für FeWo-direkt (Verbindliche Buchung)“) |
| `php artisan process:settings-report` | alle Standards und Abweichungen als Text |
| `php artisan channels:intake-report` | was der Eingang je Portal erkannt hat (Paket 4) |
Nachweis im Test: `EndToEndAcceptanceTest::test_t12_settings_hierarchy_is_applied_and_visible`; Screenshot `Abnahme/2026-11-01/T12-wirksame-einstellungen.png`.
---
## 2. Vererbung
```
Grundeinstellung (im Code)
→ Ihr Standard System › So arbeite ich
→ Wohnung Wohnung bearbeiten › „Abweichende Abwicklung dieser Wohnung“ (Expertenansicht)
→ Portal je Eingangsart Portal bearbeiten › „Anfragen über dieses Portal“ / „Feste Buchungen über dieses Portal“
→ Vorgang Schalter „Läuft automatisch / Sie geben frei“ auf der Vorgangsseite
```
- **Leer heißt „erbt“.** Ein bewusst gesetztes „nein“, „0“ oder „manuell“ ist ein eigener Wert.
- **Eingefroren beim Eingang.** Ein Vorgang behält die Werte, die bei seinem Eingang galten. Spätere Änderungen gelten nur für neue Vorgänge. Ausnahme ist die Vertragsvorlage: Sie wird erst festgehalten, wenn das Dokument erstellt wird.
- **A6 fest.** Für eigene Nutzung, Besuch und Sperre stehen Unterlagen, Zahlungen und Gastmails unabhängig von jeder Einstellung auf „Entfällt“ (Herkunft „fest für diese Vorgangsart“).
- **Anfragen:** Unterlagen schicken immer wir (Herkunft „Grundeinstellung“), denn das Angebot ist unser eigenes.
- **Die Vorgangsart ergibt sich aus den wirksamen Werten.** Anfrage direkt = A1, über ein Portal = A2; feste Portalbuchung = A3 (wir zahlen und schicken Unterlagen), A4 (Portal zahlt), A5 (Portal schickt Unterlagen); intern = A6.
---
## 3. Einstellbare Prozessparameter
| Einstellung | Standard | Übersteuerbar auf | Wirkung |
|---|---|---|---|
| Bearbeitung neuer Vorgänge (automatisch / Sie geben frei) | Sie geben frei | Vermieter, Wohnung, Portal (Anfrage und Buchung), Vorgang | Ob Angebote und Unterlagen ohne Klick hinausgehen, sobald nichts fehlt und nichts zu prüfen ist |
| Reserviert eine Anfrage den Zeitraum? | ja | Vermieter, Wohnung, Portal (Anfrage) | Belegt den Zeitraum bis zum Ablauf. Bei „nein“ gibt es kein Angebot mit Annahmelink ohne ausdrückliche Bestätigung (Hold-0-Schutz bis Paket 7). |
| Gültigkeit Angebot / Reservierung | 48 Stunden | Vermieter, Wohnung, Portal (Anfrage) | Frist für Angebot und Reservierung |
| Wer schickt Vertrag bzw. Unterlagen? | Wir | Vermieter, Wohnung, Portal (Buchung) | Portal → A5, keine eigenen Unterlagen |
| Wer kümmert sich um die Zahlungen? | Wir | Vermieter, Wohnung, Portal (Anfrage und Buchung) | Portal → A4: keine Mahnungen, Übersicht „laut Portal“ (Paket 8) |
| Wer schickt Anreise-Info und Bewertungsbitte? | Wir | Vermieter, Wohnung, Portal (Anfrage und Buchung) | Portal → keine eigenen Mails |
| Anreise-Info Tage vorher | 3 | Vermieter, Wohnung | Zeitpunkt der Anreisemail |
| Vertragsvorlage | Texte der Webseite | Wohnung, Portal (Anfrage und Buchung), Vorgang (Zusammenstellung) | Inhalt von Angebot, Bestätigung und Buchungsunterlagen |
**Weitere Einstellungen außerhalb dieser Hierarchie:**
| Einstellung | Wo | Ebene | Wirkung |
|---|---|---|---|
| Erkannte Buchungen automatisch übernehmen | Portal bearbeiten | Kanal | Aus / Beobachten / Anlegen / Anlegen und weiterbearbeiten (Paket 4) |
| Was kommt über dieses Portal? (Anfrage / Portalbuchung / gemischt) | Portal bearbeiten | Kanal | Sofortbuchungsschutz (`CalendarClearance`); „nur Anfragen“ lässt feste Buchungen klären |
| Zusätzlich von Hand sperren | Portal bearbeiten | Kanal | Portalaufgaben mit Nachweisstufe |
| Freigabe der Dokumentarten | System › So arbeite ich › Dokumente | Vermieter | Arbeitsfassungen gehen nie automatisch hinaus |
| Freigabe / Portalbedingungen einer Vorlage | Vorlagen › Freigabe | Vorlagenversion | Schutz vor unvereinbarten Bedingungen (Paket 3) |
| Kurabgabe je Person und Nacht | Wohnung › Preise | Wohnung | Position „Kurabgabe“ bei A6 |
| Testbetrieb / Testadresse | System › Betrieb | Vermieter (Server-Vorgabe `FEWO_MAIL_REDIRECT_TO` gewinnt) | Jede ausgehende Mail nur an die Testadresse |
| Anzahlungsfrist, Bewertung nach Tagen | System › Betrieb | Vermieter | Zahlungsplan, Bewertungsbitte |
---
## 4. Nachweis an konkreten Vorgängen (Abnahme 01.11.2026)
| Konstellation | Erwartung | Beobachtet |
|---|---|---|
| Standard „automatisch“, Wohnung „24 Stunden“, direkte Anfrage | automatisch (Ihr Standard), 24 h (Wohnung) | identisch (T12) |
| FeWo-direkt Anfrage „manuell“ | manuell, Herkunft Portal | identisch (T12) |
| FeWo-direkt feste Buchung ohne eigene Bearbeitungseinstellung | automatisch, Herkunft „Ihr Standard“ – erbt | identisch (T12) |
| FeWo-direkt feste Buchung, Zahlung Portal | A4 | identisch (T04, T12) |
| Anfrage über FeWo-direkt, im Vorgang auf „automatisch“ umgestellt | Vorgang automatisch, Hinweis „für diesen Vorgang umgestellt“ | identisch (T12, Seite „Wirksame Einstellungen“) |
| Familienbesuch | Unterlagen, Zahlungen, Gastmails „Entfällt (fest A6)“ | identisch (T09, Screenshot T12) |
---
## 5. Lücken und widersprüchliche Stellen
| Stelle | Beschreibung | Empfehlung |
|---|---|---|
| **Buchungsmodell am Portal und Abwicklungsprofil** | „Was kommt über dieses Portal?“ steuert noch den Sofortbuchungsschutz und den Hinweis „nur Anfragen“. Das Profil je Eingangsart steuert die Abwicklung. Beides kann sich widersprechen, z. B. Modell „nur Anfragen“, aber Abweichungen für feste Buchungen gepflegt. | Beim nächsten Paket das Modell aus den gepflegten Eingangsarten ableiten oder einen Hinweis im Portalformular zeigen. |
| **Alte Spalten** | `properties.hold_hours`, `pre_reservation_enabled` usw. und Kanal-Booleans werden seit Paket 1 nicht mehr gelesen, stehen aber noch in der Datenbank. | Nach erfolgreicher Migration auf Produktion entfernen. |
| **Kurabgabe** | Satz nur an der Wohnung, nicht in der Hierarchie; bei Gästen regulärer Buchungen nicht berechnet (die Verträge sagen „vor Ort“). | Bewusst so (B1); erweitern, falls auch reguläre Buchungen sie ausweisen sollen. |
| **Bearbeitungsart bei A6** | wird angezeigt, ist aber ohne Wirkung; bei A6 gibt es nichts Automatisches | ohne Handlungsbedarf |
| **Einstellungen im Vorgang** | Nur die Bearbeitungsart und die Vorlage (im Dokument) lassen sich je Vorgang umstellen, sonst nichts. | entspricht dem Plan |
@@ -0,0 +1,190 @@
# Umsetzungsergebnis Pakete 8, 5 und 6
Stand: 01.11.2026 · Branch `feature/abwicklung` (aufbauend auf `develop` = Pakete 1–4) · Grundlage: [UMSETZUNGSPLAN_v0.10](UMSETZUNGSPLAN_v0.10.md) §4.6, §5.6, §5.7, §5.9 und die Abnahmekriterien 5.x, 6.x, 8.x. Die normative Prozessarchitektur v0.10 wurde nicht verändert.
Begleitdokumente: [END_TO_END_ABNAHME.md](END_TO_END_ABNAHME.md) (fachliche Abnahme T01–T14) und [KONFIGURATION_UND_WIRKSAMKEIT.md](KONFIGURATION_UND_WIRKSAMKEIT.md).
---
## 1. Implementierungsstand je Paket
| Paket | Stand | Einschränkungen |
|---|---|---|
| **8 – Externe Beträge und Zahlungsstände** | umgesetzt | Kein Import von Portalbeträgen aus Mails oder Abrechnungen; erfasst wird von Hand. |
| **5 – Änderung, Storno, kontrollierter Abbruch** | umgesetzt | Kein Änderungsvorschlag an Portalgäste (geändert wird im Portal); keine PDF-Nachtragsurkunde, die Änderungsbestätigung ist eine Mail. |
| **6 – A6 im Vorgang** | umgesetzt | Der Kalender-Schnellweg ist ein Link je freiem Tag, keine Bereichsauswahl per Maus. |
Tests: **685 grün** (vorher 670; neu sind 15 fachliche Durchgangstests in `EndToEndAcceptanceTest`), Pint sauber. Die Abnahme über die Oberfläche lief im Browser auf einer Datenbankkopie. Ein Testsystem stand ohne Deployment-Freigabe nicht zur Verfügung.
---
## 2. Verfügbare Geschäftsfunktionen
### Paket 8 – Preise und Zahlungen
**Preis laut Portal eintragen.** Ein Dialog übernimmt den Gesamtpreis des Gastes als vereinbarten Preis. Aufklappbar folgen Einzelangaben mit Art, Bezeichnung, Betrag und bei Raten dem Fälligkeitsdatum:
- Übernachtung, Leistung, Rabatt, Gebühr/Steuer
- Sammelposten, nicht aufgeschlüsselt
- Provision / an das Portal gezahlt
- angekündigte Auszahlung, Rate laut Portal fällig
Zahlungen, die das Portal als bezahlt zeigt, lassen sich mit eintragen. Quelle und Stand werden gespeichert. Dieselbe Angabe ein zweites Mal wird nicht doppelt angelegt.
**Zahlungen mit Art.** Es gibt vier Arten:
- Gast hat an uns gezahlt
- Gast hat laut Portal ans Portal gezahlt
- Auszahlung vom Portal erhalten
- Erstattung an den Gast (wird automatisch abgezogen)
**Übersicht „Preis und Zahlungen“** im Vorgang:
- vereinbarter Gesamtpreis mit Herkunft
- je nach Zuständigkeit: „Noch offen – zahlt der Gast an uns“ oder „laut Portal bezahlt / noch beim Gast offen / Raten“
- angekündigte und erhaltene Auszahlungen; widersprüchliche Angaben stehen nebeneinander mit dem Hinweis „weichen um 5,51 € ab – ungeklärt“
- „Auf unserem Konto eingegangen“
- aufklappbar die Einzelangaben mit Summenprüfung („979,51 € = Gesamtpreis“)
**Zuständigkeit.** Zahlungserinnerungen entstehen nur, wenn wir die Zahlung einziehen. Bei Portalzahlung und bei A6 entstehen keine.
### Paket 5 – Ändern, Stornieren, Beenden
**„Buchung ändern …“** (bei A6 „Ändern oder verlängern …“) ändert Zeitraum, Personen, Leistungen und Preis. Vor dem Speichern zeigt der Dialog „Das ändert sich“ und „Folgen“:
- neu belegte bzw. wieder freie Nächte
- Aufgaben für Portale, die von Hand gesperrt werden
- alter und neuer Preis mit Differenz und Herkunft: neu berechnet (eigene Buchung, angepasste Positionen bleiben), neuer Betrag laut Portal (A3–A5) oder vereinbarte Miete mit Leistungen und Kurabgabe (A6)
- bisher bezahlt und danach offen; die Anzahlung bleibt, wenn sie bezahlt ist; neue Fälligkeit; Erstattungshinweis
**Zwei Wege:**
- *Mit dem Gast bereits vereinbart:* Die Änderung wirkt sofort und hält fest, wer sie wollte, warum, ab wann und auf welcher Grundlage (Telefon, E-Mail, persönlich, Portal). Auf Wunsch geht eine Bestätigung an den Gast. Sie informiert nur und gilt **nicht** als Zustimmung.
- *Dem Gast vorschlagen:* Bis zur Zustimmung ändert sich nichts. Der Gast bekommt einen signierten Link, nimmt an (mit Häkchen; Zeit und gehashte Adresse werden gespeichert) oder lehnt ab. Die Vermieterin wird informiert, der Vorschlag lässt sich zurückziehen.
**Folgen nach dem Speichern:**
- Kalender und Portalexport sind aktualisiert; Sperr- und Freigabeaufgaben entstehen.
- Der Zahlungsstatus wird neu berechnet.
- Bei Überzahlung entsteht die Aufgabe „Erstattung an den Gast prüfen“.
- Jede Änderung steht im Verlauf (`booking_changes`).
**„Stornieren …“ / „Beenden …“** wählt den Weg nach Lage:
| Lage | Ergebnis |
|---|---|
| Unverbindlich | Ohne Buchung beendet; Absage optional, Grund im Verlauf. |
| Eigene Buchung | Storniert mit Initiator, Grund und Erfasser. Stornokostenaufgabe nach der eingefrorenen Regel; Erstattungsaufgabe, wenn mehr gezahlt wurde als die Kosten. |
| Portalbuchung (A3–A5) | „Stornierung im Portal veranlassen“. Der Vorgang **bleibt gebucht** und der Zeitraum belegt, bis „Stornierung bestätigen …“ mit dem Häkchen „im Portal wirksam (geprüft)“ erledigt ist. Meldet das Portal die Stornierung selbst (Paket 4), heißt die Aktion „Stornierung übernehmen …“. |
| A6 | „Sperre aufheben …“ bzw. „Aufenthalt absagen …“: keine Stornierung, keine Kosten, keine Mails. Die Portale werden freigegeben. |
Der Stornolink des Gastes führt wie bisher zur Aufgabe am Vorgang und damit in denselben Stornoweg. „Status von Hand ändern“ bleibt in der Expertenansicht mit Pflichtbegründung und kann eine verbindliche Buchung nicht zurücksetzen.
### Paket 6 – Eigene Nutzung, Besuch, Sperre
**„Neu“ hat zwei zusätzliche Einstiege:**
- „Eigene Nutzung oder Besuch von Familie und Freunden“, mit der Frage „Wir selbst / Familie oder Freunde“
- „Eine Sperre ohne Gäste“
Erfasst werden Zeitraum und Anlass. Bei Besuch kommen Gäste, Personen, Leistungen, vereinbarte Miete (Standard 0 €), Kurabgabe-Personen und Befreiungen dazu.
**Schnellwege:**
- im Belegungsplan „+ eintragen“ an jedem freien Tag und „Eigene Nutzung / Sperre eintragen“;
- in der Liste „Sperrzeiten“ führt „Zeitraum sperren“ in denselben Dialog.
**Der A6-Vorgang:**
- belegt sofort; Portale werden gesperrt (Aufgaben oder Kalenderexport, im Export ohne Buchungsnummer und wie eine Sperre);
- hat eigene Aktivitäten: eingetragen, Portalsperren, Aufenthaltsbestätigung (optional), Zahlung ohne Erinnerungen, Aufenthalt bzw. Sperrzeit;
- ohne Mietvertrag, Mahnungen, Bewertungsanfrage, Anreisemail und Marketing; das A6-Profil setzt diese Zuständigkeiten fest auf „Entfällt“.
**Kurabgabe:**
- als eigene Position „Kurabgabe (N Personen × M Nächte)“;
- der Satz je Person und Nacht steht an der Wohnung unter Preise, Feld „Kurabgabe je Person und Nacht“;
- Befreiungen trägt man im Vorgang als Text ein;
- keine kommunale Tariflogik.
**Aufenthaltsbestätigung:** eine eigene Dokumentart mit PDF ohne Mietvertrag und Mail `StayConfirmed`. Sie wird über die Zusammenstellung aus Paket 3 versendet und ist eine Arbeitsfassung, bis sie freigegeben ist.
**Bestandsübernahme `cases:adopt-blocks`:**
- Ohne Zusatz ist es eine Vorschau; mit `--apply` werden die Sperren übernommen.
- Ein zweiter Lauf übernimmt nichts doppelt; `--revert=<Bericht>` macht die Übernahme rückgängig.
- Bisherige manuelle Sperren werden zu A6-Vorgängen. Die Sperre bleibt als gelöschte Spur erhalten.
- **Der Kalenderexport ist danach identisch:** gleiche Kennung `block-…`, gleiche Felder, gleicher Zeitstempel. Es entstehen keine Portalaufgaben und keine Mails.
### Übergreifend – Wirksame Einstellungen
Neue Expertenseite **System › Wirksame Einstellungen**:
- je Wohnung und Eingangsweg (direkte Anfrage, jedes Portal mit Anfrage und fester Buchung, A6) jede Prozesseinstellung mit wirksamem Wert, Herkunft und dem Ort, an dem sie eingestellt wird;
- „Einen Vorgang prüfen“ zeigt das tatsächlich angewandte, eingefrorene Profil und die Entscheidung im Vorgang.
Details stehen in [KONFIGURATION_UND_WIRKSAMKEIT.md](KONFIGURATION_UND_WIRKSAMKEIT.md).
---
## 3. Technische Konsolidierungen und Architekturentscheidungen
| Entscheidung | Begründung |
|---|---|
| **Kein neues Zahlungsmodell, sondern `payments.kind`** (`PaymentKind`). `Booking::paidAmount()` zählt nur Zahlungen des Gastes; `paidToUs()`, `paidViaPortal()` und `payoutsReceived()` sind getrennt. | Bestehende Zahlungen bleiben gültig (Standard „Gast an uns“), Mahnläufe und Status arbeiten weiter. Auszahlungen zählen nicht doppelt. |
| **Beträge als Angaben (`case_amounts`, `AmountKind`)**, nie verrechnet; `App\Pricing\CaseMoney` beantwortet die vier Geldfragen. | Vorgabe K01/E-014/E-015: keine Scheingenauigkeit, Widersprüche bleiben sichtbar. |
| **Eine Aktion `ChangeBooking`** mit `preview`, `apply`, `propose`, `accept`, `decline`, `withdraw`; Änderungen als `booking_changes` mit vorher/nachher und Folgen. | Ein Weg für A1–A6; Vorschau und Ausführung rechnen identisch. Kalender und Portalaufgaben folgen über den bestehenden `BookingObserver`. |
| **Gastzustimmung nur über den signierten Link** (`ChangeBasis::GuestLink` ist nur dort möglich). Eine Änderungsbestätigung setzt `confirmation_sent_at`, nicht `decided_at`. | Auftrag §5: Eine versendete Bestätigung ist keine Zustimmung. |
| **Portalstorno zweistufig** (`portal_cancellation_requested_at`, `CancelBooking::confirmOnPortal`). | Abnahme 5.5: erst storniert, wenn im Portal wirksam; nichts wird still freigegeben. |
| **A6 ist ein `Booking`** mit `intake = internal`, `internal_kind`, Quelle `internal`; das Profil setzt Unterlagen, Zahlungen und Gastmails fest auf `Responsibility::Nobody`. | Ein Vorgangskern, keine zweite Verwaltung. Die Sperrliste bleibt nur für Altbestand und Portalsperren. |
| **`bookings.export_uid`** für übernommene Sperren. | Der Portalexport bleibt identisch (Abnahme 6.3). |
| **Kurabgabe als `QuoteLineType::TouristTax`**, Satz an der Wohnung. | Empfehlung B1 und Auftrag: gepflegter Satz, Befreiung manuell, keine Rechtslogik. |
| **Befehle melden Fehler eines Mandanten sichtbar.** Der `TenantRunner` protokolliert Fehler nur; die Übernahmebefehle prüfen deshalb die Zahl der erfolgreichen Läufe. | Beim Test gefunden: Ohne diese Prüfung meldete ein Fehler „keine Sperren“. |
---
## 4. Erfüllte Abnahmekriterien
| ID | Kriterium | Nachweis | Ergebnis |
|---|---|---|---|
| 5.1 | Änderung nach Buchung (A1) mit Folgenvorschau; danach Kalender, Portalaufgaben, Zahlungsplan, Verlauf | T07; Screenshot `Abnahme/2026-11-01/T07-aendern-folgen.png` | erfüllt |
| 5.2 | Änderung extern (A4) mit Portalbetrag, keine Neuberechnung | `ChangeBooking::price` (Portalzweig); Dialogfeld „Neuer Gesamtpreis laut Portal“ | erfüllt (kein eigener Durchgangstest; durch T04/T11 und Vorschaulogik abgedeckt) |
| 5.3 | Abbruch unverbindlich | T08 (Anfrage) | erfüllt |
| 5.4 | Abbruch verbindlich mit Initiator, Grund, Kosten, Erstattung | T08 (eigene Buchung) | erfüllt |
| 5.5 | Abbruch extern: Portalaufgabe, erst storniert nach Wirksamkeit | T08 (Portalbuchung), `PortalBookingTest` | erfüllt |
| 5.6 | Storno durch Gast im selben Weg | bestehender `CancellationPolicyTest`, Aufgabe → „Stornieren …“ | erfüllt |
| 6.1 | Private Überlassung mit Gästen, Leistungen, Kurabgabe, ohne Vertrag/Bewertung/Marketing | T09; Screenshots T09 | erfüllt |
| 6.2 | Wartungssperre, verlängern, aufheben ohne Storno | T10; Screenshot T10 | erfüllt |
| 6.3 | Bestandsmigration, Export identisch | Test `test_existing_manual_blocks_become_cases_without_changing_the_portal_calendar` | erfüllt |
| 8.1 | R09 exakt erfassbar, nichts erfunden oder doppelt | T11; Screenshot T11 | erfüllt |
| 8.2 | Bezahlt laut Portal ≠ eingegangen; offen nur beim Einziehenden | T11, T04 | erfüllt |
---
## 5. Tests und verbleibende Risiken
- **Automatisiert:** 685 Tests, 3889 Zusicherungen, alle grün. Darunter T01–T14 und 6.3 als Durchgangstests über die echten Dialoge (Livewire) und die Gast-Links (HTTP).
- **Browser:** Chromium mit Zwei-Faktor-Anmeldung auf einer Kopie der lokalen Datenbank. Geprüft: Ändern mit Folgen, R09-Übersicht, Neu-Dialog Besuch, Familienbesuch, Sperre aufheben, Wirksame Einstellungen, Gastseite Änderungsvorschlag. Keine Konsolenfehler.
- **Gefunden und behoben:**
- A6 zeigte „Über: internal“;
- A6 zeigte den Schalter „Sie geben frei“ und eine Vorlage;
- Vergabe der Vorgangsnummer bei der Bestandsübernahme;
- verschluckte Fehler in Übernahmebefehlen;
- fehlende Imports durch Windows-Zeilenenden.
**Risiken:**
- Bei Portalzahlung springt der Status auf „Anzahlung erhalten / bezahlt“, sobald „laut Portal bezahlt“ eingetragen ist. Im Verlauf steht dann „Anzahlung eingegangen“, obwohl kein Geld auf unserem Konto ist. Die Übersicht ist korrekt, der Statusname missverständlich (→ §7).
- Ein Änderungsvorschlag reserviert die neuen Nächte nicht. Bei der Annahme wird die Verfügbarkeit neu geprüft und gegebenenfalls freundlich abgelehnt.
- Für die Änderungsbestätigung und die Aufenthaltsbestätigung ist die Mail jeweils eine Arbeitsfassung; sie braucht eine Prüfung bzw. Freigabe durch den Betreiber.
- Die Migration auf MariaDB ist nicht geprüft (wie schon bei den Paketen 1–4).
- Ein Testsystem wurde nicht genutzt; es gibt keine Deployment-Freigabe.
---
## 6. Migrationsbedarf und Auswirkungen auf Bestandsdaten
- Die Migration `2026_11_04_090000_create_amounts_changes_and_internal_cases` ist rein additiv. Bestehende Zahlungen werden zu „Gast an uns“.
- **Manuelle Sperren:** `php artisan cases:adopt-blocks` zuerst als Vorschau, dann mit `--apply`; vorher eine Datenbanksicherung. Der Bericht liegt unter `storage/app/private/block-adoptions/`, die Rücknahme geht mit `--revert`. Ohne diesen Lauf bleiben die Altsperren wie bisher wirksam; neue Sperren entstehen nur noch als A6-Vorgang.
- Portalbuchungen, die schon storniert wurden, bleiben storniert. Die neue Zweistufigkeit gilt nur für künftige Stornierungen.
---
## 7. Noch erforderliche fachliche Entscheidungen
| Frage | Vorschlag | Bis dahin |
|---|---|---|
| **Statusname bei Portalzahlung:** Soll „laut Portal bezahlt“ den Status „Anzahlung erhalten/Bezahlt“ setzen? | Eigene Bezeichnung „laut Portal bezahlt“ oder keinen Statuswechsel. Gehört fachlich zum Abschluss-Gate B4 (Paket 9). | Statuswechsel wie bei Gastzahlungen. |
| **B3 Änderung nach Verbindlichkeit:** Wann ist ein Vorschlag mit Zustimmung Pflicht (z. B. bei Preiserhöhung)? | Beide Wege sind da. Eine Pflichtregel braucht eine fachliche bzw. rechtliche Entscheidung. | Die Vermieterin wählt den Weg. |
| **Texte:** Änderungsbestätigung, Änderungsvorschlag, Aufenthaltsbestätigung | Prüfen und freigeben (Aufenthaltsbestätigung unter So arbeite ich › Dokumente). | Arbeitsfassungen. |
| **Kurabgabe-Satz** je Wohnung | Den Satz der Gemeinde eintragen (Wohnung › Preise). | Keine Berechnung ohne Satz. |
| **B1, B4, B5** | Unverändert offen; B1 ist mit dem gepflegten Satz praktisch beantwortet. | – |
Pakete 7 und 9 wurden nicht begonnen.
+2
View File
@@ -1,5 +1,7 @@
# Projektstand
**Pakete 8, 5 und 6 der Prozessarchitektur v0.10 (01.11.2026, Branch `feature/abwicklung`, nicht ausgeliefert):** **Beträge und Zahlungen** – Zahlungen mit Art (Gast an uns / laut Portal ans Portal / Auszahlung Portal / Erstattung), Portalbeträge als Angaben mit Quelle (`case_amounts`), Übersicht `App\Pricing\CaseMoney` trennt Gastforderung, Portalzahlung, Auszahlung und Kontoeingang; R09 exakt erfassbar. **Ändern und Beenden** – `ChangeBooking` mit Folgenvorschau, „mit dem Gast vereinbart“ (Grundlage, Zeitpunkt) oder „dem Gast vorschlagen“ (signierter Link, Annahme mit Nachweis); ein Stornoweg mit Initiator, Grund, Kosten- und Erstattungsaufgabe; Portalbuchungen erst storniert, wenn im Portal bestätigt. **A6** – Eigene Nutzung, Besuch und Sperre als Vorgang („Neu“, Belegungsplan „+ eintragen“), Kurabgabe als Position (Satz an der Wohnung), Aufenthaltsbestätigung ohne Mietvertrag, keine Mahnung/Bewertung/Marketing; Altsperren per `cases:adopt-blocks` (Vorschau, `--apply`, `--revert`, Export identisch). **System › Wirksame Einstellungen** zeigt je Eingangsweg und Vorgang die angewandten Werte. **685 Tests grün** (inkl. Abnahmekatalog T01–T14). Dokumente: [UMSETZUNGSERGEBNIS_P5_P6_P8](Prozessarchitektur/UMSETZUNGSERGEBNIS_P5_P6_P8.md), [END_TO_END_ABNAHME](Prozessarchitektur/END_TO_END_ABNAHME.md), [KONFIGURATION_UND_WIRKSAMKEIT](Prozessarchitektur/KONFIGURATION_UND_WIRKSAMKEIT.md).
**Ein Eingang für alle Kanäle – Paket 4 der Prozessarchitektur v0.10 (03.11.2026, Branch `feature/eingang`, nicht ausgeliefert):** Portalbuchungen und -anfragen kommen über einen Eingang (`App\Channels\Intake\PortalIntake`, aufgerufen nach jedem Kalenderabgleich und aus `ProcessPortalMail`): sicher erkannte Buchungen (Buchungsmail mit Nummer, Kalenderregel „Reservierung dieses Portals“) werden zum Vorgang ohne Angebot/Annahme, Anfrage-Mails zur A2-Anfrage; Dubletten über Buchungsnummer → gleiches Portal mit gleichen Nächten → Spiegelung, nie nach bloßer Überschneidung; Unsicheres wird unter „Zu erledigen“ geklärt („Klären: Was ist das?“). Stornomail, verschwundener oder geänderter Kalendereintrag eines gebuchten Vorgangs → Aufgabe am Vorgang, keine stille Stornierung. Schalter je Kanal `channels.case_intake` (Aus = Standard, Beobachten, Anlegen, Anlegen + weiter); Eingangsprotokoll (System › Eingangsprotokoll, `channels:intake-report`); Bestandsübernahme `channels:adopt-occupations` (Vorschau, `--apply`, `--revert`). Portalaufgaben mit Nachweisstufe (veranlasst / im Portal gesehen / bestätigt). **662 Tests grün**, Browserprüfung durchgeführt. Ergebnis und Aktivierungsweg: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P4.md).
**Dokumentenzusammenstellung und Vorlagensteuerung – Paket 3 der Prozessarchitektur v0.10 (02.11.2026, Branch `feature/vorgang`, nicht ausgeliefert):** Vor jedem Dokument dieselbe Zusammenstellung (`App\Documents\DocumentComposer`, Ansicht `filament/document-composition`): Empfänger, Zeitraum, Preis mit Herkunft, Leistungen, Stornoregel, Vorlage mit Herkunft, Anlagen, Hinweise (fehlt / bitte prüfen / Info), E-Mail- und PDF-Vorschau. Dokumentart je Vorgang automatisch (`App\Enums\DocumentKind`): Anfrage → Angebot mit Annahmelink, eigene Buchung → Bestätigung mit Mietvertrag, beim Portal verbindlich (A3/A4) → **Buchungsunterlagen ohne Annahmelink** (`BookingDocumentation`). Unterlagen verbindlicher Vorgänge nur über `SendBookingDocuments` (automatisch nur ohne Prüfpunkte, von Hand mit bestätigten Hinweisen, einmalig per Sperre); Angebote mit `expected_version` gegen Doppelversand; ohne Vorreservierung (Hold 0) kein Angebot ohne ausdrückliche Entscheidung. Vorlagen haben Freigabe und „gibt nur Portalbedingungen wieder“ (entfallen bei Textänderung); die Buchungsunterlagen extern sind eine Arbeitsfassung bis zur Freigabe unter So arbeite ich › Dokumente. **648 Tests grün**, Browserprüfung durchgeführt. Ergebnis, offene Freigaben (FeWo-direkt-Vorlage FW-01, Unterlagentext) und Empfehlung Paket 4: [docs/Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md](Prozessarchitektur/UMSETZUNGSERGEBNIS_P3.md).
+42
View File
@@ -0,0 +1,42 @@
@extends('theme::layouts.app', ['title' => 'Änderung Ihrer Buchung'])
@push('head')
<meta name="robots" content="noindex">
@endpush
@section('content')
<div class="mx-auto max-w-3xl px-4 py-14 sm:px-8">
<p class="eyebrow">Buchung {{ $booking->reference }}</p>
<h1 class="heading-display">Vorschlag zur Änderung</h1>
<p class="mt-2 text-muted">{{ $booking->property->name }} · für {{ $booking->guestName() }}</p>
@if (session('change.success'))
<div class="mt-8 rounded border border-accent bg-surface p-5" role="status">{{ session('change.success') }}</div>
@endif
@if (session('change.error'))
<div class="mt-8 rounded border border-line bg-surface p-5" role="alert">{{ session('change.error') }}</div>
@endif
<ul class="mt-8 list-disc space-y-1 pl-6">
@foreach (explode(' · ', $change->summary()) as $line)
<li>{{ $line }}</li>
@endforeach
</ul>
@if ($change->status === \App\Enums\ChangeStatus::Proposed && ! session('change.success'))
<p class="mt-6 text-muted">Bis zu Ihrer Zustimmung bleibt Ihre Buchung unverändert. Der Vorschlag gilt bis {{ $change->expires_at?->format('d.m.Y') }}.</p>
<form method="post" action="{{ URL::temporarySignedRoute('changes.accept', $change->expires_at ?? now()->addDay(), ['change' => $change]) }}" class="mt-6">
@csrf
<label class="flex items-start gap-3"><input type="checkbox" name="agree" value="1" class="mt-1"> <span>Ich bin mit dieser Änderung einverstanden.</span></label>
@error('agree')<p class="mt-2 text-sm">{{ $message }}</p>@enderror
<button type="submit" class="btn-accent mt-4 w-full sm:w-auto">Änderung annehmen</button>
</form>
<form method="post" action="{{ URL::temporarySignedRoute('changes.decline', $change->expires_at ?? now()->addDay(), ['change' => $change]) }}" class="mt-3">
@csrf
<button type="submit" class="text-sm text-muted underline hover:text-ink">Ablehnen</button>
</form>
@elseif (! session('change.success'))
<div class="mt-8 rounded border border-line bg-surface p-5">Dieser Vorschlag ist {{ $change->status->getLabel() }}.</div>
@endif
</div>
@endsection
@@ -0,0 +1,58 @@
{{-- Prices and payments of a case, kept apart by who owes whom (package 8). --}}
@php
/** @var \App\Pricing\CaseMoney $money */
$euro = fn (?int $cents): string => $cents === null ? 'noch nicht bekannt' : \App\Support\Money::format($cents);
$row = 'display:flex;justify-content:space-between;gap:1rem;padding:.35rem 0;border-bottom:1px solid rgba(128,128,128,.15)';
$muted = 'color:#6b7280;font-size:.85rem';
$collector = $money->collector();
$payout = $money->payout();
$positions = $money->positions();
@endphp
<div style="font-size:.95rem">
<div style="{{ $row }}"><span><strong>Vereinbarter Gesamtpreis</strong> <span style="{{ $muted }}">{{ $money->totalSource() }}</span></span><strong>{{ $euro($money->total()) }}</strong></div>
@if ($collector === \App\Enums\Responsibility::Landlord)
<div style="{{ $row }}"><span>Vom Gast an uns gezahlt</span><span>{{ $euro($booking->paidToUs()) }}</span></div>
<div style="{{ $row }}"><span>Noch offen – zahlt der Gast an uns</span><span style="color:{{ $money->openForUs() > 0 ? '#dc2626' : '#15803d' }};font-weight:600">{{ $euro($money->openForUs()) }}</span></div>
@elseif ($collector === \App\Enums\Responsibility::Portal)
<div style="{{ $row }}"><span>Zahlung des Gastes läuft über {{ $booking->processChannel()?->name ?? 'das Portal' }}</span><span style="{{ $muted }}">keine Mahnung durch uns</span></div>
<div style="{{ $row }}"><span>Laut Portal vom Gast bezahlt</span><span>{{ $euro($booking->paidViaPortal()) }}</span></div>
<div style="{{ $row }}"><span>Laut Portal noch beim Gast offen</span><span>{{ $euro($money->openAtPortal()) }}</span></div>
@foreach ($money->installmentsDue() as $installment)
<div style="{{ $row }}"><span style="{{ $muted }}">Rate laut Portal fällig{{ $installment->due_on ? ' am '.$installment->due_on->format('d.m.Y') : '' }}</span><span style="{{ $muted }}">{{ $euro($installment->amount) }}</span></div>
@endforeach
<div style="{{ $row }}"><span>Auszahlung an uns angekündigt</span>
<span>{{ $payout['values'] === [] ? 'noch keine Angabe' : implode(' bzw. ', array_map($euro, $payout['values'])) }}</span></div>
@if ($payout['difference'] > 0)
<div style="{{ $row }}"><span style="color:#b45309">Die Angaben zur Auszahlung weichen um {{ $euro($payout['difference']) }} voneinander ab – ungeklärt.</span><span></span></div>
@endif
<div style="{{ $row }}"><span>Auszahlung tatsächlich erhalten</span><span>{{ $euro($payout['received']) }}</span></div>
@if ($payout['outstanding'] !== null)
<div style="{{ $row }}"><span>Noch auszuzahlen (laut Ankündigung)</span><span>{{ $euro($payout['outstanding']) }}</span></div>
@endif
@else
<div style="{{ $row }}"><span>Bezahlt</span><span>{{ $euro($booking->paidAmount()) }}</span></div>
<div style="{{ $row }}"><span style="{{ $muted }}">Keine Zahlungserinnerungen bei eigener Nutzung / privatem Aufenthalt.</span><span></span></div>
@endif
<div style="{{ $row }}"><span>Auf unserem Konto eingegangen</span><span>{{ $euro($money->receivedOnAccount()) }}</span></div>
@if ($positions['positions']->isNotEmpty() || $money->commissions()->isNotEmpty() || $payout['announcements']->isNotEmpty())
<details style="margin-top:.6rem">
<summary style="cursor:pointer;font-weight:600">Einzelangaben laut Portal</summary>
<div style="margin-top:.4rem">
@foreach ($positions['positions'] as $position)
<div style="{{ $row }}"><span>{{ $position->title() }} <span style="{{ $muted }}">{{ $position->source }}{{ $position->stated_on ? ', '.$position->stated_on->format('d.m.Y') : '' }}</span></span><span>{{ $euro($position->amount) }}</span></div>
@endforeach
@if ($positions['positions']->isNotEmpty())
<div style="{{ $row }}"><span style="{{ $muted }}">Summe der Positionen</span><span style="{{ $muted }}">{{ $euro($positions['sum']) }}{{ $positions['difference'] === 0 ? ' = Gesamtpreis' : ($positions['difference'] !== null ? ' – Abweichung zum Gesamtpreis '.$euro($positions['difference']) : '') }}</span></div>
@endif
@foreach ($money->commissions() as $commission)
<div style="{{ $row }}"><span>{{ $commission->title() }} <span style="{{ $muted }}">{{ $commission->source }} · trägt der Vermieter, kein Betrag des Gastes</span></span><span>{{ $euro($commission->amount) }}</span></div>
@endforeach
@foreach ($payout['announcements'] as $announcement)
<div style="{{ $row }}"><span>{{ $announcement->title() }} <span style="{{ $muted }}">{{ $announcement->source }}{{ $announcement->stated_on ? ', '.$announcement->stated_on->format('d.m.Y') : '' }}{{ $announcement->note ? ' · '.$announcement->note : '' }}</span></span><span>{{ $euro($announcement->amount) }}</span></div>
@endforeach
</div>
</details>
@endif
</div>
@@ -0,0 +1,24 @@
{{-- What a change of a booking would do, before it is saved (package 5). --}}
@php
$box = fn (string $color): string => "border-left:4px solid {$color};background:rgba(128,128,128,.06);padding:.6rem .8rem;border-radius:.375rem;margin-bottom:.5rem";
$euro = fn (?int $cents): string => $cents === null ? 'noch nicht bekannt' : \App\Support\Money::format($cents);
@endphp
<div style="font-size:.95rem">
@if ($preview['errors'] !== [])
<div style="{{ $box('#dc2626') }}"><strong>So nicht möglich</strong>
<ul style="margin:.3rem 0 0 1.1rem;list-style:disc">@foreach ($preview['errors'] as $error)<li>{{ $error }}</li>@endforeach</ul>
</div>
@endif
<div style="{{ $box('#2563eb') }}"><strong>Das ändert sich</strong>
<ul style="margin:.3rem 0 0 1.1rem;list-style:disc">@foreach ($preview['summary'] as $line)<li>{{ $line }}</li>@endforeach</ul>
</div>
<div style="{{ $box('#6b7280') }}"><strong>Folgen</strong>
<ul style="margin:.3rem 0 0 1.1rem;list-style:disc">
@foreach ($preview['calendar'] as $line)<li>{{ $line }}</li>@endforeach
@foreach ($preview['portals'] as $line)<li>{{ $line }}</li>@endforeach
<li>Preis: {{ $euro($preview['price']['before']) }} → {{ $euro($preview['price']['after']) }}@if ($preview['price']['difference']) ({{ $preview['price']['difference'] > 0 ? '+' : '' }}{{ $euro($preview['price']['difference']) }})@endif · {{ $preview['price']['source'] }}</li>
@foreach ($preview['payment'] as $line)<li>{{ $line }}</li>@endforeach
@if ($preview['confirmation'])<li>Auf Wunsch geht eine Bestätigung der Änderung an den Gast. Sie informiert nur – die Zustimmung des Gastes ist unten festzuhalten.</li>@endif
</ul>
</div>
</div>
@@ -0,0 +1,72 @@
<x-filament-panels::page>
@php
$cell = 'padding:.4rem .5rem;border-bottom:1px solid rgba(128,128,128,.2);vertical-align:top';
$muted = 'color:#6b7280;font-size:.8rem';
$levels = [\App\Process\ProcessProfile::SYSTEM => 'Grundeinstellung', \App\Process\ProcessProfile::TENANT => 'Ihr Standard', \App\Process\ProcessProfile::PROPERTY => 'Wohnung', \App\Process\ProcessProfile::CHANNEL => 'Portal', \App\Process\ProcessProfile::CASE_TYPE => 'fest (A6)'];
@endphp
<x-filament::section heading="So lesen Sie diese Übersicht" collapsible collapsed>
<p style="font-size:.9rem">Jede Spalte ist ein Eingangsweg. Jede Zelle zeigt den Wert, der für einen <strong>neuen</strong> Vorgang auf diesem Weg gilt, und darunter, woher er kommt: Grundeinstellung → Ihr Standard (So arbeite ich) → Abweichung der Wohnung → Abweichung des Portals für Anfragen bzw. feste Buchungen. Laufende Vorgänge behalten ihr beim Eingang festgehaltenes Profil – das zeigt der Abschnitt „Einen Vorgang prüfen“. Ändern lassen sich die Werte nur an ihrer Stelle (rechte Spalte).</p>
</x-filament::section>
@foreach ($this->matrix() as $block)
<x-filament::section :heading="$block['property']->name">
<div style="overflow-x:auto">
<table style="width:100%;border-collapse:collapse;font-size:.85rem">
<thead>
<tr>
<th style="{{ $cell }};text-align:left">Einstellung</th>
@foreach ($block['columns'] as $column)
<th style="{{ $cell }};text-align:left">{{ $column['label'] }}<div style="{{ $muted }}">Vorgangsart {{ strtoupper($column['profile']->caseType->value) }}</div></th>
@endforeach
<th style="{{ $cell }};text-align:left">Wo einstellen?</th>
</tr>
</thead>
<tbody>
@foreach ($this->settings() as $setting)
<tr>
<td style="{{ $cell }}">{{ $setting->question() }}</td>
@foreach ($block['columns'] as $column)
@php($source = $column['profile']->source($setting))
<td style="{{ $cell }}">
<span style="{{ in_array($source, [\App\Process\ProcessProfile::SYSTEM], true) ? '' : 'font-weight:600' }}">{{ $this->describe($setting, $column['profile']) }}</span>
<div style="{{ $muted }}">{{ $levels[$source] ?? $source }}</div>
</td>
@endforeach
<td style="{{ $cell }};{{ $muted }}">{{ \App\Filament\Pages\EffectiveSettings::where($setting) }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</x-filament::section>
@endforeach
<x-filament::section heading="Einen Vorgang prüfen">
<select wire:model.live="bookingId" style="width:100%;max-width:32rem;border:1px solid rgba(128,128,128,.4);border-radius:.375rem;padding:.4rem">
<option value="">– Vorgang wählen –</option>
@foreach ($this->cases() as $id => $label)
<option value="{{ $id }}">{{ $label }}</option>
@endforeach
</select>
@if ($booking = $this->booking())
@php($profile = $booking->process())
<p style="margin-top:.8rem;font-size:.9rem"><strong>{{ $booking->reference }}</strong> · {{ $booking->caseType()->value }} – {{ $booking->caseType()->getLabel() }} · {{ $booking->intake?->getLabel() }} · Profil festgehalten am {{ $profile->frozenAt ? \Carbon\CarbonImmutable::parse($profile->frozenAt)->format('d.m.Y H:i') : '–' }} ({{ \App\Process\ProcessProfile::sourceLabel($profile->origin) }})</p>
<table style="width:100%;border-collapse:collapse;font-size:.85rem;margin-top:.5rem">
@foreach ($this->settings() as $setting)
<tr>
<td style="{{ $cell }}">{{ $setting->question() }}</td>
<td style="{{ $cell }};font-weight:600">{{ $this->describe($setting, $profile) }}</td>
<td style="{{ $cell }};{{ $muted }}">{{ in_array($setting, \App\Process\ProcessProfile::LIVE, true) ? 'wird beim Dokument festgehalten' : \App\Process\ProcessProfile::sourceLabel($profile->source($setting)) }}</td>
</tr>
@endforeach
<tr>
<td style="{{ $cell }}">Bearbeitung dieses Vorgangs (wirksam)</td>
<td style="{{ $cell }};font-weight:600">{{ $booking->processingMode()->getLabel() }}</td>
<td style="{{ $cell }};{{ $muted }}">{{ $booking->processing_mode !== null ? 'für diesen Vorgang umgestellt' : 'aus dem Profil' }}</td>
</tr>
</table>
@endif
</x-filament::section>
</x-filament-panels::page>
@@ -33,6 +33,7 @@
<x-filament::button wire:click="moveMonth(-1)" color="gray" aria-label="Vorheriger Monat">← Zurück</x-filament::button>
<x-filament::button wire:click="moveMonth(1)" color="gray" aria-label="Nächster Monat">Weiter →</x-filament::button>
<x-filament::button tag="a" :href="\App\Filament\Resources\Bookings\BookingResource::getUrl()" color="gray">Alle Anfragen & Buchungen</x-filament::button>
<x-filament::button tag="a" :href="\App\Filament\Resources\Bookings\BookingResource::getUrl('create', ['kind' => 'own_use'])" color="gray">Eigene Nutzung / Sperre eintragen</x-filament::button>
<x-filament::button tag="a" :href="\App\Filament\Resources\PortalOccupations\PortalOccupationResource::getUrl()" color="warning">Ungeklärte Belegungen</x-filament::button>
</div>
@if ($calendar)
@@ -52,7 +53,7 @@
@foreach ($calendar['days'] as $day)
<section class="occupancy-day {{ $day['free'] ? 'is-free' : '' }} {{ $day['overlap'] ? 'is-overlap' : '' }}" wire:key="night-{{ $propertyId }}-{{ $day['date']->toDateString() }}" aria-label="{{ $day['date']->format('d.m.Y') }}">
<h3>{{ $day['date']->locale('de')->translatedFormat('D, d.m.') }}</h3>
@if ($day['free'])<span>Frei</span>@endif
@if ($day['free'])<span>Frei</span> <a href="{{ \App\Filament\Resources\Bookings\BookingResource::getUrl('create', ['kind' => 'block', 'von' => $day['date']->toDateString(), 'bis' => $day['date']->addDay()->toDateString(), 'wohnung' => $propertyId]) }}" style="font-size:.8rem;text-decoration:underline" title="Eigene Nutzung, Besuch oder Sperre ab diesem Tag eintragen">+ eintragen</a>@endif
@if ($day['overlap'])<p class="occupancy-warning">Mehrere führende Einträge – prüfen</p>@endif
@foreach ($day['occupations'] as $event)
<a class="occupancy-event kind-{{ $event['kind'] }}" href="{{ $event['url'] }}">
@@ -0,0 +1,33 @@
<x-mail::message :site="$booking->website()" :message="$message ?? null">
# Änderung Ihrer Buchung
Guten Tag {{ $booking->guest->full_name }},
wie mit Ihnen vereinbart ({{ $change->basis?->getLabel() }}{{ $change->agreed_at ? ' am '.$change->agreed_at->format('d.m.Y') : '' }}), gilt für Ihre Buchung der **{{ $booking->property->name }}** ab sofort:
**Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}<br>
**Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}<br>
@if ($booking->guests)
**Personen:** {{ $booking->guests }}<br>
@endif
**Buchungsnummer:** {{ $booking->reference }}
@foreach ($change->summary() !== '' ? explode(' · ', $change->summary()) : [] as $line)
- {{ $line }}
@endforeach
@if ($booking->total !== null)
**Gesamtpreis:** {{ \App\Support\Money::format($booking->total) }}
@endif
@if ($booking->wantsPaymentTasks() && $booking->openAmount() > 0)
Noch offen: **{{ \App\Support\Money::format($booking->openAmount()) }}**@if ($booking->balance_due_on), fällig bis {{ $booking->balance_due_on->format('d.m.Y') }}@endif.
@include('mail.partials.bank')
@endif
Falls etwas nicht unserer Vereinbarung entspricht, antworten Sie bitte einfach auf diese E-Mail.
Herzliche Grüße<br>
{{ config('fewo.owner.name') }}
</x-mail::message>
@@ -0,0 +1,9 @@
<x-mail::message>
# {{ $accepted ? 'Änderung angenommen' : 'Änderung abgelehnt' }}
{{ $change->booking->guestName() }} hat den Änderungsvorschlag für {{ $change->booking->reference }} {{ $accepted ? 'angenommen – die Änderung ist jetzt wirksam' : 'abgelehnt – die Buchung bleibt unverändert' }}.
@foreach (explode(' · ', $change->summary()) as $line)
- {{ $line }}
@endforeach
</x-mail::message>
@@ -0,0 +1,20 @@
<x-mail::message :site="$booking->website()" :message="$message ?? null">
# Vorschlag zur Änderung Ihrer Buchung
Guten Tag {{ $booking->guest->full_name }},
für Ihre Buchung **{{ $booking->reference }}** der **{{ $booking->property->name }}** schlagen wir folgende Änderung vor:
@foreach (explode(' · ', $change->summary()) as $line)
- {{ $line }}
@endforeach
Bis zu Ihrer Zustimmung bleibt Ihre Buchung unverändert. Bitte sagen Sie uns **bis {{ $change->expires_at?->format('d.m.Y') }}**, ob Sie einverstanden sind:
<x-mail::button :url="$url">
Änderung ansehen und annehmen
</x-mail::button>
Herzliche Grüße<br>
{{ config('fewo.owner.name') }}
</x-mail::message>
@@ -0,0 +1,23 @@
{{-- Working draft (package 6): released by the landlord under "So arbeite ich › Dokumente" before it is sent without confirmation. --}}
<x-mail::message :site="$booking->website()" :message="$message ?? null">
# Ihr Aufenthalt in der {{ $booking->property->name }}
Guten Tag {{ $booking->guest->full_name }},
hiermit bestätigen wir Ihren Aufenthalt:
**Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}<br>
**Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}<br>
@if ($booking->guests)
**Personen:** {{ $booking->guests }}<br>
@endif
@if ($booking->total)
**Vereinbarter Betrag:** {{ \App\Support\Money::format($booking->total) }}
@endif
Die Bestätigung finden Sie auch als PDF im Anhang.
Herzliche Grüße<br>
{{ config('fewo.owner.name') }}
</x-mail::message>
+5
View File
@@ -1,5 +1,6 @@
<?php
use App\Http\Controllers\ChangeController;
use App\Http\Controllers\ChannelController;
use App\Http\Controllers\MarketingConsentController;
use App\Http\Controllers\OfferController;
@@ -22,6 +23,10 @@
Route::post('/angebot/{booking}/freigeben/bestaetigen', [SelfServiceController::class, 'release'])->name('reservations.release.confirm')->middleware('throttle:10,1');
Route::get('/angebot/{booking}/storno', [SelfServiceController::class, 'showCancel'])->name('bookings.cancel')->middleware('throttle:30,1');
Route::post('/angebot/{booking}/storno/bestaetigen', [SelfServiceController::class, 'cancel'])->name('bookings.cancel.confirm')->middleware('throttle:10,1');
// A change of a booking the guest has to agree to (package 5); under /angebot/ so the requested host is kept.
Route::get('/angebot/aenderung/{change}', [ChangeController::class, 'show'])->name('changes.show')->middleware('throttle:30,1');
Route::post('/angebot/aenderung/{change}/annehmen', [ChangeController::class, 'accept'])->name('changes.accept')->middleware('throttle:10,1');
Route::post('/angebot/aenderung/{change}/ablehnen', [ChangeController::class, 'decline'])->name('changes.decline')->middleware('throttle:10,1');
});
Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1');
+4 -8
View File
@@ -8,14 +8,13 @@
use App\Filament\Pages\PricesAndOffers;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Properties\PropertyResource;
use App\Filament\Resources\Users\Pages\ListUsers;
use App\Filament\Resources\Users\UserResource;
use App\Models\BlockedPeriod;
use App\Models\Property;
use App\Models\Season;
use App\Models\User;
use Filament\Actions\CreateAction;
use Filament\Actions\Testing\TestAction;
use Filament\Facades\Filament;
use Filament\Livewire\Topbar;
@@ -110,17 +109,14 @@ public function test_user_menu_switches_the_mode(): void
$this->assertSame(AdminMode::Expert, $user->fresh()->adminMode());
}
public function test_blocked_periods_can_be_managed_in_their_own_list(): void
public function test_the_block_list_leads_to_a_new_block_case(): void
{
$property = Property::factory()->create();
$this->actingAs(User::factory()->role(UserRole::Rentals)->create());
$this->get(BlockedPeriodResource::getUrl('index'))->assertOk();
Livewire::test(ManageBlockedPeriods::class)
->callAction(CreateAction::class, ['property_id' => $property->id, 'starts_on' => '2026-12-01', 'ends_on' => '2026-12-05', 'reason' => 'Eigennutzung'])
->assertHasNoFormErrors();
$this->assertSame(['manual', 'Eigennutzung'], [BlockedPeriod::sole()->source, BlockedPeriod::sole()->reason]);
->assertActionVisible('createCase')
->assertActionHasUrl('createCase', BookingResource::getUrl('create', ['kind' => 'block']));
}
public function test_administrator_can_reset_the_two_factor_login_of_another_user(): void
+2 -2
View File
@@ -313,7 +313,7 @@ public function test_the_landlord_releases_the_booking_documentation_on_the_sett
$this->assertSame('Ingrid', DocumentReleases::decision(DocumentKind::ExternalRecord)['by']);
}
/** A6 is prepared: a private stay gets a confirmation that is no rental contract, and it cannot be sent yet. */
/** A6: a private stay gets a confirmation that is no rental contract; its text is a working draft until released. */
public function test_a_private_stay_confirmation_is_prepared_without_a_rental_contract(): void
{
$booking = $this->request();
@@ -323,7 +323,7 @@ public function test_a_private_stay_confirmation_is_prepared_without_a_rental_co
$this->assertSame(DocumentKind::StayConfirmation, $composition->kind);
$this->assertFalse($composition->kind->containsContract());
$this->assertStringContainsString('späteren Ausbauschritt', implode(' ', $composition->blockers()));
$this->assertStringContainsString('Arbeitsfassung', implode(' ', $composition->toConfirm()));
[$view, $data] = app(RentalContract::class)->view($booking, DocumentKind::StayConfirmation);
$html = view($view, $data)->render();
$this->assertStringContainsString('nicht um einen Mietvertrag', $html);
+514
View File
@@ -0,0 +1,514 @@
<?php
namespace Tests\Feature;
use App\Actions\CreateReservation;
use App\Actions\ProcessPortalMail;
use App\Actions\ProvideGuestContact;
use App\Actions\RecordPayment;
use App\Actions\RequestReviews;
use App\Actions\SendBookingReminders;
use App\Actions\SyncChannel;
use App\Channels\ICal\ICalFeed;
use App\Channels\Mail\PortalMail;
use App\Documents\DocumentReleases;
use App\Enums\AdminMode;
use App\Enums\AmountKind;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\CaseIntakeMode;
use App\Enums\CaseType;
use App\Enums\ChangeBasis;
use App\Enums\ChangeStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\InternalKind;
use App\Enums\PaymentKind;
use App\Enums\PaymentMethod;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Filament\Pages\EffectiveSettings;
use App\Filament\Resources\Bookings\Pages\CreateBooking;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Mail\BookingCancelled;
use App\Mail\BookingChanged;
use App\Mail\BookingConfirmed;
use App\Mail\ChangeProposed;
use App\Mail\OfferMade;
use App\Mail\ReviewRequest;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\Extra;
use App\Models\Property;
use App\Models\User;
use App\Pricing\CaseMoney;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\ProcessSettings;
use App\Process\WorkList;
use App\Support\Content;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\Events\MessageSent;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Livewire\Livewire;
use Tests\TestCase;
/**
* The business acceptance catalogue (docs/Prozessarchitektur/END_TO_END_ABNAHME.md, T01–T14): every case is played
* through the way the landlord works – the "Neu" dialog, the case page and its actions, the guest's links – and checked
* by what she would see: the case, its next step, the calendar and portal tasks, the money and the mails.
*/
class EndToEndAcceptanceTest extends TestCase
{
use RefreshDatabase;
private Property $property;
private Channel $manualPortal;
/** What the portal calendars deliver (null: the portal cannot be reached). */
private ?string $feed = null;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
$this->property = Property::sole();
app(TenantContext::class)->set($this->property->tenant);
// A portal that has to be blocked by hand: every change of the calendar becomes a portal task.
$this->manualPortal = Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'booking_model' => 'inquiry', 'connector' => 'ical', 'import_enabled' => false, 'requires_manual_blocking' => true, 'export_enabled' => true, 'export_mode' => 'regular', 'status' => 'active']);
Mail::fake();
Storage::fake('local');
Http::fake(fn () => $this->feed === null ? Http::response('', 500) : Http::response($this->feed));
$this->withoutVite();
$this->actingAs(User::factory()->create(['name' => 'Ingrid', 'admin_mode' => AdminMode::Simple]));
}
/** T01 – own request, automatic: the offer goes out by itself and the case waits for the guest. */
public function test_t01_own_request_handled_automatically(): void
{
$this->releaseTexts();
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]);
$booking = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org']);
$this->assertSame([BookingStatus::OfferSent, CaseType::A1], [$booking->status, $booking->case_type]);
Mail::assertSent(OfferMade::class, 1);
$this->assertSame('acceptance', collect(CaseActivities::for($booking))->firstWhere('state.value', 'waiting')?->key);
$this->assertSame([], WorkList::items(), 'nothing for the landlord to do');
}
/** T02 – own request, manual: prepared, released by the landlord, accepted by the guest, confirmed automatically. */
public function test_t02_own_request_released_by_hand_and_accepted_by_the_guest(): void
{
Livewire::test(CreateBooking::class)
->fillForm(['kind' => BookingForm::INQUIRY, 'property_id' => $this->property->id, 'guests' => 2, 'arrival' => '2026-11-07', 'departure' => '2026-11-10', 'first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org', 'send_mails' => false])
->call('create')->assertHasNoFormErrors();
$booking = Booking::query()->sole();
$this->assertSame('Angebot prüfen und senden', WorkList::items()[0]['title']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('sendOffer')->arguments([]))
->assertNotified('Angebot gesendet');
$booking->refresh();
$this->post(URL::temporarySignedRoute('offers.accept', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]), ['terms' => '1'])->assertRedirect();
$booking->refresh();
$this->assertSame(BookingStatus::Confirmed, $booking->status);
$this->assertNotNull($booking->contract_path);
Mail::assertSent(BookingConfirmed::class, 1);
$this->assertSame(1, ChannelTask::query()->where('channel_id', $this->manualPortal->id)->count(), 'the manual portal is blocked');
}
/** T03 – missing guest data: one understandable task, then the case continues automatically. */
public function test_t03_missing_guest_data_becomes_a_task_and_the_case_continues(): void
{
$this->releaseTexts();
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic']]);
Livewire::test(CreateBooking::class)
->fillForm(['kind' => BookingForm::INQUIRY, 'property_id' => $this->property->id, 'guests' => 2, 'arrival' => '2026-11-07', 'departure' => '2026-11-10', 'first_name' => 'Paul', 'last_name' => 'Telefon', 'send_mails' => true])
->call('create')->assertHasNoFormErrors();
$booking = Booking::query()->sole();
$this->assertSame('E-Mail-Adresse des Gastes eintragen', WorkList::items()[0]['title']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('provideContact')->arguments([]), ['guest' => ['first_name' => 'Paul', 'last_name' => 'Telefon', 'email' => 'paul@example.org'], 'process' => ProvideGuestContact::AUTOMATIC, 'guest_confirmed' => false])
->assertNotified('Kontaktdaten gespeichert, Angebot gesendet');
$this->assertSame(BookingStatus::OfferSent, $booking->fresh()->status);
}
/** T04 – FeWo-direkt direct booking: one case, the portal's price, payments with the portal, no reminders. */
public function test_t04_fewo_direkt_booking_is_one_case_with_the_portal_price_and_portal_payments(): void
{
$fewo = $this->fewo();
$this->portalMail('Neue Buchung', "Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-7X3K9Q");
$booking = Booking::query()->sole();
$this->assertSame([CaseType::A4, IntakeKind::Booking, BookingStatus::Confirmed, 0], [$booking->case_type, $booking->intake, $booking->status, $booking->offer_version]);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'guests' => 2, 'stated_on' => '2026-10-22'])
->assertNotified('Beträge gespeichert');
$booking->refresh();
$this->assertSame(97951, $booking->total);
$this->assertSame(Responsibility::Portal, CaseMoney::of($booking)->collector());
$this->assertSame(0, CaseMoney::of($booking)->openForUs());
$this->travelTo(CarbonImmutable::parse('2026-12-01'));
app(SendBookingReminders::class)->handle();
$this->assertSame(0, BookingTask::query()->where('booking_id', $booking->id)->count(), 'no reminders of our own');
$this->assertSame($fewo->id, $booking->origin_channel_id);
}
/** T05 – Destination Solutions: binding on the portal, contract documents and payments by us. */
public function test_t05_destination_solutions_booking_with_our_documents_and_payments(): void
{
$ds = Channel::factory()->for($this->property)->create(['name' => 'Destination Solutions', 'booking_model' => 'portal_booking']);
Livewire::test(CreateBooking::class)
->fillForm(['kind' => BookingForm::EXTERNAL, 'property_id' => $this->property->id, 'arrival' => '2027-02-01', 'departure' => '2027-02-08', 'guests' => 2, 'channel_id' => $ds->id, 'portal_reference' => 'DS-4711', 'portal_total' => '840.00', 'first_name' => 'Hans', 'last_name' => 'Gast', 'email' => 'hans@example.org'])
->call('create')->assertHasNoFormErrors();
$booking = Booking::query()->sole();
$this->assertSame([CaseType::A3, 84000, 'DS-4711'], [$booking->case_type, $booking->total, $booking->portal_reference]);
$this->assertTrue($booking->wantsPaymentTasks());
$this->assertSame('sendDocuments', collect(CaseActivities::for($booking))->firstWhere('key', 'documents')->action);
app(RecordPayment::class)->handle($booking, (int) $booking->deposit, CarbonImmutable::today(), PaymentMethod::Transfer);
$this->assertSame(BookingStatus::DepositPaid, $booking->fresh()->status);
}
/** T06 – the same booking by mail and calendar stays one case. */
public function test_t06_duplicate_portal_reports_make_one_case(): void
{
$fewo = $this->fewo(['settings' => ['import_url' => 'https://portal.example/fewo.ics', 'email_senders' => 'fewo-direkt.de']]);
$fewo->forceFill(['ical_active_rules' => [['name' => 'Buchung', 'priority' => 10, 'enabled' => true, 'case_sensitive' => false, 'match' => 'all',
'conditions' => [['field' => 'SUMMARY', 'operator' => 'starts_with', 'value' => 'Reservation']], 'event_type' => 'portal_reservation', 'origin' => 'current',
'representation' => 'leading_candidate', 'extractions' => [['field' => 'DESCRIPTION', 'target' => 'booking_reference', 'method' => 'after', 'start' => 'Buchung ']]]]])->save();
$this->portalMail('Neue Buchung', "Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-7X3K9Q");
$this->feed = ("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Test//DE\r\nBEGIN:VEVENT\r\nUID:evt-1\r\nDTSTAMP:20261022T090000Z\r\nDTSTART;VALUE=DATE:20261207\r\nDTEND;VALUE=DATE:20261214\r\nSUMMARY:Reservation\r\nDESCRIPTION:Buchung HA-7X3K9Q\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n");
app(SyncChannel::class)->handle($fewo->fresh());
app(SyncChannel::class)->handle($fewo->fresh());
$this->assertSame(1, Booking::query()->count());
$this->assertSame(Booking::query()->sole()->id, $fewo->blockedPeriods()->where('source', 'channel')->sole()->linked_booking_id);
}
/** T07 – change after booking: dates, price, payment plan, calendar and portal tasks follow; the history keeps it. */
public function test_t07_change_of_a_booking_updates_price_payment_calendar_and_portals(): void
{
$booking = $this->confirmedOwnBooking();
$before = $booking->total;
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-07', 'departure' => '2026-11-12', 'guests' => 2, 'way' => 'agreed', 'requested_by' => 'guest', 'basis' => ChangeBasis::Phone->value, 'reason' => 'Gast verlängert um 2 Nächte'])
->assertNotified('Änderung gespeichert');
$booking->refresh();
$this->assertSame('2026-11-12', $booking->departure->toDateString());
$this->assertGreaterThan($before, $booking->total);
$change = $booking->changes()->sole();
$this->assertSame([ChangeStatus::Applied, ChangeBasis::Phone, 'guest'], [$change->status, $change->basis, $change->requested_by]);
$this->assertStringContainsString('Neu belegt: 10.11.–12.11.2026', implode(' ', $change->consequences['calendar']));
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('ends_on', '2026-11-12')->exists(), 'portal task for the new dates');
$this->assertSame('Gast verlängert um 2 Nächte', $booking->events()->where('type', 'change')->value('reason'));
}
/** T08 – cancellation: the right way for own and for portal bookings, with costs, refund and portal task. */
public function test_t08_cancellation_takes_the_right_way(): void
{
$own = $this->confirmedOwnBooking();
app(RecordPayment::class)->handle($own, 10000, CarbonImmutable::today(), PaymentMethod::Transfer);
Livewire::test(ViewBooking::class, ['record' => $own->getRouteKey()])
->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Krankheit', 'notify' => false, 'costs_task' => true])
->assertNotified('Buchung storniert');
$own->refresh();
$this->assertSame(BookingStatus::Cancelled, $own->status);
$this->assertSame(['guest', 'Krankheit', 'Ingrid'], [$own->cancellation->initiated_by, $own->cancellation->reason, $own->cancellation->recorded_by]);
$this->assertTrue(BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::CancellationFee)->exists());
$this->assertTrue(BookingTask::query()->where('booking_id', $own->id)->where('kind', BookingTaskKind::RefundCheck)->exists());
$this->fewo();
$this->portalMail('Neue Buchung', "Anreise: 07.12.2026\nAbreise: 14.12.2026\nBuchungsnummer: HA-STORNO1");
$portal = Booking::query()->where('portal_reference', 'HA-STORNO1')->sole();
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])
->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Gast storniert über FeWo-direkt'])
->assertNotified('Stornierung im Portal veranlassen');
$this->assertSame(BookingStatus::Confirmed, $portal->fresh()->status, 'stays booked until the portal confirms');
Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])
->callAction('confirmPortalCancellation', ['initiated_by' => 'guest', 'effective' => true])
->assertNotified('Buchung storniert');
$this->assertSame(BookingStatus::Cancelled, $portal->fresh()->status);
$request = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-28'), CarbonImmutable::parse('2026-12-01'), 2), ['first_name' => 'Ina', 'last_name' => 'Anfrage', 'email' => 'ina@example.org'], sendMails: false);
Livewire::test(ViewBooking::class, ['record' => $request->getRouteKey()])
->callAction('end', ['reason' => 'Hund nicht erlaubt', 'notify' => false])
->assertNotified('Vorgang beendet');
$this->assertSame(BookingStatus::Declined, $request->fresh()->status);
$this->assertNull($request->fresh()->cancellation, 'a request without booking is no cancellation');
}
/** T09 – family visit: no rent, guests, services and tourist tax; no contract, no reminders, no review. */
public function test_t09_family_visit(): void
{
$this->property->update(['tourist_tax_rate' => 250]);
$linen = Extra::query()->create(['property_id' => $this->property->id, 'name' => 'Wäschepaket', 'price' => 1800, 'pricing' => 'per_item', 'is_active' => true]);
Livewire::test(CreateBooking::class)
->fillForm(['kind' => BookingForm::OWN_USE, 'internal_kind' => InternalKind::PrivateStay->value, 'occasion' => 'Besuch von Tochter Anna', 'property_id' => $this->property->id, 'guests' => 3, 'arrival' => '2026-11-14', 'departure' => '2026-11-19',
'stay_first_name' => 'Anna', 'stay_last_name' => 'Stommer', 'stay_email' => 'anna@example.org', 'rent' => '0', 'tourist_tax_persons' => 2, 'tourist_tax_note' => 'Enkelkind unter 6 Jahren befreit',
'items' => [['extra_id' => $linen->id, 'quantity' => 3]]])
->call('create')->assertHasNoFormErrors();
$visit = Booking::query()->sole();
$this->assertSame([CaseType::A6, InternalKind::PrivateStay, BookingStatus::Confirmed], [$visit->case_type, $visit->internal_kind, $visit->status]);
$this->assertSame(3 * 1800 + 2 * 5 * 250, $visit->total);
$this->assertContains('tourist_tax', array_column($visit->quote['lines'], 'type'));
$this->assertSame(Responsibility::Nobody, $visit->process()->documents());
$this->assertFalse($visit->wantsPaymentTasks());
$this->assertNull($visit->contract_path);
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->whereDate('starts_on', '2026-11-14')->exists(), 'portals are blocked');
$this->assertSame(DocumentKind::StayConfirmation, DocumentKind::forCase($visit));
$this->travelTo(CarbonImmutable::parse('2026-11-21'));
app(SendBookingReminders::class)->handle();
app(RequestReviews::class)->handle();
Mail::assertNotSent(ReviewRequest::class);
$this->assertSame(0, BookingTask::query()->where('booking_id', $visit->id)->count());
}
/** T10 – maintenance block: no guest, contract or payment; extended and lifted with the portals following. */
public function test_t10_maintenance_block_extended_and_lifted(): void
{
$this->get(route('filament.admin.resources.bookings.create', ['kind' => 'block', 'von' => '2026-11-20', 'bis' => '2026-11-23']))->assertOk();
Livewire::withQueryParams(['kind' => 'block', 'von' => '2026-11-20', 'bis' => '2026-11-23'])->test(CreateBooking::class)
->assertSet('data.kind', 'block')->assertSet('data.arrival', '2026-11-20')
->fillForm(['kind' => BookingForm::BLOCK, 'occasion' => 'Malerarbeiten im Bad', 'property_id' => $this->property->id, 'arrival' => '2026-11-20', 'departure' => '2026-11-23'])
->call('create')->assertHasNoFormErrors();
$block = Booking::query()->sole();
$this->assertSame([InternalKind::Block, null, null, null], [$block->internal_kind, $block->guest_id, $block->total, $block->contract_path]);
Livewire::test(ViewBooking::class, ['record' => $block->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-20', 'departure' => '2026-11-25', 'reason' => 'Trocknung dauert länger'])
->assertNotified('Änderung gespeichert');
$this->assertSame('2026-11-25', $block->fresh()->departure->toDateString());
$this->assertSame(ChangeBasis::NotNeeded, $block->changes()->sole()->basis);
Livewire::test(ViewBooking::class, ['record' => $block->getRouteKey()])
->callAction('end', ['reason' => 'Arbeiten abgeschlossen'])
->assertNotified('Sperre aufgehoben');
$block->refresh();
$this->assertSame(BookingStatus::Cancelled, $block->status);
$this->assertNull($block->cancellation, 'lifting a block is no cancellation');
$this->assertSame('Sperre aufgehoben', $block->events()->where('type', 'status')->reorder()->orderByDesc('id')->value('summary'));
$this->assertTrue(ChannelTask::query()->where('channel_id', $this->manualPortal->id)->where('action', 'unblock')->exists(), 'portals are released');
Mail::assertNotSent(BookingConfirmed::class);
Mail::assertNotSent(BookingCancelled::class);
}
/** T11 – external payments (R09): portal total, payouts, commission and open amounts kept apart. */
public function test_t11_external_payments_of_reference_case_r09(): void
{
$this->fewo();
$this->portalMail('Neue Buchung', "Anreise: 10.07.2027\nAbreise: 17.07.2027\nBuchungsnummer: HA-R09XYZ");
$booking = Booking::query()->sole();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'guests' => 2, 'stated_on' => '2026-10-22',
'amounts' => [
['kind' => AmountKind::Accommodation->value, 'label' => '7 Nächte', 'amount' => '840.00'],
['kind' => AmountKind::Discount->value, 'label' => 'Rabatt', 'amount' => '-42.00'],
['kind' => AmountKind::Unexplained->value, 'label' => 'Gebühren und Steuern', 'amount' => '181.51'],
['kind' => AmountKind::Commission->value, 'label' => 'An FeWo-direkt gezahlt', 'amount' => '-84.82'],
['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Auszahlung', 'amount' => '894.69'],
['kind' => AmountKind::PayoutAnnounced->value, 'label' => 'Erwartete Auszahlung', 'amount' => '900.20', 'note' => 'zweite Ansicht'],
['kind' => AmountKind::InstallmentDue->value, 'label' => '2. Rate', 'amount' => '588.90', 'due_on' => '2027-06-10'],
],
'paid' => [['amount' => '390.61', 'paid_on' => '2026-10-20']]])
->assertNotified('Beträge gespeichert');
$money = CaseMoney::of($booking->fresh());
$this->assertSame(97951, $money->total());
$this->assertSame(0, $money->positions()['difference'], 'the positions add up to the total – nothing invented');
$this->assertSame([89469, 90020], $money->payout()['values']);
$this->assertSame(551, $money->payout()['difference']);
$this->assertNull($money->payout()['outstanding'], 'contradicting announcements are not settled by the system');
$this->assertSame(58890, $money->openAtPortal());
$this->assertSame(0, $money->openForUs());
$this->assertSame(0, $money->receivedOnAccount(), 'paid to the portal is not money on our account');
app(RecordPayment::class)->handle($booking->fresh(), 89469, CarbonImmutable::today(), PaymentMethod::Transfer, kind: PaymentKind::PortalPayout, source: 'FeWo-direkt');
$money = CaseMoney::of($booking->fresh());
$this->assertSame(89469, $money->receivedOnAccount());
$this->assertSame(39061, $booking->fresh()->paidAmount(), 'the payout is not counted as a payment of the guest');
// Entering the same statements again does not double them.
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'stated_on' => '2026-10-22', 'amounts' => [['kind' => AmountKind::Accommodation->value, 'label' => '7 Nächte', 'amount' => '840.00']], 'paid' => [['amount' => '390.61', 'paid_on' => '2026-10-20']]]);
$this->assertSame(7, $booking->amounts()->count());
$this->assertSame(39061, $booking->fresh()->paidAmount());
}
/** T12 – settings hierarchy: landlord, property, channel per intake and the single case. */
public function test_t12_settings_hierarchy_is_applied_and_visible(): void
{
$fewo = $this->fewo(['process_overrides' => ['inquiry' => ['processing' => 'manual'], 'booking' => ['payments' => 'portal']]]);
Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'hold_hours' => 48]]);
$this->property->update(['process_overrides' => ['hold_hours' => 24]]);
$settings = app(ProcessSettings::class);
$direct = $settings->resolve($this->property->fresh(), null, IntakeKind::Inquiry);
$portalRequest = $settings->resolve($this->property->fresh(), $fewo, IntakeKind::Inquiry);
$portalBooking = $settings->resolve($this->property->fresh(), $fewo, IntakeKind::Booking);
$this->assertSame([ProcessingMode::Automatic, 'tenant'], [$direct->processing(), $direct->source(ProcessSetting::Processing)]);
$this->assertSame([24, 'property'], [$direct->holdHours(), $direct->source(ProcessSetting::HoldHours)]);
$this->assertSame([ProcessingMode::Manual, 'channel'], [$portalRequest->processing(), $portalRequest->source(ProcessSetting::Processing)]);
$this->assertSame([ProcessingMode::Automatic, 'tenant'], [$portalBooking->processing(), $portalBooking->source(ProcessSetting::Processing)], 'the booking intake inherits the default');
$this->assertSame(CaseType::A4, $portalBooking->caseType);
$case = app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'], sendMails: false, originChannel: $fewo);
$this->assertSame(ProcessingMode::Manual, $case->processingMode());
Livewire::test(ViewBooking::class, ['record' => $case->getRouteKey()])->callAction('automation', ['mode' => ProcessingMode::Automatic->value]);
$this->assertSame(ProcessingMode::Automatic, $case->fresh()->processingMode(), 'the case decision wins');
$this->actingAs(User::factory()->create(['admin_mode' => AdminMode::Expert]));
Livewire::test(EffectiveSettings::class)
->assertSee('FeWo-direkt – Anfrage')->assertSee('FeWo-direkt – feste Buchung')->assertSee('Portal')->assertSee('Wohnung')
->set('bookingId', $case->id)->assertSee('für diesen Vorgang umgestellt');
}
/** T13 – test operation: every message of a whole run reaches only the test address. */
public function test_t13_test_operation_redirects_every_outgoing_message(): void
{
// A real mailer behind the gate instead of the fake of setUp().
$manager = new MailManager(app());
app()->instance('mail.manager', $manager);
Mail::swap($manager);
config(['fewo.mail_redirect_to' => null, 'mail.default' => 'array']);
// Every message that really leaves the system (after the test-operation gate), whichever mailer sent it.
$sent = [];
Event::listen(MessageSent::class, function (MessageSent $event) use (&$sent): void {
$sent[] = ['subject' => $event->message->getSubject(), 'to' => array_map(fn ($address) => $address->getAddress(), $event->sent->getEnvelope()->getRecipients())];
});
Settings::tenant()->update(['operating_mode' => Settings::MODE_TEST, 'test_recipient' => 'test@example.com']);
app(TenantContext::class)->set(Settings::tenant()->fresh());
$booking = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@gast.example']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction(TestAction::make('sendOffer')->arguments([]));
$booking->refresh();
$this->post(URL::temporarySignedRoute('offers.accept', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]), ['terms' => '1']);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-07', 'departure' => '2026-11-11', 'guests' => 2, 'way' => 'agreed', 'requested_by' => 'guest', 'basis' => ChangeBasis::Email->value, 'reason' => 'eine Nacht mehr', 'send_confirmation' => true]);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Absage', 'notify' => true, 'costs_task' => true]);
$this->assertGreaterThanOrEqual(6, count($sent), 'request, notification, offer, confirmation, change, cancellation');
foreach ($sent as $message) {
$this->assertSame(['test@example.com'], $message['to'], $message['subject']);
}
}
/** T14 – an agreed change and a change that needs the guest's consent are kept apart. */
public function test_t14_agreed_and_consent_requiring_changes_are_kept_apart(): void
{
$booking = $this->confirmedOwnBooking();
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-07', 'departure' => '2026-11-11', 'guests' => 3, 'way' => 'propose', 'requested_by' => 'landlord', 'reason' => 'Angebot: eine Nacht länger'])
->assertNotified('Vorschlag an den Gast gesendet');
$proposal = $booking->changes()->sole();
$this->assertSame(ChangeStatus::Proposed, $proposal->status);
$this->assertSame('2026-11-10', $booking->fresh()->departure->toDateString(), 'nothing changes before the guest agrees');
Mail::assertSent(ChangeProposed::class);
$this->assertSame('change_proposed', collect(CaseActivities::for($booking->fresh()))->firstWhere('key', 'change_proposed')?->key);
$this->get(URL::temporarySignedRoute('changes.show', $proposal->expires_at, ['change' => $proposal]))->assertOk()->assertSee('Änderung annehmen');
$this->post(URL::temporarySignedRoute('changes.accept', $proposal->expires_at, ['change' => $proposal]), ['agree' => '1'])->assertRedirect();
$proposal->refresh();
$this->assertSame([ChangeStatus::Applied, ChangeBasis::GuestLink], [$proposal->status, $proposal->basis]);
$this->assertNotNull($proposal->decided_at);
$this->assertSame('2026-11-11', $booking->fresh()->departure->toDateString());
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('change', ['arrival' => '2026-11-07', 'departure' => '2026-11-11', 'guests' => 2, 'way' => 'agreed', 'requested_by' => 'guest', 'basis' => ChangeBasis::Phone->value, 'reason' => 'Eine Person weniger', 'send_confirmation' => true])
->assertNotified('Änderung gespeichert');
$agreed = $booking->changes()->reorder()->orderByDesc('id')->first();
$this->assertSame(ChangeBasis::Phone, $agreed->basis);
$this->assertNull($agreed->decided_at, 'an updated confirmation is no consent of the guest');
$this->assertNotNull($agreed->confirmation_sent_at);
Mail::assertSent(BookingChanged::class, 1);
}
/** 6.3 – manual blocks become A6 cases; the calendar the portals read stays the same. */
public function test_existing_manual_blocks_become_cases_without_changing_the_portal_calendar(): void
{
$target = Channel::factory()->for($this->property)->create(['name' => 'Ziel', 'export_enabled' => true, 'export_mode' => 'regular', 'status' => 'active']);
BlockedPeriod::factory()->for($this->property)->create(['source' => 'manual', 'starts_on' => '2026-11-20', 'ends_on' => '2026-11-25', 'block_purpose' => 'maintenance', 'block_note' => 'Bad']);
BlockedPeriod::factory()->for($this->property)->create(['source' => 'manual', 'starts_on' => '2026-12-01', 'ends_on' => '2026-12-04', 'block_purpose' => 'own_use', 'block_note' => 'Wir selbst']);
$tasksBefore = ChannelTask::query()->count();
Mail::fake(); // the two blocks above informed the landlord about their portal tasks; from here on nothing may be sent
$feed = fn (): string => preg_replace('/^DTSTAMP:.*$/m', '', app(ICalFeed::class)->build($target->fresh()));
$exportBefore = $feed();
$this->artisan('cases:adopt-blocks')->expectsOutputToContain('Vorschau – nichts geändert')->assertSuccessful();
$this->assertSame(0, Booking::query()->count());
$this->artisan('cases:adopt-blocks', ['--apply' => true])->expectsOutputToContain('übernommen 2')->assertSuccessful();
$this->artisan('cases:adopt-blocks', ['--apply' => true])->assertSuccessful();
$this->assertSame(2, Booking::query()->count(), 'a repeated run adopts nothing twice');
$this->assertSame([InternalKind::Block, InternalKind::OwnUse], Booking::query()->orderBy('arrival')->get()->pluck('internal_kind')->all());
$this->assertSame($exportBefore, $feed(), 'the portals see exactly the same calendar');
$this->assertSame($tasksBefore, ChannelTask::query()->count(), 'no portal tasks');
Mail::assertNothingSent();
}
private function confirmedOwnBooking(): Booking
{
$booking = app(CreateReservation::class)->handle($this->property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org'], sendMails: false);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])->callAction('confirm', ['notify' => false]);
return $booking->fresh();
}
/**
* @param array<string, mixed> $attributes
*/
private function fewo(array $attributes = []): Channel
{
return Channel::query()->where('name', 'FeWo-direkt')->first() ?? Channel::factory()->for($this->property)->create([
'name' => 'FeWo-direkt', 'booking_model' => 'portal_booking', 'case_intake' => CaseIntakeMode::Create,
'settings' => ['email_senders' => 'fewo-direkt.de'], 'process_overrides' => ['booking' => ['payments' => 'portal']], ...$attributes,
]);
}
private function portalMail(string $subject, string $text): void
{
app(ProcessPortalMail::class)->handle(new PortalMail(uniqid('msg-'), 'noreply@fewo-direkt.de', $subject, $text, CarbonImmutable::now()));
}
private function releaseTexts(): void
{
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051']);
DocumentReleases::set(DocumentKind::ExternalRecord, false, 'Test');
}
}
+4 -5
View File
@@ -174,14 +174,13 @@ public function test_private_purpose_and_note_survive_a_changed_calendar_import_
Http::assertSentCount(1);
}
public function test_manual_block_can_be_created_and_edited_with_own_use_and_private_channel(): void
public function test_an_existing_manual_block_can_still_be_edited_with_own_use_and_private_channel(): void
{
$property = $this->property();
Livewire::test(ManageBlockedPeriods::class)->callAction('create', [
'property_id' => $property->id, 'starts_on' => '2026-11-10', 'ends_on' => '2026-11-12',
'block_purpose' => 'own_use', 'block_note' => 'Eigener Aufenthalt', 'is_private' => true,
])->assertHasNoActionErrors();
// New blocks are A6 cases; blocks from before stay editable in the list.
BlockedPeriod::factory()->for($property)->create(['source' => 'manual', 'starts_on' => '2026-11-10', 'ends_on' => '2026-11-12',
'block_purpose' => 'own_use', 'block_note' => 'Eigener Aufenthalt', 'is_private' => true]);
$block = BlockedPeriod::sole();
$this->assertSame('manual', $block->source);
+16 -6
View File
@@ -166,7 +166,7 @@ public function test_the_new_dialog_takes_over_a_portal_booking_and_the_page_lea
->callAction(TestAction::make('provideContact')->arguments([]), ['guest' => ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'erika@example.test'], 'process' => ProvideGuestContact::MANUAL, 'guest_confirmed' => false])
->assertNotified('Kontaktdaten gespeichert')
->callAction(TestAction::make('portalPrice')->arguments([]), ['portal_total' => '979.51', 'guests' => 2])
->assertNotified('Preis gespeichert');
->assertNotified('Beträge gespeichert');
$booking->refresh();
$this->assertNotNull($booking->contact_requested_at);
@@ -224,19 +224,29 @@ public function test_the_manual_status_action_is_an_expert_function_and_not_offe
$this->assertSame(BookingStatus::Paid, $portal->fresh()->status);
}
public function test_ending_a_portal_booking_cancels_it_and_asks_to_cancel_on_the_portal_too(): void
public function test_ending_a_portal_booking_requests_the_cancellation_on_the_portal_and_cancels_once_confirmed(): void
{
$booking = $this->takeOver(total: 50000);
$this->actingAs(User::factory()->create());
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Gast storniert im Portal', 'costs_task' => true])
->callAction('end', ['initiated_by' => 'guest', 'reason' => 'Gast storniert im Portal'])
->assertNotified('Stornierung im Portal veranlassen');
// The contract was made on the portal: the case stays booked until the cancellation is effective there.
$this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status);
$this->assertNotNull($booking->fresh()->portal_cancellation_requested_at);
$this->assertTrue(BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::PortalCancellation)->where('status', 'open')->exists());
$this->assertSame('Gast storniert im Portal', $booking->events()->where('type', 'status')->reorder()->latest('id')->value('reason'));
$this->assertSame('confirmPortalCancellation', CaseActivities::next($booking->fresh())?->action);
Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
->callAction('confirmPortalCancellation', ['initiated_by' => 'guest', 'reason' => null, 'effective' => true])
->assertNotified('Buchung storniert');
$this->assertSame(BookingStatus::Cancelled, $booking->fresh()->status);
$this->assertTrue(BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::PortalCancellation)->exists());
$this->assertSame('Gast storniert im Portal', $booking->events()->where('type', 'status')->reorder()->latest('id')->value('reason'));
$this->assertSame('Stornierung im Portal veranlassen bzw. prüfen', CaseActivities::next($booking->fresh())?->label);
$this->assertSame('guest', $booking->fresh()->cancellation->initiated_by);
$this->assertFalse(BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::PortalCancellation)->where('status', 'open')->exists());
}
public function test_archived_bookings_leave_the_list_but_keep_everything(): void