Compare commits

..
Author SHA1 Message Date
LarsandClaude Opus 5.5 3bcfc09417 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>
2026-11-01 22:16:47 +01:00
LarsandClaude Opus 5.5 33f8f899d6 Prozessarchitektur 0.10
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m57s
Neue hierarchische Struktur der fachlichen Sollbeschreibung (README, Prozesslandkarte,
Buchungsarchetypen, Abwicklungsprofile, Entscheidungen, Offene Fragen, Querschnitt,
Szenarien, V01/V02, Referenzen); die Fassung 0.9 bleibt in der Git-Historie.
Obsidian-Fensterzustand (workspace.json) wird nicht mehr versioniert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 21:11:54 +01:00
LarsandClaude Opus 5.5 0c10880e4f Testbetrieb: eine Schranke fuer jede ausgehende E-Mail
Deploy FeWo mit PipelineManager / deploy (push) Failing after 3m10s
EnforceMailTestMode prueft jede Mail unmittelbar vor dem Versand (MessageSending,
jeder Mailer): im Testbetrieb gehen An/Cc/Bcc nur an die Testadresse, ohne
Testadresse wird nichts versendet; der Modus wird je Mail frisch gelesen.
Ersetzt alwaysTo am Standard-Mailer. Tests inkl. Pruefung, dass kein Code am
Mailer vorbei versendet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 21:03:24 +01:00
LarsandClaude Opus 5.5 ac9d20b812 Ein Eingang fuer alle Kanaele (Paket 4, Prozessarchitektur v0.10)
Portalbuchungen und -anfragen aus Kalender und Mail werden ueber PortalIntake
zum Vorgang (nur bei sicherer Erkennung), Dubletten ueber Buchungsnummer,
gleiches Portal mit gleichen Naechten und Spiegelung; Unsicheres wird geklaert.
Portalstorno und -aenderung als Aufgabe am Vorgang ohne stille Stornierung.
Schalter je Kanal (Aus als Standard, Beobachten, Anlegen, Anlegen + weiter),
Eingangsprotokoll, Bestandsuebernahme mit Vorschau/Bericht/Ruecknahme,
Sperrnachweis in drei Stufen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 20:53:35 +01:00
LarsandClaude Opus 5.5 cf11c8a474 Dokumentenzusammenstellung und Vorlagensteuerung (Paket 3, Prozessarchitektur v0.10)
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m59s
Eine Zusammenstellung vor jedem Dokument (Angebot, Bestaetigung, Buchungsunterlagen
extern), Dokumentart je Vorgangsart, Freigaben fuer Vorlagen und Dokumentarten,
Schutz vor unvereinbarten Bedingungen bei Portalbuchungen (E-004), kein doppelter
Versand, Absicherung Hold 0 bis Paket 7, A6-Aufenthaltsbestaetigung vorbereitet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 19:44:52 +01:00
LarsandClaude Opus 5.5 64248c09fa Preisangaben bei Portalbuchungen für Paket 8 vorgemerkt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:41:38 +01:00
203 changed files with 9033 additions and 5935 deletions

No files matched your search

+3
View File
@@ -34,3 +34,6 @@ Thumbs.db
/scripts/deploy.*.env
!/scripts/deploy.example.env
storage/app/private/exports/
# Obsidian: persönlicher Fensterzustand des Editors
docs/Prozessarchitektur/.obsidian/workspace.json
+1 -1
View File
@@ -17,7 +17,7 @@ # Ferienwohnung Stommer
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Findings detected repeatedly (e.g. by the 5-minute sync) go through `AppSupportInbox` (admin Postfach, fingerprint per tenant, repeated only per the tenant's `reminder_interval_days`), never straight to mail; daily/weekly summaries: `SendDigests` + `DigestReport` (sections `DigestSection`). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. The one gate is `App\Listeners\EnforceMailTestMode` (MessageSending, every mailer; no test address in test mode = nothing is sent) – never send mail around Laravel's mailer (no direct transports, `mail()`, own SMTP; `MailTestModeGateTest` checks this). Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Findings detected repeatedly (e.g. by the 5-minute sync) go through `AppSupportInbox` (admin Postfach, fingerprint per tenant, repeated only per the tenant's `reminder_interval_days`), never straight to mail; daily/weekly summaries: `SendDigests` + `DigestReport` (sections `DigestSection`). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
+9 -2
View File
@@ -4,7 +4,10 @@
use App\Availability\AvailabilityChecker;
use App\Availability\CalendarClearance;
use App\Documents\DocumentComposer;
use App\Documents\DocumentFinding;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\Booking;
@@ -18,7 +21,8 @@
*
* Rules: pre-reservation active (the dates are really blocked), guest e-mail known, dates still free, contract
* texts released by the landlord (not the sample text; skipped while mails only go to the test recipient),
* and the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed).
* the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed) and an
* offer composition without anything to confirm ({@see DocumentComposer}: template released, contract data complete).
*/
class AutoOffer
{
@@ -57,6 +61,9 @@ public function blockers(Booking $booking): array
$reasons[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).';
}
// Status, e-mail, dates and the missing reservation are checked above; the composition adds what concerns the document.
$reasons = [...$reasons, ...app(DocumentComposer::class)->compose($booking, DocumentKind::Offer)->toConfirm(except: [DocumentFinding::HOLD_ZERO])];
return [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)];
}
@@ -79,7 +86,7 @@ public function handle(Booking $booking): array
}
try {
$this->sendOffer->handle($booking->fresh());
$this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]);
} catch (QuoteException|ReservationException $exception) {
// A mail failure keeps the saved offer (SendOffer reports it in the inbox); the landlord can resend the link.
return [$exception->getMessage()];
+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']];
}
}
+21 -3
View File
@@ -6,11 +6,15 @@
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\InboxMessageKind;
use App\Exceptions\ReservationException;
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;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
@@ -84,18 +88,32 @@ public function bind(Booking $booking): void
*
* @return bool whether the guest has the confirmation (true when no mail was requested)
*/
public function deliver(Booking $booking, bool $notifyGuest = true): bool
public function deliver(Booking $booking, bool $notifyGuest = true, ?DocumentKind $kind = null): bool
{
$booking->loadMissing(['guest', 'property']);
$kind ??= DocumentKind::forCase($booking) ?? DocumentKind::Confirmation;
try {
$this->contract->generate($booking);
$created = $booking->contract_path === null;
$this->contract->generate($booking, kind: $kind);
if ($created) {
CaseLog::record($booking, 'document', $kind->getLabel().' erstellt'.(isset($booking->offer_terms['template']['name']) ? ' (Vorlage '.$booking->offer_terms['template']['name'].', Version '.$booking->offer_terms['template']['version'].')' : ' (Texte der Webseite)'), data: [
'kind' => $kind->value,
'template' => $booking->offer_terms['template'] ?? null,
'annexes' => array_map(fn (array $annex): string => $annex['name'].' (Version '.$annex['version'].')', (array) ($booking->offer_terms['annexes'] ?? [])),
'pdf_sha256' => $booking->contract_pdf_sha256,
]);
}
if (! $notifyGuest) {
return true;
}
Mail::to($booking->guest->email, $booking->guest->full_name)->send(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';
}
}
+21
View File
@@ -3,6 +3,7 @@
namespace App\Actions;
use App\Channels\ConflictDetector;
use App\Channels\Intake\PortalIntake;
use App\Channels\Mail\ParsedPortalMail;
use App\Channels\Mail\PortalMail;
use App\Channels\Mail\PortalMailParser;
@@ -12,6 +13,7 @@
use App\Mail\PortalMailNotification;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\IntakeObservation;
use App\Models\PortalEmail;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
@@ -75,6 +77,9 @@ public function handle(PortalMail $mail): ?PortalEmail
]);
});
// One intake for all channels (package 4): bookings, requests and cancellations reach their case.
rescue(fn () => $this->intake($channel, $parsed, $record));
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
}
@@ -86,6 +91,17 @@ public function handle(PortalMail $mail): ?PortalEmail
return $record;
}
private function intake(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void
{
$intake = app(PortalIntake::class);
match ($parsed->type) {
PortalEmailType::Booking => $record->blocked_period_id !== null ? $intake->process(BlockedPeriod::query()->findOrFail($record->blocked_period_id), IntakeObservation::SOURCE_MAIL) : null,
PortalEmailType::Cancellation => $intake->cancellationMail($channel, $parsed, $record),
PortalEmailType::Inquiry => $intake->inquiryMail($channel, $parsed, $record),
PortalEmailType::Unknown => null,
};
}
/**
* Channels list the sender addresses or domains of their notification e-mails in settings.email_senders.
*/
@@ -177,6 +193,11 @@ private function release(Channel $channel, ParsedPortalMail $parsed): array
default => null,
};
// A block that belongs to a case is never released by a mail: the case leads, the landlord decides (E-019).
if ($block && $block->linked_booking_id !== null) {
return [PortalEmailStatus::NeedsReview, $block, 'Stornierung zu einem gebuchten Vorgang gemeldet – nichts automatisch freigegeben; Aufgabe am Vorgang prüfen.'];
}
if ($block) {
$block->delete();
+16 -10
View File
@@ -8,8 +8,8 @@
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Guest;
use App\Process\CaseAutomation;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* The guest's contact data arrived (portal message, e-mail, phone) and is entered on the booking. The landlord chooses
@@ -22,7 +22,7 @@ class ProvideGuestContact
public const MANUAL = 'manual';
public function __construct(private ConfirmBooking $confirm, private SendOffer $offer) {}
public function __construct(private ConfirmBooking $confirm, private AutoOffer $autoOffer, private SendBookingDocuments $documents) {}
/**
* @param array<string, ?string> $contact first_name, last_name, email, phone, street, postal_code, city, country
@@ -62,22 +62,28 @@ public function handle(Booking $booking, array $contact, string $process = self:
$booking->update(['processing_mode' => ProcessingMode::Automatic]);
if (in_array($booking->status, BookingStatus::occupying(), true)) {
$missing = app(CaseAutomation::class)->documentBlockers($booking);
if ($missing !== []) {
throw new ReservationException('Kontaktdaten gespeichert. Die Unterlagen können noch nicht automatisch versendet werden: '.implode(' ', $missing));
$reasons = $this->documents->automatically($booking);
if ($reasons !== []) {
throw new ReservationException('Kontaktdaten gespeichert. Die Unterlagen werden noch nicht automatisch versendet: '.implode(' ', $reasons));
}
$this->confirm->deliver($booking);
return 'Kontaktdaten gespeichert, Vertrag gesendet';
return 'Kontaktdaten gespeichert, Unterlagen gesendet';
}
if ($booking->intake === IntakeKind::Booking) {
$this->confirm->handle($booking);
DB::transaction(fn () => $this->confirm->bind($booking));
$reasons = $this->documents->automatically($booking->fresh());
if ($reasons !== []) {
throw new ReservationException('Kontaktdaten gespeichert und Buchung bestätigt. Die Unterlagen werden noch nicht automatisch versendet: '.implode(' ', $reasons));
}
return 'Kontaktdaten gespeichert, Buchung bestätigt und Vertrag gesendet';
return 'Kontaktdaten gespeichert, Buchung bestätigt und Unterlagen gesendet';
}
$this->offer->handle($booking);
$reasons = $this->autoOffer->handle($booking);
if ($reasons !== []) {
throw new ReservationException('Kontaktdaten gespeichert. Das Angebot wird noch nicht automatisch gesendet: '.implode(' ', $reasons));
}
return 'Kontaktdaten gespeichert, Angebot gesendet';
}
+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());
}
}
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace App\Actions;
use App\Documents\DocumentComposer;
use App\Documents\DocumentComposition;
use App\Enums\DocumentKind;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Process\CaseLog;
use Illuminate\Support\Facades\Cache;
/**
* Sends the documents of a binding case – the confirmation with the rental contract, or the booking documentation of a
* booking already binding on a portal – from its composition ({@see DocumentComposer}). Automatically only when nothing
* is missing and nothing has to be confirmed; by hand after the landlord confirmed every point. The documents go out
* once: a lock and a fresh look at the case keep repeated runs, double clicks and parallel jobs from sending twice.
* Until the first document exists the terms are taken from the composition (template and annexes as chosen); after
* that they stay as they were sent.
*/
class SendBookingDocuments
{
public function __construct(private DocumentComposer $composer, private ConfirmBooking $confirm) {}
/**
* @param array<string, mixed> $changes
*/
public function compose(Booking $booking, array $changes = []): DocumentComposition
{
return $this->composer->compose($booking, self::kindFor($booking), $changes);
}
/**
* The automatic run: sends when the composition allows it.
*
* @return list<string> why nothing was sent (empty: sent or nothing to send)
*/
public function automatically(Booking $booking): array
{
if ($booking->confirmation_sent_at !== null) {
return [];
}
$composition = $this->compose($booking);
if (! $composition->canSendAutomatically()) {
return [...$composition->blockers(), ...array_map(fn (string $point): string => 'Bitte prüfen: '.$point, $composition->toConfirm())];
}
return $this->send($booking, $composition, acknowledged: false, automatic: true) ? [] : ['Die Unterlagen konnten nicht versendet werden (siehe Postfach).'];
}
/**
* Sending by hand after the landlord saw the composition.
*
* @param array<string, mixed> $changes contract_template_id, annex_ids
* @return bool whether the guest has the documents
*
* @throws ReservationException
*/
public function handle(Booking $booking, array $changes = [], bool $acknowledged = false): bool
{
if (! $booking->isBinding()) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'mit Unterlagen bestätigt');
}
$composition = $this->compose($booking, $changes);
if ($composition->blockers() !== []) {
throw new ReservationException(implode(' ', $composition->blockers()));
}
if (! $composition->canSendByHand($acknowledged)) {
throw new ReservationException('Bitte die Hinweise prüfen und ausdrücklich bestätigen: '.implode(' ', $composition->toConfirm()));
}
return $this->send($booking, $composition, $acknowledged, automatic: false);
}
/**
* The document kind of a binding case (a case whose documents the portal sends has none from us).
*/
public static function kindFor(Booking $booking): DocumentKind
{
$kind = DocumentKind::forCase($booking);
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
{
$lock = Cache::lock('booking-documents-'.$booking->id, 120);
if (! $lock->get()) {
throw new ReservationException('Die Unterlagen werden gerade versendet. Bitte kurz warten und die Seite neu laden.');
}
try {
$booking->refresh();
if ($booking->confirmation_sent_at !== null) {
return true;
}
if (! $composition->termsFrozen && $booking->contract_path === null && $composition->terms !== null) {
$booking->update(['offer_terms' => $composition->terms]);
}
if ($acknowledged && $composition->toConfirm() !== []) {
CaseLog::record($booking, 'document', 'Hinweise vor dem Versand bestätigt', data: ['confirmed' => $composition->toConfirm()]);
}
return CaseLog::context(fn (): bool => $this->confirm->deliver($booking, kind: $composition->kind), actor: $automatic ? CaseLog::SYSTEM.' (automatisch)' : null);
} finally {
$lock->release();
}
}
}
+28 -3
View File
@@ -3,9 +3,11 @@
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Documents\DocumentComposer;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\InboxMessageKind;
use App\Enums\QuoteLineType;
use App\Exceptions\ReservationException;
@@ -17,6 +19,7 @@
use App\Pricing\QuoteException;
use App\Pricing\QuoteLine;
use App\Pricing\StayRequest;
use App\Process\CaseLog;
use App\Support\Inbox;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
@@ -42,7 +45,12 @@ public function __construct(
) {}
/**
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, annex_ids?: ?list<int|string>, guest?: array<string, ?string>} $changes
* The offer is checked through its composition ({@see DocumentComposer}) like every other document: points the
* landlord has to confirm (e.g. an unreleased template, missing contract data, a request that by the settings
* reserves nothing) stop it unless `acknowledged` is set. `expected_version` makes a repeated call harmless: when
* another offer was sent in the meantime, nothing is sent again.
*
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, annex_ids?: ?list<int|string>, guest?: array<string, ?string>, acknowledged?: bool, expected_version?: ?int} $changes
*
* @throws QuoteException
* @throws ReservationException
@@ -57,6 +65,11 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
}
$toConfirm = app(DocumentComposer::class)->compose($booking, DocumentKind::Offer, $changes)->toConfirm();
if ($toConfirm !== [] && ! ($changes['acknowledged'] ?? false)) {
throw new ReservationException('Bitte die Hinweise prüfen und ausdrücklich bestätigen: '.implode(' ', $toConfirm));
}
DB::transaction(function () use ($booking, $changes): void {
$booking->lockForTransition();
@@ -64,6 +77,10 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
}
if (isset($changes['expected_version']) && $booking->offer_version !== (int) $changes['expected_version']) {
throw new ReservationException('Inzwischen wurde schon ein Angebot gesendet (Version '.$booking->offer_version.'). Es wurde nichts erneut gesendet.');
}
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
@@ -75,7 +92,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
$stay = new StayRequest($arrival, $departure, (int) ($changes['guests'] ?? $booking->guests), $booking->extras ?? [], $promoCode);
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
$adjustmentLabel = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag');
$quote = $this->quoteWithAdjustment($booking, $stay, $adjustment, $adjustmentLabel);
$quote = $this->quoteFor($booking, $stay, $adjustment, $adjustmentLabel);
if (filled($changes['guest'] ?? null)) {
$booking->guest->update(Arr::only(array_map(fn ($value) => filled($value) ? trim((string) $value) : null, $changes['guest']), ['first_name', 'last_name', 'phone', 'street', 'postal_code', 'city', 'country']));
@@ -105,6 +122,14 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
$booking->refresh();
$this->contract->generate($booking, draft: true);
CaseLog::record($booking, 'document', 'Angebot Version '.$booking->offer_version.' erstellt'.(isset($booking->offer_terms['template']['name']) ? ' (Vorlage '.$booking->offer_terms['template']['name'].', Version '.$booking->offer_terms['template']['version'].')' : ' (Texte der Webseite)'), data: array_filter([
'kind' => DocumentKind::Offer->value,
'template' => $booking->offer_terms['template'] ?? null,
'annexes' => array_map(fn (array $annex): string => $annex['name'].' (Version '.$annex['version'].')', (array) ($booking->offer_terms['annexes'] ?? [])),
'pdf_sha256' => $booking->offer_pdf_sha256,
'offer_hash' => $booking->offer_hash,
'confirmed' => $toConfirm,
]));
if ($sendMail) {
$this->deliver($booking);
@@ -155,7 +180,7 @@ public function offerUrl(Booking $booking): string
*
* @throws QuoteException
*/
private function quoteWithAdjustment(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote
public function quoteFor(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote
{
$quote = $this->calculator->calculate($booking->property, $stay);
if ($adjustment === 0) {
+3
View File
@@ -5,6 +5,7 @@
use App\Channels\ChannelSyncException;
use App\Channels\ConflictDetector;
use App\Channels\ExternalPeriod;
use App\Channels\Intake\PortalIntake;
use App\Enums\ChannelEchoBehavior;
use App\Models\BlockedPeriod;
use App\Models\Booking;
@@ -135,6 +136,8 @@ public function handle(Channel $channel): ChannelSyncLog
'alerted_at' => null, 'last_import_events' => count($periods), 'sync_warnings' => $warnings])->save();
});
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
// One intake for all channels (package 4); a failure there never fails the sync itself.
rescue(fn () => app(PortalIntake::class)->afterSync($channel->fresh()));
return $channel->syncLogs()->create(['successful' => true, 'events' => count($periods), ...$counts,
'conflicts' => count($conflicts), 'warnings' => $warnings,
+3 -1
View File
@@ -5,6 +5,7 @@
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\OccupationKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\BlockedPeriod;
use App\Models\Booking;
@@ -31,7 +32,7 @@ class TakeOverExternalBooking
public function __construct(private ConfirmBooking $confirm, private PortalPrice $price) {}
/**
* @param array{guest?: ?array<string, ?string>, guests?: ?int, portal_reference?: ?string, portal_total?: ?int, notes?: ?string, guest_confirmed?: bool} $facts
* @param array{guest?: ?array<string, ?string>, guests?: ?int, portal_reference?: ?string, portal_total?: ?int, notes?: ?string, guest_confirmed?: bool, processing_mode?: ?ProcessingMode} $facts
*
* @throws ReservationException
*/
@@ -73,6 +74,7 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar
'hold_expires_at' => null,
'guest_confirmed_at' => ($facts['guest_confirmed'] ?? false) ? now() : null,
'internal_notes' => filled($facts['notes'] ?? null) ? trim((string) $facts['notes']) : null,
'processing_mode' => $facts['processing_mode'] ?? null,
...$this->price->columns($property, $arrival, $departure, $guests, $portalTotal, $channel->name),
]);
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Channel;
use App\Process\CaseAutomation;
use App\Process\ProcessSettings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/**
* A non-binding request through a portal (case type A2) as it arrives: dates and the portal's reference, nothing
* invented. Guest, number of guests and price stay unknown until the landlord enters them; the case then asks for
* exactly that and continues like a request of the own website. Whether the dates are reserved follows the channel's
* settings for requests.
*/
class TakeOverPortalInquiry
{
public function __construct(private AvailabilityChecker $availability, private ProcessSettings $settings) {}
/**
* @throws ReservationException
*/
public function handle(Channel $channel, CarbonImmutable $arrival, CarbonImmutable $departure, ?string $reference = null, ?string $notes = null, ?ProcessingMode $processingMode = null): Booking
{
$property = $channel->property;
if ($departure->lessThanOrEqualTo($arrival)) {
throw new ReservationException('Die Abreise muss nach der Anreise liegen.');
}
$booking = DB::transaction(function () use ($property, $channel, $arrival, $departure, $reference, $notes, $processingMode): Booking {
$property->newQuery()->whereKey($property->id)->lockForUpdate()->firstOrFail();
if (! $this->availability->isAvailable($property, $arrival, $departure)) {
throw ReservationException::notAvailable();
}
$profile = $this->settings->resolve($property, $channel, IntakeKind::Inquiry);
return $property->bookings()->create([
'status' => BookingStatus::Reserved,
'source' => 'portal',
'intake' => IntakeKind::Inquiry,
'origin_channel_id' => $channel->id,
'portal_reference' => $reference,
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'hold_expires_at' => $profile->preReservation() ? now()->addHours($profile->holdHours()) : null,
'processing_mode' => $processingMode,
'internal_notes' => $notes,
]);
});
app(CaseAutomation::class)->advance($booking);
return $booking->refresh();
}
}
+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()
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Channels\Intake;
use App\Enums\CaseType;
use App\Enums\IntakeOutcome;
use App\Models\Booking;
/**
* What the intake recognised in one incoming portal event, with its reasons in plain words.
*/
final class IntakeDecision
{
/**
* @param list<string> $reasons why the intake decided so
* @param list<string> $missing what the new case will not know yet
*/
public function __construct(
public readonly IntakeOutcome $outcome,
public readonly array $reasons = [],
public readonly ?Booking $booking = null,
public readonly ?CaseType $caseType = null,
public readonly array $missing = [],
public readonly ?string $reference = null,
) {}
public function withBooking(Booking $booking): self
{
return new self($this->outcome, $this->reasons, $booking, $this->caseType ?? $booking->case_type, $this->missing, $this->reference);
}
/**
* @param list<string> $reasons
*/
public function as(IntakeOutcome $outcome, array $reasons): self
{
return new self($outcome, $reasons, $this->booking, $this->caseType, $this->missing, $this->reference);
}
}
+489
View File
@@ -0,0 +1,489 @@
<?php
namespace App\Channels\Intake;
use App\Actions\ReconcileChannelRepresentations;
use App\Actions\TakeOverExternalBooking;
use App\Actions\TakeOverPortalInquiry;
use App\Channels\Mail\ParsedPortalMail;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\CaseIntakeMode;
use App\Enums\ChannelBookingModel;
use App\Enums\IntakeKind;
use App\Enums\IntakeOutcome;
use App\Enums\OccupationKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\IntakeObservation;
use App\Models\PortalEmail;
use App\Pricing\QuoteException;
use App\Process\CaseLog;
use App\Process\ProcessSettings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Collection;
use Throwable;
/**
* The one intake for bookings and requests from portals (UMSETZUNGSPLAN_v0.10 §5.5, package 4). Every incoming event –
* an entry of a portal calendar, a booking, request or cancellation e-mail – is judged the same way:
*
* - **Same case first** (no duplicates): an entry already linked to a case; the portal's booking reference; the same
* portal with exactly the same nights; the calendar mirror of an entry that belongs to a case. Different references
* or overlapping but different dates are never merged – they are clarified.
* - **New case only when certain**: a booking e-mail of the portal with dates and reference, or a calendar entry that
* the channel's rules recognise as a reservation booked at this portal (or that the landlord classified so). Blocks,
* mirrors of other portals, own use and unrecognised entries never become cases by themselves.
* - **Reports about known cases** (cancellation e-mail, entry gone from the calendar, other dates) become a task on the
* case and an entry in its history – the case itself is never cancelled, released or changed here (E-019).
*
* What happens then depends on the channel ({@see CaseIntakeMode}): nothing (off), only a record (observe), or the
* cases and tasks are created (create; continue additionally lets the new cases follow the automatic handling).
* Creating a case never sends anything the landlord did not release (package 3).
*/
class PortalIntake
{
public const LINK_NOTE = 'Automatisch dem Vorgang zugeordnet; der Vorgang führt diese Belegung.';
public function __construct(
private TakeOverExternalBooking $takeOver,
private TakeOverPortalInquiry $inquiry,
private ProcessSettings $settings,
) {}
/**
* Judges one portal calendar entry or e-mail block without changing anything.
*/
public function evaluate(BlockedPeriod $block): IntakeDecision
{
$block->loadMissing(['channel', 'property', 'canonicalBlock', 'linkedBooking']);
$channel = $block->channel;
$reference = self::reference($block);
if ($channel === null || ! in_array($block->source, ['channel', 'email'], true)) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Kein importierter Portaleintrag.'], reference: $reference);
}
if ($block->trashed()) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Nicht mehr im Kalender des Portals.'], reference: $reference);
}
if ($block->linked_booking_id !== null && $block->linkedBooking !== null) {
return new IntakeDecision(IntakeOutcome::Link, ['Bereits dem Vorgang zugeordnet.'], $block->linkedBooking, reference: $reference);
}
if ($block->is_representation) {
$leaderCase = $block->canonicalBlock?->linkedBooking;
return $leaderCase !== null
? new IntakeDecision(IntakeOutcome::Link, ['Spiegelung einer Belegung, die zu diesem Vorgang gehört.'], $leaderCase, reference: $reference)
: new IntakeDecision(IntakeOutcome::Ignore, ['Spiegelung einer anderen Belegung, keine eigene Buchung.'], reference: $reference);
}
if ($reference !== null && ($case = $this->caseByReference($channel, $reference)) !== null) {
return new IntakeDecision(IntakeOutcome::Link, ['Gleiche Buchungsnummer '.$reference.' wie der Vorgang.'], $case, reference: $reference);
}
if ($block->ends_on->lessThanOrEqualTo(CarbonImmutable::today())) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Liegt in der Vergangenheit.'], reference: $reference);
}
if ($block->occupationKind() === OccupationKind::Block) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Als Sperrzeit eingeordnet (z. B. Spiegelung, eigene Nutzung oder Wartung).'], reference: $reference);
}
if ($block->is_private) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Als private Belegung eingeordnet.'], reference: $reference);
}
$origin = $block->origin_channel_id;
if ($origin !== null && $origin !== $channel->id) {
$case = $this->caseWithSameNights($block, $origin);
return $case !== null
? new IntakeDecision(IntakeOutcome::Link, ['Laut Kalender über ein anderes Portal gebucht; dort gibt es den Vorgang mit genau diesen Nächten.'], $case, reference: $reference)
: new IntakeDecision(IntakeOutcome::Clarify, ['Laut Kalender über ein anderes Portal gebucht – der Vorgang entsteht dort, nicht hier.'], reference: $reference);
}
$case = $this->caseWithSameNights($block, $channel->id);
if ($case !== null) {
return filled($case->portal_reference) && $reference !== null && $case->portal_reference !== $reference
? new IntakeDecision(IntakeOutcome::Clarify, ['Gleiche Nächte wie Vorgang '.$case->reference.', aber andere Buchungsnummer ('.$reference.' / '.$case->portal_reference.').'], reference: $reference)
: new IntakeDecision(IntakeOutcome::Link, ['Dasselbe Portal mit genau denselben Nächten wie Vorgang '.$case->reference.'.'], $case, reference: $reference);
}
$overlap = Booking::query()->occupying()->where('property_id', $block->property_id)->overlapping($block->starts_on, $block->ends_on)->first();
if ($overlap !== null) {
return new IntakeDecision(IntakeOutcome::Clarify, ['Überschneidet sich mit Vorgang '.$overlap->reference.' ('.$overlap->arrival->format('d.m.').'–'.$overlap->departure->format('d.m.Y').'), ohne dieselbe Buchung zu sein.'], reference: $reference);
}
$sameChannelOverlap = $channel->blockedPeriods()->occupying()->whereKeyNot($block->id)->overlapping($block->starts_on, $block->ends_on)->exists();
if ($sameChannelOverlap) {
return new IntakeDecision(IntakeOutcome::Clarify, ['Weitere Einträge desselben Portals überschneiden sich – keine Zusammenführung nach Terminen.'], reference: $reference);
}
$certainty = $this->certainty($block, $reference);
if ($certainty !== null) {
return new IntakeDecision(IntakeOutcome::Clarify, [$certainty], reference: $reference);
}
if ($channel->booking_model === ChannelBookingModel::Inquiry) {
return new IntakeDecision(IntakeOutcome::Clarify, ['Über dieses Portal kommen laut Einstellung nur Anfragen – eine feste Buchung bitte bestätigen.'], reference: $reference);
}
$profile = $this->settings->resolve($block->property, $channel, IntakeKind::Booking);
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
return new IntakeDecision(
IntakeOutcome::Create,
[$block->source === 'email' ? 'Buchungsmail von '.$channel->name.' mit Zeitraum und Buchungsnummer.' : 'Kalendereintrag nach Regel „'.($block->ical_interpretation['rule'] ?? 'persönlich eingeordnet').'“ als Buchung bei '.$channel->name.' erkannt.'],
caseType: $profile->caseType,
missing: array_values(array_filter([
blank($fields['guest_full_name'] ?? null) ? 'Name des Gastes' : 'Name des Gastes (nur als Hinweis aus dem Kalender)',
'E-Mail-Adresse des Gastes',
'Personenzahl',
'Gesamtpreis laut Portal',
$reference === null ? 'Buchungsnummer' : null,
])),
reference: $reference,
);
}
/**
* Judges an entry and acts as the channel allows: records what was recognised and – only when the channel creates
* cases – creates the case, links the entry to its case or marks it for clarification.
*/
public function process(BlockedPeriod $block, string $source): IntakeDecision
{
$channel = $block->channel;
$mode = $channel?->case_intake ?? CaseIntakeMode::Off;
if (! $mode->records()) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Automatische Übernahme ist für dieses Portal aus.']);
}
$decision = $this->evaluate($block);
$applied = false;
if ($mode->creates()) {
[$decision, $applied] = match ($decision->outcome) {
IntakeOutcome::Create => $this->create($block, $decision, $mode, $source),
IntakeOutcome::Link => [$decision, $this->link($block, $decision->booking, $decision->reasons[0] ?? '')],
IntakeOutcome::Clarify => [$decision, $this->flag($block, $decision->reasons[0] ?? '')],
default => [$decision, false],
};
}
$this->record($channel, $mode, $source, $decision, $applied, $block, null, $block->starts_on, $block->ends_on);
return $decision;
}
/**
* Takes over an existing portal entry by an explicit run of the landlord or operator (stock adoption), whatever the
* channel's switch says: certain bookings become cases (released by hand, never automatic), entries of known cases
* are linked, everything else is only reported.
*/
public function adopt(BlockedPeriod $block): IntakeDecision
{
$decision = $this->evaluate($block);
$applied = false;
if ($decision->outcome === IntakeOutcome::Create) {
[$decision, $applied] = $this->create($block, $decision, CaseIntakeMode::Create, IntakeObservation::SOURCE_ADOPTION);
} elseif ($decision->outcome === IntakeOutcome::Link) {
$applied = $this->link($block, $decision->booking, $decision->reasons[0] ?? '');
}
$this->record($block->channel, CaseIntakeMode::Create, IntakeObservation::SOURCE_ADOPTION, $decision, $applied, $block, null, $block->starts_on, $block->ends_on);
return $decision;
}
/**
* After a calendar sync: new or changed entries of the channel go through the intake; entries of known cases that
* disappeared or show other nights become reports on the case.
*/
public function afterSync(Channel $channel): void
{
$mode = $channel->case_intake ?? CaseIntakeMode::Off;
if (! $mode->records()) {
return;
}
$open = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id')
->where('is_representation', false)->whereDate('ends_on', '>', CarbonImmutable::today())->orderBy('starts_on')->get();
foreach ($open as $block) {
$this->process($block, IntakeObservation::SOURCE_CALENDAR);
}
$linked = $channel->blockedPeriods()->withTrashed()->with('linkedBooking')->where('source', 'channel')->whereNotNull('linked_booking_id')
->whereHas('linkedBooking', fn ($query) => $query->whereIn('status', BookingStatus::occupying())->whereDate('departure', '>', CarbonImmutable::today()))->get();
foreach ($linked as $block) {
$case = $block->linkedBooking;
if ($block->trashed()) {
$this->report($channel, $mode, $case, IntakeOutcome::CancellationSignal, 'Der Eintrag '.$block->starts_on->format('d.m.').'–'.$block->ends_on->format('d.m.Y').' ist aus dem Kalender von '.$channel->name.' verschwunden. Das kann eine Stornierung sein, ist aber kein Nachweis – bitte im Portal prüfen.', 'gone:'.$block->id, IntakeObservation::SOURCE_CALENDAR, $block);
} elseif (! $block->starts_on->equalTo($case->arrival) || ! $block->ends_on->equalTo($case->departure)) {
$this->report($channel, $mode, $case, IntakeOutcome::ChangeSignal, 'Der Kalender von '.$channel->name.' meldet '.$block->starts_on->format('d.m.').'–'.$block->ends_on->format('d.m.Y').', der Vorgang hat '.$case->arrival->format('d.m.').'–'.$case->departure->format('d.m.Y').'. Bitte prüfen, ob die Buchung im Portal geändert wurde.', 'dates:'.$block->id.':'.$block->starts_on->toDateString().':'.$block->ends_on->toDateString(), IntakeObservation::SOURCE_CALENDAR, $block);
}
}
}
/**
* A portal e-mail reporting a cancellation: the case learns about it as a task; nothing is cancelled.
*
* @return Booking|null the case the report belongs to
*/
public function cancellationMail(Channel $channel, ParsedPortalMail $parsed, PortalEmail $mail): ?Booking
{
$case = $parsed->reference !== null ? $this->caseByReference($channel, $parsed->reference) : null;
$mode = $channel->case_intake ?? CaseIntakeMode::Off;
if ($case === null || ! $case->isBinding()) {
$this->record($channel, $mode, IntakeObservation::SOURCE_MAIL, new IntakeDecision(IntakeOutcome::Clarify, [$parsed->reference === null ? 'Stornierungsmail ohne Buchungsnummer – keinem Vorgang sicher zuzuordnen.' : 'Kein gebuchter Vorgang mit der Buchungsnummer '.$parsed->reference.'.'], reference: $parsed->reference), false, null, $mail, $parsed->startsOn, $parsed->endsOn);
return null;
}
$this->report($channel, $mode, $case, IntakeOutcome::CancellationSignal, $channel->name.' meldet eine Stornierung (E-Mail „'.$mail->subject.'“). Bitte prüfen Sie die Buchung und die nächsten Schritte.', 'mail:'.$mail->message_id, IntakeObservation::SOURCE_MAIL, null, $mail);
return $case;
}
/**
* A request e-mail of a portal: a request case with the dates and the reference (A2), when the channel creates
* cases; otherwise only recorded.
*/
public function inquiryMail(Channel $channel, ParsedPortalMail $parsed, PortalEmail $mail): IntakeDecision
{
$mode = $channel->case_intake ?? CaseIntakeMode::Off;
if (! $mode->records()) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Automatische Übernahme ist für dieses Portal aus.']);
}
$profile = $this->settings->resolve($channel->property, $channel, IntakeKind::Inquiry);
$decision = match (true) {
! $parsed->hasPeriod() => new IntakeDecision(IntakeOutcome::Clarify, ['Anfrage erkannt, aber An- und Abreise nicht sicher lesbar.'], reference: $parsed->reference),
$parsed->reference !== null && ($case = $this->caseByReference($channel, $parsed->reference)) !== null => new IntakeDecision(IntakeOutcome::Link, ['Gleiche Anfragenummer '.$parsed->reference.' wie der Vorgang.'], $case, reference: $parsed->reference),
$parsed->endsOn->lessThanOrEqualTo(CarbonImmutable::today()) => new IntakeDecision(IntakeOutcome::Ignore, ['Liegt in der Vergangenheit.'], reference: $parsed->reference),
default => new IntakeDecision(IntakeOutcome::Inquiry, ['Anfrage-Mail von '.$channel->name.' mit Zeitraum.'], caseType: $profile->caseType, missing: ['Name und E-Mail-Adresse des Gastes', 'Personenzahl'], reference: $parsed->reference),
};
$applied = false;
if ($mode->creates() && $decision->outcome === IntakeOutcome::Inquiry) {
try {
$case = $this->inquiry->handle($channel, $parsed->startsOn, $parsed->endsOn, $parsed->reference, 'Automatisch aus der Anfrage-Mail von '.$channel->name.' übernommen („'.$mail->subject.'“).', $mode === CaseIntakeMode::Create ? ProcessingMode::Manual : null);
CaseLog::record($case, 'intake', 'Automatisch aus der Anfrage-Mail von '.$channel->name.' angelegt', actor: CaseLog::SYSTEM, data: ['source' => IntakeObservation::SOURCE_MAIL, 'message_id' => $mail->message_id]);
$decision = $decision->withBooking($case);
$applied = true;
} catch (ReservationException|QuoteException $exception) {
$decision = $decision->as(IntakeOutcome::Clarify, ['Anfrage nicht automatisch übernommen: '.$exception->getMessage()]);
}
}
$this->record($channel, $mode, IntakeObservation::SOURCE_MAIL, $decision, $applied, null, $mail, $parsed->startsOn, $parsed->endsOn);
return $decision;
}
/**
* The portal's booking reference of an entry: extracted by the calendar rules, or the one of a booking e-mail.
*/
public static function reference(BlockedPeriod $block): ?string
{
$fromRules = $block->ical_interpretation['fields']['booking_reference'] ?? null;
if (filled($fromRules)) {
return trim((string) $fromRules);
}
if ($block->source === 'email' && str_starts_with((string) $block->external_uid, 'email:')) {
$reference = substr((string) $block->external_uid, 6);
// Mails without a reference got a random identifier, which is no booking reference.
return preg_match('/^[0-9a-f]{32}$/', $reference) === 1 ? null : $reference;
}
return null;
}
/**
* The case of a portal booking with this reference: on the case itself or on an entry that belongs to a case.
*/
public function caseByReference(Channel $channel, string $reference): ?Booking
{
$case = Booking::query()->where('portal_reference', $reference)
->where(fn ($query) => $query->where('origin_channel_id', $channel->id)->orWhere('import_channel_id', $channel->id))
->orderBy('id')->first();
if ($case !== null) {
return $case;
}
$linked = $channel->blockedPeriods()->withTrashed()->whereNotNull('linked_booking_id')
->whereIn('external_uid', [$reference, 'email:'.$reference])->value('linked_booking_id');
return $linked !== null ? Booking::query()->find($linked) : null;
}
/**
* The one occupying case of this portal with exactly these nights (more than one: none – that is for a person).
*/
private function caseWithSameNights(BlockedPeriod $block, int $channelId): ?Booking
{
/** @var Collection<int, Booking> $cases */
$cases = Booking::query()->occupying()->where('property_id', $block->property_id)
->whereDate('arrival', $block->starts_on)->whereDate('departure', $block->ends_on)
->where(fn ($query) => $query->where('origin_channel_id', $channelId)->orWhere('import_channel_id', $channelId))
->get();
return $cases->count() === 1 ? $cases->first() : null;
}
/**
* Null when the entry is certainly a booking of its portal, otherwise why not.
*/
private function certainty(BlockedPeriod $block, ?string $reference): ?string
{
if ($block->needs_review && ! in_array($block->review_note, [ReconcileChannelRepresentations::OVERLAP_NOTE], true)) {
return 'Prüfhinweis am Eintrag: '.($block->review_note ?? 'bitte prüfen').'.';
}
if ($block->source === 'email') {
return $reference === null ? 'Buchungsmail ohne Buchungsnummer – ohne Nummer lässt sich ein späterer Kalendereintrag nicht sicher zuordnen.' : null;
}
// Classified by the landlord as a reservation booked at this portal.
if ($block->occupation_kind === OccupationKind::Reservation && $block->reviewed_at !== null && $block->origin_channel_id === $block->channel_id) {
return null;
}
$interpretation = (array) ($block->ical_interpretation ?? []);
if (! ($interpretation['matched'] ?? false)) {
return 'Kein Kalendermerkmal erkannt – eine reine Belegt-Meldung ist kein Nachweis einer Buchung.';
}
if (($interpretation['event_type'] ?? null) !== 'portal_reservation') {
return 'Die Regel „'.($interpretation['rule'] ?? '').'“ ordnet den Eintrag nicht als Buchung ein.';
}
if (($interpretation['representation'] ?? null) !== 'leading_candidate' || $block->origin_channel_id !== $block->channel_id) {
return 'Die Regel erkennt eine Reservierung, aber nicht sicher als Buchung bei diesem Portal.';
}
return null;
}
/**
* @return array{IntakeDecision, bool}
*/
private function create(BlockedPeriod $block, IntakeDecision $decision, CaseIntakeMode $mode, string $source): array
{
$channel = $block->channel;
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
$name = trim((string) ($fields['guest_full_name'] ?? $fields['guest_first_name'] ?? ''));
$origin = match ($source) {
IntakeObservation::SOURCE_MAIL => 'der Buchungsmail',
IntakeObservation::SOURCE_ADOPTION => 'dem Bestand der Portalbelegungen',
default => 'dem Kalender',
};
try {
$case = $this->takeOver->handle($block->property, $channel, CarbonImmutable::parse($block->starts_on), CarbonImmutable::parse($block->ends_on), [
'portal_reference' => $decision->reference,
'notes' => 'Automatisch aus '.$origin.' von '.$channel->name.' übernommen.'.($name !== '' ? ' Name laut Portal: '.$name.'.' : ''),
'processing_mode' => $mode === CaseIntakeMode::Create ? ProcessingMode::Manual : null,
], $block);
} catch (ReservationException $exception) {
$this->flag($block, 'Nicht automatisch übernommen: '.$exception->getMessage());
return [$decision->as(IntakeOutcome::Clarify, ['Nicht automatisch übernommen: '.$exception->getMessage()]), false];
}
CaseLog::record($case, 'intake', 'Automatisch aus '.$origin.' von '.$channel->name.' angelegt', actor: CaseLog::SYSTEM, data: ['source' => $source, 'blocked_period_id' => $block->id, 'reference' => $decision->reference]);
return [$decision->withBooking($case), true];
}
/**
* Makes the entry a mirror of its case (the case leads availability and export).
*/
private function link(BlockedPeriod $block, ?Booking $case, string $reason): bool
{
if ($case === null || $block->linked_booking_id === $case->id || $block->is_representation) {
return false;
}
$block->forceFill([
'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null,
'linked_booking_id' => $case->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(),
'occupation_kind' => OccupationKind::Reservation, 'review_note' => self::LINK_NOTE,
])->save();
app(ReconcileChannelRepresentations::class)->handle($block->property);
CaseLog::record($case, 'intake', 'Weitere Quelle zugeordnet: '.($block->source === 'email' ? 'E-Mail' : 'Kalender').' von '.$block->channel?->name.' ('.$block->starts_on->format('d.m.').'–'.$block->ends_on->format('d.m.Y').')', $reason, actor: CaseLog::SYSTEM, data: ['blocked_period_id' => $block->id]);
return true;
}
/**
* Puts an uncertain entry in front of the landlord ("Zu erledigen") with the reason.
*/
private function flag(BlockedPeriod $block, string $reason): bool
{
if ($block->needs_review || $block->reviewed_at !== null) {
return false;
}
$block->forceFill(['needs_review' => true, 'review_note' => mb_substr($reason, 0, 250)])->saveQuietly();
return true;
}
/**
* A report of the portal about a known case: a task and an entry in the history – once per report.
*/
private function report(Channel $channel, CaseIntakeMode $mode, Booking $case, IntakeOutcome $outcome, string $message, string $key, string $source, ?BlockedPeriod $block = null, ?PortalEmail $mail = null): void
{
$fingerprint = hash('sha256', $channel->id.'|signal|'.$key);
$known = $case->events()->where('type', 'portal_signal')->get()->contains(fn ($event): bool => ($event->data['fingerprint'] ?? null) === $fingerprint);
$applied = false;
if ($mode->creates() && ! $known) {
$kind = $outcome === IntakeOutcome::CancellationSignal ? BookingTaskKind::PortalCancellationReported : BookingTaskKind::PortalChangeReported;
$task = BookingTask::query()->firstOrNew(['booking_id' => $case->id, 'kind' => $kind]);
$task->forceFill(['tenant_id' => $case->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'note' => mb_substr($message, 0, 1000), 'completed_by' => null, 'completed_at' => null])->save();
CaseLog::record($case, 'portal_signal', $message, actor: $channel->name, data: ['fingerprint' => $fingerprint, 'source' => $source]);
$applied = true;
}
$this->record($channel, $mode, $source, new IntakeDecision($outcome, [$message], $case, $case->case_type), $applied, $block, $mail, $block?->starts_on ?? $case->arrival, $block?->ends_on ?? $case->departure, $key);
}
/**
* Records the decision once per event and result (repeated syncs and mails add nothing).
*/
private function record(?Channel $channel, CaseIntakeMode $mode, string $source, IntakeDecision $decision, bool $applied, ?BlockedPeriod $block, ?PortalEmail $mail, mixed $startsOn, mixed $endsOn, ?string $key = null): void
{
if ($channel === null || ! $mode->records()) {
return;
}
$fingerprint = hash('sha256', implode('|', [
$channel->id, $mode->value, $decision->outcome->value, $key ?? '',
$block?->id ?? '', $mail?->message_id ?? '', $decision->booking?->id ?? '',
$startsOn instanceof \DateTimeInterface ? $startsOn->format('Y-m-d') : (string) $startsOn,
$endsOn instanceof \DateTimeInterface ? $endsOn->format('Y-m-d') : (string) $endsOn,
]));
try {
$observation = IntakeObservation::query()->firstOrNew(['fingerprint' => $fingerprint]);
if ($observation->exists) {
return;
}
$observation->fill([
'channel_id' => $channel->id, 'blocked_period_id' => $block?->id, 'portal_email_id' => $mail?->id,
'booking_id' => $decision->booking?->id, 'source' => $source, 'mode' => $mode, 'outcome' => $decision->outcome,
'applied' => $applied, 'case_type' => $decision->caseType?->value, 'reference' => $decision->reference,
'starts_on' => $startsOn, 'ends_on' => $endsOn, 'reasons' => $decision->reasons, 'missing' => $decision->missing,
'occurred_at' => now(),
]);
$observation->tenant_id = $channel->tenant_id;
$observation->save();
} catch (Throwable $exception) {
// The record must never stop the intake itself.
report($exception);
}
}
}
+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;
}
}
@@ -0,0 +1,129 @@
<?php
namespace App\Console\Commands;
use App\Channels\Intake\PortalIntake;
use App\Enums\ChannelTaskStatus;
use App\Enums\IntakeOutcome;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
#[Signature('channels:adopt-occupations
{--channel=* : Nur diese Kanal-IDs}
{--apply : Wirklich übernehmen (ohne: nur Vorschau)}
{--revert= : Eine frühere Übernahme anhand ihres Berichts zurücknehmen}')]
#[Description('Bestehende Portalbelegungen ohne Vorgang prüfen und – nur mit --apply – als Vorgang übernehmen bzw. dem vorhandenen Vorgang zuordnen (Bericht, wiederholbar, rücknehmbar)')]
class AdoptPortalOccupations extends Command
{
private const DIRECTORY = 'intake-adoptions';
/** Attributes of an entry that an adoption changes and a revert restores. */
private const RESTORED = ['is_representation', 'representation_automatic', 'canonical_block_id', 'linked_booking_id', 'export_approved', 'needs_review', 'reviewed_at', 'occupation_kind', 'guest_id', 'review_note'];
public function handle(TenantRunner $runner, PortalIntake $intake): 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' => [], 'channel_task_ids' => []];
$firstTask = (int) ChannelTask::query()->withoutGlobalScopes()->max('id');
$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')
->where('is_representation', false)->whereDate('ends_on', '>', today())->orderBy('starts_on')->get();
foreach ($entries as $entry) {
$before = collect(self::RESTORED)->mapWithKeys(fn (string $field): array => [$field => $entry->getRawOriginal($field)])->all();
$decision = $apply ? $intake->adopt($entry) : $intake->evaluate($entry);
$created = $apply && $decision->outcome === IntakeOutcome::Create && $decision->booking !== null;
$report['entries'][] = [
'tenant' => $tenant->id, 'channel' => $channel->name, 'blocked_period_id' => $entry->id,
'period' => $entry->starts_on->format('d.m.Y').'–'.$entry->ends_on->format('d.m.Y'),
'outcome' => $decision->outcome->value, 'case_type' => $decision->caseType?->value, 'reference' => $decision->reference,
'booking_id' => $decision->booking?->id, 'created' => $created, 'reasons' => $decision->reasons, 'before' => $before,
];
}
}
});
if ($apply) {
$report['channel_task_ids'] = ChannelTask::query()->withoutGlobalScopes()->where('id', '>', $firstTask)->pluck('id')->all();
}
$this->table(['Kanal', 'Zeitraum', 'Ergebnis', 'Art', 'Nr.', 'Vorgang', 'Begründung'], array_map(fn (array $entry): array => [
$entry['channel'], $entry['period'], IntakeOutcome::from($entry['outcome'])->getLabel(), strtoupper((string) $entry['case_type']), $entry['reference'] ?? '–',
$entry['booking_id'] ? '#'.$entry['booking_id'].($entry['created'] ? ' (neu)' : '') : '–', implode(' ', $entry['reasons']),
], $report['entries']));
$path = self::DIRECTORY.'/'.$report['run'].($apply ? '' : '-vorschau').'.json';
for ($number = 2; Storage::disk('local')->exists($path); $number++) {
$path = self::DIRECTORY.'/'.$report['run'].($apply ? '' : '-vorschau').'-'.$number.'.json';
}
Storage::disk('local')->put($path, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
$counts = collect($report['entries'])->countBy('outcome');
$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;
}
/**
* Takes an adoption back: cases created by it are removed again as long as nothing has happened with them (no
* document, no payment), and every entry gets its former state. Cases with activity are reported, not touched.
*/
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);
if (! ($report['apply'] ?? false)) {
$this->info('Das war eine Vorschau – es gibt nichts zurückzunehmen.');
return self::SUCCESS;
}
$kept = [];
foreach ((array) $report['entries'] as $entry) {
$block = BlockedPeriod::query()->withoutGlobalScopes()->withTrashed()->find($entry['blocked_period_id']);
$case = ($entry['created'] ?? false) ? Booking::query()->withoutGlobalScopes()->find($entry['booking_id']) : null;
if ($case !== null && ($case->contract_path !== null || $case->confirmation_sent_at !== null || $case->payments()->withoutGlobalScopes()->exists())) {
$kept[] = $case->reference;
continue;
}
// The entry first gets its former state (it may point to the case), then the case created by the run goes.
if ($block !== null && in_array($entry['outcome'], [IntakeOutcome::Create->value, IntakeOutcome::Link->value], true)) {
$block->forceFill((array) $entry['before'])->saveQuietly();
}
$case?->delete();
}
ChannelTask::query()->withoutGlobalScopes()->whereKey((array) ($report['channel_task_ids'] ?? []))->where('status', ChannelTaskStatus::Open)
->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Bestandsübernahme zurückgenommen.']);
$this->info('Zurückgenommen.'.($kept === [] ? '' : ' Nicht entfernt, weil schon bearbeitet: '.implode(', ', $kept)));
return self::SUCCESS;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use App\Enums\IntakeOutcome;
use App\Models\IntakeObservation;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('channels:intake-report {--days=14 : Zeitraum in Tagen}')]
#[Description('Bericht des Eingangsprotokolls: was über die Portale hereinkam und welche Vorgänge entstanden sind oder entstanden wären')]
class IntakeReport extends Command
{
public function handle(TenantRunner $runner): int
{
$runner->each(function (Tenant $tenant): void {
$observations = IntakeObservation::query()->with(['channel', 'booking'])
->where('occurred_at', '>=', now()->subDays((int) $this->option('days')))->orderBy('occurred_at')->get();
$this->line("<options=bold>{$tenant->name}</>: ".$observations->count().' Einträge');
$this->table(['Wann', 'Portal', 'Quelle', 'Zeitraum', 'Ergebnis', 'Ausgeführt', 'Vorgang', 'Begründung'], $observations->map(fn (IntakeObservation $observation): array => [
$observation->occurred_at->format('d.m. H:i'),
$observation->channel?->name,
$observation->sourceLabel(),
$observation->starts_on ? $observation->starts_on->format('d.m.').'–'.$observation->ends_on?->format('d.m.Y') : '–',
$observation->outcome->getLabel(),
$observation->applied ? 'ja' : 'nur protokolliert',
$observation->booking?->reference ?? '–',
implode(' ', (array) $observation->reasons),
])->all());
$wouldCreate = $observations->filter(fn (IntakeObservation $observation): bool => ! $observation->applied && in_array($observation->outcome, [IntakeOutcome::Create, IntakeOutcome::Inquiry], true))->count();
$this->info("Wären entstanden (Beobachten): {$wouldCreate}");
});
return self::SUCCESS;
}
}
+2
View File
@@ -25,6 +25,8 @@ public function handle(): int
$this->line("Versandweg: {$mailer}".($mailer === 'smtp' ? ' ('.config('mail.mailers.smtp.host').':'.config('mail.mailers.smtp.port').')' : '').' · Absender: '.config('mail.from.address'));
if (filled($redirect)) {
$this->line("Umleitung aktiv: die Mail geht an {$redirect} statt an {$to}.");
} elseif (! Settings::isLive()) {
$this->warn('Testbetrieb ohne Testadresse: Es wird keine E-Mail versendet. Testempfänger unter System › Betrieb eintragen.');
}
if ($mailer === 'log') {
$this->warn('Versandweg "log": es wird nichts zugestellt. Zum echten Versand MAIL_MAILER=smtp und MAIL_PASSWORD setzen (docs/BETRIEB.md §5a).');
+4 -4
View File
@@ -106,10 +106,10 @@ private static function values(Booking $booking, array $propertyData): array
'anreise_datum' => $booking->arrival->format('d.m.Y'),
'abreise_datum' => $booking->departure->format('d.m.Y'),
'naechte' => (string) $booking->nights(),
'personen' => (string) $booking->guests,
'gesamtpreis' => Money::format($booking->total),
'anzahlung' => Money::format($booking->deposit),
'restzahlung' => Money::format($booking->total - $booking->deposit),
'personen' => $booking->guests !== null ? (string) $booking->guests : null,
'gesamtpreis' => $booking->total !== null ? Money::format($booking->total) : null,
'anzahlung' => $booking->deposit !== null ? Money::format($booking->deposit) : null,
'restzahlung' => $booking->total !== null && $booking->deposit !== null ? Money::format($booking->total - $booking->deposit) : null,
'restzahlung_faellig' => $booking->balance_due_on?->format('d.m.Y'),
'buchungsnummer' => $booking->reference,
'datum' => ($booking->confirmed_at ?? $booking->offer_sent_at ?? now())->format('d.m.Y'),
+405
View File
@@ -0,0 +1,405 @@
<?php
namespace App\Documents;
use App\Actions\SendOffer;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Models\CancellationPolicy;
use App\Models\ContractTemplate;
use App\Models\Extra;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Throwable;
/**
* Prepares the document a case needs (UMSETZUNGSPLAN_v0.10 §4.5, package 3): applies the landlord's adjustments to a copy
* of the case, takes template and annexes from the process settings, captures the terms the document would freeze and
* lists – in plain words – what is missing, what has to be confirmed and what is only worth knowing. Nothing is saved.
*
* Only objective criteria lead to findings (missing or contradictory data, unreleased texts, terms not shown to be
* agreed); nationality or origin of a guest never do.
*/
class DocumentComposer
{
/** Placeholders that state payments to the landlord. */
private const PAYMENT_PLACEHOLDERS = ['anzahlung', 'restzahlung', 'restzahlung_faellig'];
public function __construct(
private SendOffer $offer,
private AvailabilityChecker $availability,
private ProcessSettings $settings,
) {}
/**
* @param array<string, mixed> $changes adjustments of the landlord (offer: dates, guests, promo code, price adjustment
* in cents, validity, message, guest data; all kinds: contract_template_id, annex_ids)
*/
public function compose(Booking $booking, ?DocumentKind $kind = null, array $changes = []): DocumentComposition
{
$booking->loadMissing(['guest', 'property', 'originChannel', 'importChannel']);
$kind ??= DocumentKind::forCase($booking) ?? DocumentKind::Internal;
$findings = [];
$draft = clone $booking;
$draft->setRelation('guest', $booking->guest !== null ? (clone $booking->guest)->fill(self::guestChanges($changes)) : null);
if ($kind === DocumentKind::Offer) {
$findings = [...$findings, ...$this->prepareOffer($booking, $draft, $changes)];
}
$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),
};
$terms = match (true) {
! $kind->isForGuests() => null,
$frozen => $booking->offer_terms,
default => OfferTerms::capture($template, $draft, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null),
};
$draft->offer_terms = $terms;
$findings = [...$findings, ...$this->commonFindings($booking, $draft, $kind, $template, $frozen)];
if ($kind === DocumentKind::ExternalRecord) {
$findings = [...$findings, ...$this->externalFindings($booking, $template, $terms, $frozen)];
}
if ($kind === DocumentKind::Confirmation) {
$findings = [...$findings, ...$this->confirmationFindings($booking)];
}
return new DocumentComposition(
kind: $kind,
draft: $draft,
intakeLabel: explode(' · ', CaseActivities::situation($booking))[0],
priceLines: array_values(array_map(fn (array $line): array => ['label' => (string) $line['label'], 'amount' => (int) $line['amount']], (array) ($draft->quote['lines'] ?? []))),
priceSource: $this->priceSource($booking, $draft, $kind),
services: $this->services($draft),
cancellation: $this->cancellation($terms, $kind),
template: $template,
templateSource: $this->templateSource($booking, $frozen, $explicitTemplate),
annexes: array_values(array_map(fn (array $annex): array => ['id' => (int) $annex['id'], 'label' => $annex['name'].' (Version '.$annex['version'].')'], (array) ($terms['annexes'] ?? []))),
terms: $terms,
termsFrozen: $frozen,
findings: $findings,
);
}
/**
* Applies the offer adjustments to the copy and calculates its price exactly as {@see SendOffer} will.
*
* @param array<string, mixed> $changes
* @return list<DocumentFinding>
*/
private function prepareOffer(Booking $booking, Booking $draft, array $changes): array
{
$findings = [];
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
$findings[] = DocumentFinding::blocker('Für diesen Vorgang ist kein Angebot mehr möglich ('.$booking->status->getLabel().').');
}
try {
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
$guests = (int) ($changes['guests'] ?? $booking->guests);
$promo = array_key_exists('promo_code', $changes) ? (filled($changes['promo_code']) ? trim((string) $changes['promo_code']) : null) : $booking->promo_code;
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
$label = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag');
$quote = $this->offer->quoteFor($booking, new StayRequest($arrival, $departure, max(1, $guests), $booking->extras ?? [], $promo), $adjustment, $label);
$draft->forceFill([
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'guests' => $quote->guests,
'promo_code' => $quote->promoCodeApplied ? $promo : null,
'quote' => $quote->toArray(),
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
]);
if (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
$findings[] = DocumentFinding::blocker('Der Zeitraum ist nicht mehr frei.');
}
} catch (QuoteException $exception) {
$findings[] = DocumentFinding::blocker('Preis: '.$exception->getMessage());
} catch (Throwable) {
$findings[] = DocumentFinding::blocker('Bitte Anreise, Abreise und Personen angeben.');
}
$draft->forceFill([
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()),
'offer_version' => $booking->offer_version + 1,
'offer_sent_at' => now(),
'offer_message' => $changes['offer_message'] ?? $booking->offer_message,
]);
if (! $booking->process()->preReservation()) {
$findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Ein Angebot mit Annahmelink reserviert ihn trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen. Eine Auskunft ohne Reservierung gibt es erst in einem späteren Ausbauschritt.', DocumentFinding::HOLD_ZERO);
}
if ($booking->offer_version > 0) {
$findings[] = DocumentFinding::info('Ersetzt Angebot Version '.$booking->offer_version.'; dessen Link wird ungültig.');
}
return $findings;
}
/**
* @return list<DocumentFinding>
*/
private function commonFindings(Booking $booking, Booking $draft, DocumentKind $kind, ?ContractTemplate $template, bool $frozen): array
{
if (! $kind->isForGuests()) {
return [DocumentFinding::info('Für diesen Vorgang geht kein Dokument an Gäste.')];
}
$findings = [];
if (! $kind->isAvailable()) {
$findings[] = DocumentFinding::blocker('„'.$kind->getLabel().'“ kann erst mit einem späteren Ausbauschritt versendet werden; die Arbeitsfassung ist vorbereitet.');
}
if ($draft->guest === null) {
$findings[] = DocumentFinding::blocker('Name und Kontaktdaten des Gastes fehlen.');
} elseif (blank($draft->guest->email)) {
$findings[] = DocumentFinding::blocker('Die E-Mail-Adresse des Gastes fehlt.');
}
if ($kind !== DocumentKind::Offer && $booking->total === null) {
$findings[] = DocumentFinding::blocker($booking->intake === IntakeKind::Booking ? 'Der Gesamtpreis (laut Portal) fehlt.' : 'Der Preis fehlt.');
}
if ($booking->confirmation_sent_at !== null && $kind !== DocumentKind::Offer) {
$findings[] = DocumentFinding::info('Bereits gesendet am '.$booking->confirmation_sent_at->format('d.m.Y, H:i').' Uhr. Erneutes Senden schickt dieselben Unterlagen.');
}
if ($frozen) {
return $findings;
}
if ($kind->isAvailable() && ! DocumentReleases::isReleased($kind)) {
$findings[] = DocumentFinding::confirm('Die Texte für „'.$kind->getLabel().'“ sind eine Arbeitsfassung und noch nicht freigegeben (So arbeite ich › Dokumente).');
}
if ($template !== null && ! $template->isReleased()) {
$findings[] = DocumentFinding::confirm('Die Vorlage „'.$template->label().'“ ist noch nicht für Gäste freigegeben (Vorlagen › Freigabe).');
}
$missing = $this->missingPlaceholders($draft);
if ($missing !== []) {
$findings[] = DocumentFinding::confirm('Im Vertragstext fehlen Angaben, sie erscheinen als [name?]: '.implode(', ', $missing).'.');
}
return $findings;
}
/**
* Bookings already binding on a portal: no acceptance link, the portal price counts, and the template must not add
* obligations the guest did not accept there (E-004).
*
* @param array<string, mixed>|null $terms
* @return list<DocumentFinding>
*/
private function externalFindings(Booking $booking, ?ContractTemplate $template, ?array $terms, bool $frozen): array
{
$channel = $booking->processChannel()?->name ?? 'dem Portal';
$findings = [DocumentFinding::info('Kein Annahmelink: Die Buchung ist bei '.$channel.' bereits verbindlich zustande gekommen.')];
if ($frozen) {
return $findings;
}
if ($template === null) {
$findings[] = DocumentFinding::confirm('Für Buchungen über '.$channel.' ist keine eigene Vorlage hinterlegt. Die Unterlagen enthielten Ihre Mietbedingungen der Webseite – ihnen hat der Gast bei '.$channel.' nicht zugestimmt.');
} elseif (! $template->confirmsPortalTerms()) {
$findings[] = DocumentFinding::confirm('Die Vorlage „'.$template->label().'“ ist nicht als Wiedergabe der Bedingungen von '.$channel.' bestätigt. Zusätzliche Pflichten gelten nur, wenn der Gast ihnen dort zugestimmt hat.');
$fees = $this->fees($terms);
if ($fees !== []) {
$findings[] = DocumentFinding::confirm('Gebühren in der Vorlage, die bei '.$channel.' nicht nachweislich vereinbart sind: '.implode('; ', $fees).'.');
}
}
if ($booking->process()->payments() === Responsibility::Portal && $this->mentionsPaymentsToUs($terms)) {
$findings[] = DocumentFinding::confirm('Die Vorlage nennt Zahlungen an Sie (Anzahlung/Restzahlung), laut Einstellung zahlt der Gast über '.$channel.'.');
}
return $findings;
}
/**
* @return list<DocumentFinding>
*/
private function confirmationFindings(Booking $booking): array
{
return $booking->accepted_at !== null
? [DocumentFinding::info('Bedingungen wie im angenommenen Angebot vom '.$booking->accepted_at->format('d.m.Y').' (unverändert).')]
: [];
}
private function priceSource(Booking $booking, Booking $draft, DocumentKind $kind): string
{
return match (true) {
$draft->total === null => 'noch nicht bekannt',
($draft->quote['source'] ?? null) === 'portal' => 'laut '.($booking->processChannel()?->name ?? 'Portal').' übernommen, nicht neu berechnet',
$kind === DocumentKind::Offer => 'aus Ihren Preisen berechnet',
$booking->accepted_at !== null => 'wie im angenommenen Angebot',
default => 'aus Ihren Preisen berechnet',
};
}
private function templateSource(Booking $booking, bool $frozen, bool $explicit): string
{
if ($frozen) {
return $booking->offer_version > 0 ? 'im angenommenen Angebot festgehalten' : 'mit den Unterlagen festgehalten';
}
if ($explicit) {
return 'für diesen Vorgang gewählt';
}
$source = $this->settings->forBooking($booking)->source(ProcessSetting::ContractTemplate);
return match ($source) {
ProcessProfile::CHANNEL => 'eingestellt für '.$booking->processChannel()?->name.' ('.($booking->intake?->getLabel() ?? '').')',
ProcessProfile::PROPERTY => 'eingestellt für die Wohnung '.$booking->property->name,
ProcessProfile::TENANT => 'Ihre Standardeinstellung',
default => 'keine Vorlage eingestellt',
};
}
/**
* @return list<string>
*/
private function services(Booking $draft): array
{
$extras = array_filter((array) ($draft->extras ?? []), fn ($quantity): bool => (int) $quantity > 0);
if ($extras === []) {
return [];
}
return Extra::query()->whereIn('id', array_keys($extras))->orderBy('name')->get()
->map(fn (Extra $extra): string => $extra->name.((int) $extras[$extra->id] > 1 ? ' × '.$extras[$extra->id] : ''))
->values()->all();
}
/**
* @param array<string, mixed>|null $terms
* @return list<string>
*/
private function cancellation(?array $terms, DocumentKind $kind): array
{
$lines = [];
if ($kind === DocumentKind::ExternalRecord) {
$lines[] = 'Maßgeblich ist die bei der Buchung über das Portal vereinbarte Regel.';
}
$policy = $terms['cancellation_policy'] ?? null;
if (is_array($policy) && ! empty($policy['tiers'])) {
return [...$lines, ...CancellationPolicy::describe($policy)];
}
if (filled($terms['texts']['stay.cancellation'] ?? null)) {
return [...$lines, 'Laut Text „Rücktritt / Stornierung“ der Vorlage bzw. Webseite (keine Staffel hinterlegt).'];
}
return $terms === null ? $lines : [...$lines, 'Keine Stornoregel hinterlegt.'];
}
/**
* Placeholders of the contract text that have no value for this case.
*
* @return list<string>
*/
private function missingPlaceholders(Booking $draft): array
{
$terms = (array) ($draft->offer_terms ?? []);
$data = (array) ($terms['property_data'] ?? []);
$texts = array_filter([
$terms['document']['body'] ?? null,
$terms['document']['annex_body'] ?? null,
...array_map(fn (array $annex): ?string => $annex['body'] ?? null, (array) ($terms['annexes'] ?? [])),
]);
return array_values(array_unique(array_merge(...array_map(fn (string $html): array => ContractPlaceholders::missing($html, $draft, $data), $texts ?: ['']))));
}
/**
* Fees a template states: the replacement fee of its cancellation rule and amounts written in its texts.
*
* @param array<string, mixed>|null $terms
* @return list<string>
*/
private function fees(?array $terms): array
{
$fees = [];
$policy = $terms['cancellation_policy'] ?? null;
if (is_array($policy) && ($policy['replacement_fee'] ?? null) !== null) {
$fees[] = 'Ersatzmieter-Gebühr '.Money::format((int) $policy['replacement_fee']);
}
if (is_array($policy) && ! empty($policy['tiers'])) {
$fees[] = 'Stornokosten nach Staffel ('.$policy['name'].')';
}
$text = strip_tags(implode(' ', $this->templateTexts($terms)));
preg_match_all('/\d{1,3}(?:\.\d{3})*(?:,\d{1,2})?\s?(?:€|EUR\b|Euro\b)/u', html_entity_decode($text), $amounts);
foreach (array_unique($amounts[0]) as $amount) {
$fees[] = trim($amount).' (im Text)';
}
return $fees;
}
/**
* @param array<string, mixed>|null $terms
*/
private function mentionsPaymentsToUs(?array $terms): bool
{
$text = implode(' ', $this->templateTexts($terms));
foreach (self::PAYMENT_PLACEHOLDERS as $placeholder) {
if (preg_match('/\{\{\s*'.$placeholder.'\s*\}\}/i', $text) === 1) {
return true;
}
}
return false;
}
/**
* The texts a template contributes (not the website texts it falls back to).
*
* @param array<string, mixed>|null $terms
* @return list<string>
*/
private function templateTexts(?array $terms): array
{
if ($terms === null || ! isset($terms['template'])) {
return [];
}
$template = ContractTemplate::query()->find($terms['template']['id']);
return array_values(array_filter([
$terms['document']['body'] ?? null,
$terms['document']['annex_body'] ?? null,
...array_values($template?->overrides() ?? []),
...array_map(fn (array $annex): ?string => $annex['body'] ?? null, (array) ($terms['annexes'] ?? [])),
]));
}
/**
* @param array<string, mixed> $changes
* @return array<string, ?string>
*/
private static function guestChanges(array $changes): array
{
$guest = (array) ($changes['guest'] ?? []);
return array_map(fn ($value): ?string => filled($value) ? trim((string) $value) : null, array_filter(Arr::only($guest, ['first_name', 'last_name', 'phone', 'street', 'postal_code', 'city', 'country']), 'filled'));
}
}
+129
View File
@@ -0,0 +1,129 @@
<?php
namespace App\Documents;
use App\Enums\DocumentKind;
use App\Models\Booking;
use App\Models\ContractTemplate;
/**
* Everything a document of a case consists of before it is sent (UMSETZUNGSPLAN_v0.10 §4.5): recipient, stay, how the
* case came in, price with its origin, services, cancellation rule, template and annexes, and what has to be checked.
* The same composition is shown to the landlord, decides whether the automatic run may send, and is what is sent.
*/
final class DocumentComposition
{
/**
* @param Booking $draft the case as the document will show it (never saved)
* @param list<array{label: string, amount: int}> $priceLines
* @param list<string> $services
* @param list<string> $cancellation
* @param list<array{id: int, label: string}> $annexes
* @param array<string, mixed>|null $terms the terms the document freezes (null: the website texts apply live)
* @param list<DocumentFinding> $findings
*/
public function __construct(
public readonly DocumentKind $kind,
public readonly Booking $draft,
public readonly string $intakeLabel,
public readonly array $priceLines,
public readonly string $priceSource,
public readonly array $services,
public readonly array $cancellation,
public readonly ?ContractTemplate $template,
public readonly string $templateSource,
public readonly array $annexes,
public readonly ?array $terms,
public readonly bool $termsFrozen,
public readonly array $findings,
) {}
public function recipientName(): ?string
{
return $this->draft->guest?->full_name;
}
public function recipientEmail(): ?string
{
return filled($this->draft->guest?->email) ? $this->draft->guest->email : null;
}
/**
* @return list<string>
*/
public function blockers(): array
{
return $this->messages(DocumentFinding::BLOCKER);
}
/**
* @param list<string> $except codes of findings left out
* @return list<string>
*/
public function toConfirm(array $except = []): array
{
return $this->messages(DocumentFinding::CONFIRM, $except);
}
/**
* @return list<string>
*/
public function information(): array
{
return $this->messages(DocumentFinding::INFO);
}
/**
* The automatic run sends only a document without blockers and without anything the landlord has to confirm.
*/
public function canSendAutomatically(): bool
{
return $this->blockers() === [] && $this->toConfirm() === [];
}
/**
* By hand: no blockers, and every point to confirm was confirmed.
*/
public function canSendByHand(bool $acknowledged): bool
{
return $this->blockers() === [] && ($this->toConfirm() === [] || $acknowledged);
}
/**
* The template as the landlord reads it.
*/
public function templateLabel(): string
{
if ($this->terms !== null && isset($this->terms['template']['name'])) {
return $this->terms['template']['name'].' (Version '.$this->terms['template']['version'].')';
}
return $this->template?->label() ?? 'Texte der Webseite';
}
/**
* What is stored about the document in the case history.
*
* @return array<string, mixed>
*/
public function record(): array
{
return [
'kind' => $this->kind->value,
'template' => $this->terms['template'] ?? null,
'annexes' => array_map(fn (array $annex): string => $annex['label'], $this->annexes),
'recipient' => $this->recipientEmail(),
'total' => $this->draft->total,
'price_source' => $this->priceSource,
];
}
/**
* @param list<string> $except
* @return list<string>
*/
private function messages(string $severity, array $except = []): array
{
return array_values(array_map(fn (DocumentFinding $finding): string => $finding->message, array_filter($this->findings, fn (DocumentFinding $finding): bool => $finding->severity === $severity && ! in_array($finding->code, $except, true))));
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Documents;
/**
* One finding of a document composition. A blocker stops the document (data missing or contradictory); a point to
* confirm stops the automatic run and needs the landlord's explicit confirmation before sending by hand; information
* only explains.
*/
final class DocumentFinding
{
public const BLOCKER = 'blocker';
public const CONFIRM = 'confirm';
public const INFO = 'info';
/** Code of the finding "the settings reserve nothing for requests" (Hold = 0, package 7). */
public const HOLD_ZERO = 'hold_zero';
public function __construct(
public readonly string $severity,
public readonly string $message,
public readonly ?string $code = null,
) {}
public static function blocker(string $message): self
{
return new self(self::BLOCKER, $message);
}
public static function confirm(string $message, ?string $code = null): self
{
return new self(self::CONFIRM, $message, $code);
}
public static function info(string $message): self
{
return new self(self::INFO, $message);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Documents;
use App\Enums\DocumentKind;
use App\Models\Tenant;
use App\Support\Settings;
/**
* Which document kinds the landlord has released for guests (tenants.document_releases). A kind that is not released is
* a working draft: it is never sent automatically, and by hand only after an explicit confirmation in the case.
*/
class DocumentReleases
{
public static function isReleased(DocumentKind $kind, ?Tenant $tenant = null): bool
{
$entry = self::entries($tenant)[$kind->value] ?? null;
return is_array($entry) ? (bool) ($entry['released'] ?? false) : $kind->releasedByDefault();
}
/**
* @return array{released: bool, by: ?string, at: ?string}|null the landlord's decision, null when none was made
*/
public static function decision(DocumentKind $kind, ?Tenant $tenant = null): ?array
{
$entry = self::entries($tenant)[$kind->value] ?? null;
return is_array($entry) ? ['released' => (bool) ($entry['released'] ?? false), 'by' => $entry['by'] ?? null, 'at' => $entry['at'] ?? null] : null;
}
/**
* Stores the decision for one kind; an unchanged decision keeps its date and author.
*/
public static function set(DocumentKind $kind, bool $released, string $actor, ?Tenant $tenant = null): void
{
$tenant ??= Settings::tenant();
if ($tenant === null || self::isReleased($kind, $tenant) === $released && self::decision($kind, $tenant) !== null) {
return;
}
$entries = self::entries($tenant);
$entries[$kind->value] = ['released' => $released, 'by' => $actor, 'at' => now()->toIso8601String()];
$tenant->update(['document_releases' => $entries]);
}
/**
* @return array<string, mixed>
*/
private static function entries(?Tenant $tenant): array
{
return (array) (($tenant ?? Settings::tenant())?->document_releases ?? []);
}
}
+42 -19
View File
@@ -2,50 +2,73 @@
namespace App\Documents;
use App\Enums\DocumentKind;
use App\Models\Booking;
use App\Models\Site;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;
/**
* The rental contract as PDF. As a draft it is part of the offer (offer_path, one file per offer version);
* the final contract is generated at confirmation (contract_path). Both are stored, so later changes of
* texts or prices do not alter a document the guest already received.
* The PDF of a case's document. As a draft it is part of the offer (offer_path, one file per offer version); the
* document of record – rental contract, booking documentation of a portal booking or stay confirmation, depending on
* the case – is generated once when it is sent (contract_path). Both are stored, so later changes of texts or prices do
* not alter a document the guest already received.
*/
class RentalContract
{
private const DISK = 'local';
public function generate(Booking $booking, bool $draft = false): string
public function generate(Booking $booking, bool $draft = false, ?DocumentKind $kind = null): string
{
$booking->loadMissing(['guest', 'property']);
$kind = $draft ? DocumentKind::Offer : ($kind ?? DocumentKind::forCase($booking) ?? DocumentKind::Confirmation);
$filename = $draft
? "contracts/Angebot-{$booking->reference}-v{$booking->offer_version}.pdf"
: "contracts/Mietvertrag-{$booking->reference}.pdf";
$path = "contracts/tenants/{$booking->tenant_id}/bookings/{$booking->id}/".basename($filename);
? "Angebot-{$booking->reference}-v{$booking->offer_version}.pdf"
: "{$kind->fileName()}-{$booking->reference}.pdf";
$path = "contracts/tenants/{$booking->tenant_id}/bookings/{$booking->id}/{$filename}";
// The logo is embedded as a file: the PDF is rendered on the server and must not depend on
// fetching anything over the network. Each website has its own (A14).
$logo = $booking->website()?->brandPath(Site::BRAND_DOCUMENT_LOGO);
// The final contract is a document of record: once stored it is never rewritten (confirmation resends reuse it).
// The document of record is never rewritten once stored (confirmation resends reuse it).
if (! $draft && $booking->contract_path !== null && Storage::disk(self::DISK)->exists($booking->contract_path)) {
return $booking->contract_path;
}
$document = OfferTerms::document($booking);
$pdf = Pdf::loadView($document !== null ? 'pdf.contract-document' : 'pdf.contract', [
'booking' => $booking,
'draft' => $draft,
'logo' => $logo,
'document' => $document,
])->setPaper('a4')->output();
$pdf = $this->render($booking, $kind, $draft);
Storage::disk(self::DISK)->put($path, $pdf);
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path, $draft ? 'offer_pdf_sha256' : 'contract_pdf_sha256' => hash('sha256', $pdf)]);
return $path;
}
/**
* The PDF bytes of a document, without storing anything (also used for previews of a composition).
*/
public function render(Booking $booking, DocumentKind $kind, bool $draft = false): string
{
[$view, $data] = $this->view($booking, $kind, $draft);
return Pdf::loadView($view, $data)->setPaper('a4')->output();
}
/**
* The view and its data that make up the document.
*
* @return array{0: string, 1: array<string, mixed>}
*/
public function view(Booking $booking, DocumentKind $kind, bool $draft = false): array
{
// The logo is embedded as a file: the PDF is rendered on the server and must not depend on
// fetching anything over the network. Each website has its own (A14).
$logo = $booking->website()?->brandPath(Site::BRAND_DOCUMENT_LOGO);
$document = $kind === DocumentKind::StayConfirmation ? null : OfferTerms::document($booking);
$view = match (true) {
$kind === DocumentKind::StayConfirmation => 'pdf.stay-confirmation',
$document !== null => 'pdf.contract-document',
default => 'pdf.contract',
};
return [$view, ['booking' => $booking, 'draft' => $draft, 'logo' => $logo, 'document' => $document, 'kind' => $kind]];
}
public function absolutePath(Booking $booking, bool $draft = false): ?string
{
$path = $draft ? $booking->offer_path : $booking->contract_path;
+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);
}
}
+8 -2
View File
@@ -17,6 +17,9 @@ enum BookingTaskKind: string implements HasLabel
case CancellationRequest = 'cancellation_request';
case CancellationFee = 'cancellation_fee';
case PortalCancellation = 'portal_cancellation';
case PortalCancellationReported = 'portal_cancel_reported';
case PortalChangeReported = 'portal_change_reported';
case RefundCheck = 'refund_check';
public function getLabel(): string
{
@@ -27,12 +30,15 @@ public function getLabel(): string
self::CancellationRequest => 'Stornierungswunsch des Gastes',
self::CancellationFee => 'Stornokosten prüfen und abrechnen',
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], true);
return ! in_array($this, [self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported, self::RefundCheck], true);
}
/**
@@ -46,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 => null,
self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported, self::RefundCheck => null,
};
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
/**
* Whether bookings and requests recognised on a channel become cases by themselves (UMSETZUNGSPLAN_v0.10 §5.5). Every
* channel starts switched off; observing only records what would happen. Creating cases never sends anything that the
* landlord has not released (documents need their release, package 3); only the last mode lets the new cases follow
* the automatic handling of the settings.
*/
enum CaseIntakeMode: string implements HasDescription, HasLabel
{
case Off = 'off';
case Observe = 'observe';
case Create = 'create';
case Continue = 'continue';
public function getLabel(): string
{
return match ($this) {
self::Off => 'Aus – Sie übernehmen Buchungen selbst',
self::Observe => 'Beobachten – nur protokollieren, was entstehen würde',
self::Create => 'Vorgänge anlegen – die nächsten Schritte geben Sie frei',
self::Continue => 'Vorgänge anlegen und nach Ihren Einstellungen weiterbearbeiten',
};
}
public function getDescription(): string
{
return match ($this) {
self::Off => 'Erkannte Buchungen erscheinen als Klärungsfall; nichts entsteht automatisch.',
self::Observe => 'Es entsteht nichts. Das Eingangsprotokoll zeigt, welche Vorgänge entstanden wären und warum.',
self::Create => 'Sicher erkannte Buchungen werden zum Vorgang; Sie geben jeden weiteren Schritt frei.',
self::Continue => 'Wie „anlegen“; danach laufen die Vorgänge automatisch oder mit Freigabe – wie unter „So arbeite ich“ eingestellt.',
};
}
public function records(): bool
{
return $this !== self::Off;
}
public function creates(): bool
{
return in_array($this, [self::Create, self::Continue], true);
}
}
+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',
};
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
/**
* How far a block (or release) on a portal is proven (E-018). The three steps are different statements: entering the
* block does not show that the portal took it over, and a calendar feed we provide proves nothing about the portal.
*/
enum ChannelTaskProof: string implements HasColor, HasLabel
{
/** The change was made or started (by hand or by an automation). */
case Initiated = 'initiated';
/** The block was seen in the portal's own calendar. */
case Observed = 'observed';
/** The portal confirmed it (e.g. its own confirmation or a test booking was refused). */
case Confirmed = 'confirmed';
public function getLabel(): string
{
return match ($this) {
self::Initiated => 'veranlasst',
self::Observed => 'im Portal gesehen',
self::Confirmed => 'Wirksamkeit bestätigt',
};
}
public function getColor(): string
{
return match ($this) {
self::Initiated => 'warning',
self::Observed => 'info',
self::Confirmed => 'success',
};
}
/**
* The choice the landlord reads when completing a task.
*/
public function question(bool $block = true): string
{
$what = $block ? 'gesperrt' : 'freigegeben';
return match ($this) {
self::Initiated => "Ich habe den Zeitraum im Portal {$what}.",
self::Observed => "… und im Kalender des Portals gesehen, dass er {$what} ist.",
self::Confirmed => 'Das Portal hat es bestätigt (z. B. Bestätigung oder Testanfrage abgelehnt).',
};
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
namespace App\Enums;
use App\Models\Booking;
use Filament\Support\Contracts\HasLabel;
/**
* The kinds of documents a case can produce (UMSETZUNGSPLAN_v0.10 §5.4). Which one a case needs follows from its case
* type, never from a choice of the landlord: a request gets a binding offer, a booking we made ourselves gets the
* confirmation with the rental contract, a booking that is already binding on a portal gets the booking documentation
* without an acceptance link (E-004). Information "unter Vorbehalt" (package 7) and the stay confirmation of A6
* (package 6) are prepared as working drafts but cannot be sent yet.
*/
enum DocumentKind: string implements HasLabel
{
case Offer = 'offer';
case Information = 'information';
case Confirmation = 'confirmation';
case ExternalRecord = 'external_record';
case StayConfirmation = 'stay_confirmation';
case Internal = 'internal';
public function getLabel(): string
{
return match ($this) {
self::Offer => 'Angebot mit Annahmelink',
self::Information => 'Auskunft unter Vorbehalt',
self::Confirmation => 'Buchungsbestätigung mit Mietvertrag',
self::ExternalRecord => 'Buchungsunterlagen (beim Portal gebucht)',
self::StayConfirmation => 'Aufenthaltsbestätigung (privat)',
self::Internal => 'Nur intern, kein Dokument an Gäste',
};
}
/**
* What the landlord reads about this kind on the settings page.
*/
public function description(): string
{
return match ($this) {
self::Offer => 'Für Anfragen: Preis, Vertragsentwurf und ein Link, mit dem der Gast verbindlich annimmt.',
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, nur auf Wunsch.',
self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.',
};
}
/**
* The document a case needs at its current stage, or null when nobody needs one from us (e.g. the portal sends it).
*/
public static function forCase(Booking $booking): ?self
{
$profile = $booking->process();
return match (true) {
$booking->intake === IntakeKind::Internal => $booking->guest_id !== null ? self::StayConfirmation : self::Internal,
$booking->caseType()->isExternallyBinding() => $profile->documents() === Responsibility::Portal ? null : self::ExternalRecord,
$booking->isBinding() => $profile->documents() === Responsibility::Portal ? null : self::Confirmation,
default => self::Offer,
};
}
/**
* Whether the guest makes the contract by accepting this document (only the offer carries an acceptance link).
*/
public function hasAcceptanceLink(): bool
{
return $this === self::Offer;
}
/**
* Whether a rental contract is part of this document.
*/
public function containsContract(): bool
{
return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord], true);
}
/**
* Whether this kind can be sent with the current packages (the others exist as working drafts only).
*/
public function isAvailable(): bool
{
return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord, self::StayConfirmation], true);
}
/**
* Whether the texts of this kind count as released while the landlord has not decided otherwise: the offer and the
* confirmation are the documents in use since the start; every new kind starts as a working draft.
*/
public function releasedByDefault(): bool
{
return in_array($this, [self::Offer, self::Confirmation], true);
}
/**
* Whether this kind goes to guests at all.
*/
public function isForGuests(): bool
{
return $this !== self::Internal;
}
/**
* File name prefix of the stored PDF.
*/
public function fileName(): string
{
return match ($this) {
self::Offer => 'Angebot',
self::Information => 'Auskunft',
self::Confirmation => 'Mietvertrag',
self::ExternalRecord => 'Buchungsunterlagen',
self::StayConfirmation => 'Aufenthaltsbestaetigung',
self::Internal => 'Intern',
};
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
/**
* What the intake made of one incoming event (portal calendar entry or portal e-mail).
*/
enum IntakeOutcome: string implements HasColor, HasLabel
{
/** A booking binding on the portal, recognised with confidence: a new case (A3–A5). */
case Create = 'create';
/** A non-binding request through the portal: a new request case (A2). */
case Inquiry = 'inquiry';
/** The same booking as an existing case (reference, same portal and dates, or its calendar mirror). */
case Link = 'link';
/** Not certain enough: the landlord clarifies. */
case Clarify = 'clarify';
/** No booking of this portal (block, mirror of another portal, own use, already clarified). */
case Ignore = 'ignore';
/** The portal reports a cancellation of a known case. */
case CancellationSignal = 'cancellation';
/** The portal reports other dates for a known case, or its calendar entry disappeared. */
case ChangeSignal = 'change';
public function getLabel(): string
{
return match ($this) {
self::Create => 'Neuer Vorgang (Buchung)',
self::Inquiry => 'Neuer Vorgang (Anfrage)',
self::Link => 'Gehört zu vorhandenem Vorgang',
self::Clarify => 'Klärung nötig',
self::Ignore => 'Keine Buchung',
self::CancellationSignal => 'Portal meldet Stornierung',
self::ChangeSignal => 'Portal meldet Änderung',
};
}
public function getColor(): string
{
return match ($this) {
self::Create, self::Inquiry => 'success',
self::Link, self::Ignore => 'gray',
self::Clarify => 'warning',
self::CancellationSignal, self::ChangeSignal => 'danger',
};
}
}
+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',
};
}
}
@@ -0,0 +1,112 @@
<?php
namespace App\Filament\Forms;
use App\Documents\DocumentComposer;
use App\Documents\DocumentComposition;
use App\Documents\RentalContract;
use App\Enums\AdminMode;
use App\Enums\DocumentKind;
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;
use Filament\Forms\Components\Checkbox;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\View;
use Throwable;
/**
* The composition of a document inside an action modal: the same picture for offer, confirmation and booking
* documentation, recalculated whenever the landlord adjusts something, plus the explicit confirmation that is
* required when there is something to check.
*/
class DocumentCompositionFields
{
/** @var array<string, DocumentComposition> */
private static array $compositions = [];
/**
* @param Closure(Get): array<string, mixed> $changes the adjustments currently in the form
* @return list<View|Checkbox>
*/
public static function make(Booking $booking, DocumentKind $kind, Closure $changes, ?Closure $visible = null): array
{
$compose = fn (Get $get): DocumentComposition => self::compose($booking, $kind, $changes($get));
return [
View::make('filament.document-composition')
->viewData(fn (Get $get): array => self::viewData($compose($get), $changes($get))),
Checkbox::make('acknowledged')
->label('Ich habe die Hinweise geprüft und möchte das Dokument so senden.')
->visible(fn (Get $get): bool => ($visible === null || $visible($get)) && $compose($get)->toConfirm() !== [])
->accepted(),
];
}
/**
* One composition per form state and request (the view and the confirmation box both need it).
*
* @param array<string, mixed> $changes
*/
public static function compose(Booking $booking, DocumentKind $kind, array $changes): DocumentComposition
{
$key = $booking->id.':'.$kind->value.':'.md5(serialize($changes)).':'.$booking->updated_at?->getTimestamp();
return self::$compositions[$key] ??= app(DocumentComposer::class)->compose($booking, $kind, $changes);
}
/**
* @param array<string, mixed> $changes
* @return array<string, mixed>
*/
private static function viewData(DocumentComposition $composition, array $changes): array
{
$user = auth()->user();
return [
'composition' => $composition,
'expert' => $user instanceof User && $user->adminMode() === AdminMode::Expert,
'mailPreview' => self::mailPreview($composition),
'documentPreview' => self::documentPreview($composition),
'pdfUrl' => route('filament.admin.document-preview', ['booking' => $composition->draft->getRouteKey(), 'kind' => $composition->kind->value, 'changes' => base64_encode(json_encode($changes) ?: '[]')]),
];
}
private static function mailPreview(DocumentComposition $composition): string
{
$draft = $composition->draft;
if ($draft->guest === null) {
return '<p style="font-family:sans-serif">Keine Vorschau: Der Gast ist noch nicht bekannt.</p>';
}
try {
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) {
report($exception);
return '<p style="font-family:sans-serif">Die Vorschau der E-Mail ist gerade nicht möglich.</p>';
}
}
private static function documentPreview(DocumentComposition $composition): string
{
try {
[$view, $data] = app(RentalContract::class)->view($composition->draft, $composition->kind, draft: $composition->kind === DocumentKind::Offer);
return view($view, $data)->render();
} catch (Throwable $exception) {
report($exception);
return '<p style="font-family:sans-serif">Die Vorschau des Dokuments ist gerade nicht möglich.</p>';
}
}
}
+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;
}
}
+42 -2
View File
@@ -2,6 +2,8 @@
namespace App\Filament\Pages;
use App\Documents\DocumentReleases;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\UserRole;
@@ -12,7 +14,9 @@
use App\Models\Tenant;
use App\Support\Settings;
use BackedEnum;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
@@ -63,7 +67,10 @@ public static function settings(): array
public function mount(): void
{
$this->form->fill(ProcessSettingFields::state((array) ($this->tenant()->process_defaults ?? [])));
$this->form->fill([
...ProcessSettingFields::state((array) ($this->tenant()->process_defaults ?? [])),
'document_releases' => collect(self::releasableKinds())->mapWithKeys(fn (DocumentKind $kind): array => [$kind->value => DocumentReleases::isReleased($kind, $this->tenant())])->all(),
]);
}
public function form(Schema $schema): Schema
@@ -75,6 +82,17 @@ public function form(Schema $schema): Schema
->description('Gilt für alle Wohnungen und Portale, solange dort nichts anderes eingestellt ist. Neue Einstellungen gelten für neue Vorgänge; laufende Vorgänge behalten ihre Regeln.')
->columns(2)
->schema(ProcessSettingFields::make('', self::settings(), fn (ProcessSetting $setting): string => 'Grundeinstellung ('.$setting->describe($setting->default()).')')),
Section::make('Dokumente')
->description('Welche Dokumente an Gäste gehen dürfen. Eine Arbeitsfassung wird nie automatisch versendet, von Hand nur nach ausdrücklicher Bestätigung im Vorgang. Vorlagen selbst geben Sie unter Vorlagen frei.')
->schema([
...array_map(fn (DocumentKind $kind): Toggle => Toggle::make('document_releases.'.$kind->value)
->label($kind->getLabel().' – freigegeben')
->helperText(fn (): string => $kind->description().self::decisionNote($kind)), self::releasableKinds()),
Text::make(fn (): HtmlString => new HtmlString('<ul style="list-style:disc;padding-left:1.25rem">'.collect(DocumentKind::cases())
->reject(fn (DocumentKind $kind): bool => in_array($kind, self::releasableKinds(), true) || ! $kind->isForGuests())
->map(fn (DocumentKind $kind): string => '<li><strong>'.e($kind->getLabel()).'</strong>: '.e($kind->description()).' '.e($kind->isAvailable() ? '(in Verwendung; Texte unter Webseite › Texte bzw. Vorlagen)' : '(Arbeitsfassung vorbereitet, noch nicht nutzbar)').'</li>')
->implode('').'</ul>')),
]),
Section::make('Abweichungen')
->description('Wo Portale oder Wohnungen anders arbeiten. Ändern unter Portale bzw. Wohnungen (Expertenansicht).')
->collapsed()
@@ -94,11 +112,33 @@ public function content(Schema $schema): Schema
public function save(): void
{
$this->tenant()->update(['process_defaults' => ProcessSettingFields::values($this->form->getState(), self::settings())]);
$state = $this->form->getState();
$this->tenant()->update(['process_defaults' => ProcessSettingFields::values($state, self::settings())]);
foreach (self::releasableKinds() as $kind) {
DocumentReleases::set($kind, (bool) ($state['document_releases'][$kind->value] ?? false), (string) auth()->user()?->name, $this->tenant());
}
Notification::make()->title('Gespeichert')->body('Gilt für neue Vorgänge.')->success()->send();
}
/**
* Document kinds whose texts the landlord releases here: the new kinds that can already be sent. Offer and
* confirmation are in use since the start; the others are drafts of later packages.
*
* @return list<DocumentKind>
*/
public static function releasableKinds(): array
{
return array_values(array_filter(DocumentKind::cases(), fn (DocumentKind $kind): bool => $kind->isAvailable() && ! $kind->releasedByDefault()));
}
private static function decisionNote(DocumentKind $kind): string
{
$decision = DocumentReleases::decision($kind);
return $decision === null || $decision['at'] === null ? ' Bisher: Arbeitsfassung.' : ' Zuletzt geändert am '.CarbonImmutable::parse($decision['at'])->format('d.m.Y').' von '.$decision['by'].'.';
}
/**
* Every deviation of a property or a channel, in plain words.
*/
@@ -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,10 +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;
@@ -19,6 +21,7 @@
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* Entry of a new case that did not come through the website: a request (A1/A2) goes the same way as a website request,
@@ -35,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 {
@@ -63,7 +65,16 @@ protected function handleRecordCreation(array $data): Model
$booking = app(CreateReservation::class)->handle($property, $stay, $guest, source: 'manual', sendMails: $sendMails && ! ($data['confirm_immediately'] ?? false), originChannel: $channel);
if ($data['confirm_immediately'] ?? false) {
app(ConfirmBooking::class)->handle($booking, notifyGuest: $sendMails && filled($booking->guest?->email));
DB::transaction(fn () => app(ConfirmBooking::class)->bind($booking));
if ($sendMails && filled($booking->guest?->email)) {
// The documents go out only when their composition needs no check; otherwise they wait on the case page.
$waiting = app(SendBookingDocuments::class)->automatically($booking->fresh());
if ($waiting !== []) {
Notification::make()->title('Gebucht – Unterlagen noch nicht gesendet')->body(implode(' ', $waiting))->warning()->send();
}
} else {
app(ConfirmBooking::class)->deliver($booking->fresh(), notifyGuest: false);
}
}
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
@@ -77,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,30 +3,43 @@
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;
use App\Filament\Actions\AssignGuestAction;
use App\Filament\Forms\Components\EuroInput;
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\PriceCalculator;
use App\Pricing\PrivateStayPrice;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
@@ -34,8 +47,10 @@
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;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
@@ -44,12 +59,15 @@
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\Group;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
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 Throwable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* The case page. At the top only what matters now: the next step as one large button, "Beenden" and the switch between
@@ -84,8 +102,12 @@ protected function getHeaderActions(): array
$this->requestContactAction(),
AssignGuestAction::make(),
$this->confirmAction(),
$this->sendDocumentsAction(),
$this->resendConfirmationAction(),
$this->portalPriceAction(),
$this->changeAction(),
$this->confirmPortalCancellationAction(),
$this->withdrawChangeAction(),
$this->extendHoldAction(),
$this->servicesAction(),
$this->offerPdfAction(),
@@ -125,10 +147,11 @@ private function sendOfferAction(): Action
->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking)
->modalHeading('Angebot an den Gast')
->modalDescription('Alles ist vorbereitet: Preis, Vertragsvorlage, Anlagen und Gültigkeit kommen aus Ihren Einstellungen. Prüfen Sie die Angaben; „Anpassen“ nur bei Bedarf. Mit „Senden“ erhält der Gast das Angebot mit einem Link zum Annehmen.')
->modalDescription('Alles ist vorbereitet: Preis, Vertragsvorlage, Anlagen und Gültigkeit kommen aus Ihren Einstellungen. Prüfen Sie die Zusammenstellung; „Anpassen“ nur bei Bedarf. Mit „Senden“ erhält der Gast das Angebot mit einem Link zum Annehmen.')
->modalSubmitActionLabel('Senden')
->modalWidth('3xl')
->modalWidth('4xl')
->fillForm(fn (): array => [
'expected_version' => $this->record->offer_version,
'arrival' => $this->record->arrival->toDateString(),
'departure' => $this->record->departure->toDateString(),
'guests' => $this->record->guests,
@@ -137,16 +160,14 @@ private function sendOfferAction(): Action
'price_adjustment_label' => $this->record->price_adjustment_label,
'valid_until' => now()->addHours($this->record->process()->holdHours())->format('Y-m-d H:i'),
'offer_message' => $this->record->offer_message,
'annex_ids' => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? [],
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'street', 'postal_code', 'city', 'phone']) ?? [],
])
->schema([
Section::make('So geht das Angebot hinaus')->schema([
Text::make(fn (Get $get): string => $this->offerPricePreview($get)),
Text::make(fn (): string => 'Gast: '.$this->record->guestName().' · '.($this->record->guest?->email ?: 'keine E-Mail-Adresse')),
Text::make(fn (): string => 'Vertragsvorlage: '.(OfferTerms::templateFor($this->record)?->label() ?? 'Texte der Webseite')),
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3),
]),
Section::make('Anpassen')->description('Zeitraum, Preis, Vorlage, Gültigkeit, Angaben zum Gast')->collapsed()->schema([
Hidden::make('expected_version'),
...DocumentCompositionFields::make($this->record, DocumentKind::Offer, fn (Get $get): array => $this->offerChanges(self::formState($get, ['expected_version', 'arrival', 'departure', 'guests', 'promo_code', 'price_adjustment', 'price_adjustment_label', 'valid_until', 'offer_message', 'contract_template_id', 'annex_ids', 'guest']))),
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3)->live(onBlur: true),
Section::make('Anpassen')->description('Zeitraum, Preis, Vorlage, Gültigkeit, Angaben zum Gast – die Zusammenstellung oben rechnet sofort neu.')->collapsed()->schema([
Section::make('Termin')->columns(3)->schema([
DatePicker::make('arrival')->label('Anreise')->required()->live(onBlur: true),
DatePicker::make('departure')->label('Abreise')->after('arrival')->required()->live(onBlur: true),
@@ -155,44 +176,88 @@ private function sendOfferAction(): Action
Section::make('Preis')->columns(3)->schema([
TextInput::make('promo_code')->label('Rabattcode')->maxLength(50)->live(onBlur: true),
TextInput::make('price_adjustment')->label('Preisanpassung')->helperText('Minus = Nachlass, z. B. -50')->numeric()->step(0.01)->suffix('€')->live(onBlur: true),
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80),
]),
Section::make('Vorlage und Anlagen')->schema([
Select::make('contract_template_id')
->label('Andere Vorlage für dieses Angebot')
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
->placeholder('wie eingestellt'),
Select::make('annex_ids')
->label('Anlagen')
->multiple()
->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all())
->default(fn (): array => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? []),
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80)->live(onBlur: true),
]),
...$this->templateFields(),
DateTimePicker::make('valid_until')
->label('Angebot gültig bis')
->helperText(fn (): string => 'Eingestellt: '.$this->record->process()->holdHours().' Stunden. Bis dahin bleibt der Zeitraum reserviert.')
->seconds(false)
->after('now')
->required(),
->required()
->live(onBlur: true),
Section::make('Gast – so erscheint er im Vertrag')->columns(2)->schema([
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100),
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100),
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150),
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20),
TextInput::make('guest.city')->label('Ort')->maxLength(100),
TextInput::make('guest.phone')->label('Telefon')->maxLength(50),
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100)->live(onBlur: true),
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100)->live(onBlur: true),
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150)->live(onBlur: true),
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20)->live(onBlur: true),
TextInput::make('guest.city')->label('Ort')->maxLength(100)->live(onBlur: true),
TextInput::make('guest.phone')->label('Telefon')->maxLength(50)->live(onBlur: true),
]),
]),
])
->action(fn (array $data, SendOffer $send) => $this->runWorkflow(fn () => $send->handle($this->record, $this->offerChanges($data)), 'Angebot gesendet'));
}
/**
* The documents of a binding case (confirmation with contract, or booking documentation of a portal booking), sent
* after the landlord saw their composition.
*/
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 || ($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')
->modalWidth('4xl')
->fillForm(fn (): array => ['annex_ids' => $this->record->contract_path === null && $this->record->offer_version === 0 ? (OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? []) : null])
->schema(fn (): array => [
...DocumentCompositionFields::make($this->record, SendBookingDocuments::kindFor($this->record), fn (Get $get): array => $this->documentChanges(self::formState($get, ['contract_template_id', 'annex_ids']))),
Section::make('Anpassen')->description('Vorlage und Anlagen für diesen Vorgang.')->collapsed()->visible($this->record->contract_path === null && $this->record->offer_version === 0)->schema($this->templateFields()),
])
->action(function (array $data, SendBookingDocuments $documents): void {
$this->runWorkflow(function () use ($data, $documents): void {
if (! $documents->handle($this->record, $this->documentChanges($data), (bool) ($data['acknowledged'] ?? false))) {
throw new ReservationException('Der Versand ist fehlgeschlagen (Details im Postfach). Sie können ihn über „Unterlagen erneut senden“ wiederholen.');
}
}, 'Unterlagen gesendet');
});
}
/**
* Choice of template and annexes for one case; changing the template proposes its annexes.
*
* @return list<Section>
*/
private function templateFields(): array
{
return [
Section::make('Vorlage und Anlagen')->schema([
Select::make('contract_template_id')
->label('Andere Vorlage für diesen Vorgang')
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label().($template->isReleased() ? '' : ' – nicht freigegeben')])->all())
->placeholder('wie eingestellt')
->live()
->afterStateUpdated(fn (Set $set, $state) => $set('annex_ids', OfferTerms::templateFor($this->record, $state)?->annexesFor($this->record)->pluck('id')->all() ?? [])),
Select::make('annex_ids')
->label('Anlagen')
->multiple()
->live()
->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all()),
]),
];
}
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')
@@ -239,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')
@@ -253,15 +318,40 @@ private function requestContactAction(): Action
private function confirmAction(): Action
{
$kind = fn (): DocumentKind => $this->record->intake === IntakeKind::Booking ? DocumentKind::ExternalRecord : DocumentKind::Confirmation;
return Action::make('confirm')
->label('Direkt verbindlich bestätigen')
->icon(Heroicon::OutlinedCheckCircle)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
->requiresConfirmation()
->modalHeading('Buchung direkt bestätigen')
->modalDescription('Ohne Angebot und Annahme durch den Gast – nur wenn die Buchung schon anders verbindlich vereinbart wurde (z. B. am Telefon). Der Zeitraum wird fest belegt.')
->schema([Toggle::make('notify')->label('Buchungsbestätigung an den Gast senden')->default(fn (): bool => filled($this->record->guest?->email))])
->action(fn (array $data, ConfirmBooking $confirm) => $this->runWorkflow(fn () => $confirm->handle($this->record, $data['notify']), 'Buchung bestätigt'));
->modalSubmitActionLabel('Bestätigen')
->modalWidth('4xl')
->fillForm(fn (): array => ['notify' => filled($this->record->guest?->email)])
->schema(fn (): array => [
Toggle::make('notify')->label('Unterlagen an den Gast senden')->live(),
Group::make(DocumentCompositionFields::make($this->record, $kind(), fn (Get $get): array => [], fn (Get $get): bool => (bool) $get('notify')))
->visible(fn (Get $get): bool => (bool) $get('notify')),
])
->action(function (array $data, ConfirmBooking $confirm, SendBookingDocuments $documents) use ($kind): void {
$notify = (bool) ($data['notify'] ?? false);
$acknowledged = (bool) ($data['acknowledged'] ?? false);
if ($notify) {
$composition = DocumentCompositionFields::compose($this->record, $kind(), []);
if (! $composition->canSendByHand($acknowledged)) {
Notification::make()->title('Nicht möglich')->body(implode(' ', [...$composition->blockers(), ...$composition->toConfirm()]))->danger()->send();
return;
}
}
$this->runWorkflow(function () use ($confirm, $documents, $notify, $acknowledged): void {
DB::transaction(fn () => $confirm->bind($this->record));
$notify ? $documents->handle($this->record->fresh(), [], $acknowledged) : $confirm->deliver($this->record->fresh(), notifyGuest: false);
}, 'Buchung bestätigt');
});
}
private function resendConfirmationAction(): Action
@@ -273,13 +363,12 @@ private function resendConfirmationAction(): Action
default => 'Bestätigung erneut senden',
})
->icon(Heroicon::OutlinedEnvelope)
->visible(fn (): bool => $this->record->isBinding() && filled($this->record->guest?->email))
->visible(fn (): bool => $this->record->isBinding() && filled($this->record->guest?->email) && ($this->record->confirmation_sent_at !== null || $this->record->confirmation_failed_at !== null))
->requiresConfirmation()
->modalDescription(fn (): string => 'Der Gast erhält die Buchungsbestätigung mit dem Vertrag (Vorlage: '.(OfferTerms::templateFor($this->record)?->label() ?? 'Texte der Webseite').').')
->modalDescription(fn (): string => 'Der Gast erhält dieselben Unterlagen noch einmal (Vorlage: '.(isset($this->record->offer_terms['template']['name']) ? $this->record->offer_terms['template']['name'].', Version '.$this->record->offer_terms['template']['version'] : 'Texte der Webseite').').')
->action(function (ConfirmBooking $confirm): void {
$missing = app(CaseAutomation::class)->documentBlockers($this->record);
if ($missing !== []) {
Notification::make()->title('Noch nicht möglich')->body(implode(' ', $missing))->warning()->send();
if ($this->record->contract_path === null) {
Notification::make()->title('Bitte zuerst prüfen')->body('Die Unterlagen wurden noch nie erstellt – bitte über „Unterlagen prüfen und senden“.')->warning()->send();
return;
}
@@ -290,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')
@@ -331,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([
@@ -454,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;
}
@@ -483,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')
@@ -496,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();
@@ -519,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();
});
}
@@ -550,28 +840,31 @@ private function offerChanges(array $data): array
{
return [
...$data,
'acknowledged' => (bool) ($data['acknowledged'] ?? false),
'price_adjustment' => filled($data['price_adjustment'] ?? null) ? (int) round((float) $data['price_adjustment'] * 100) : null,
];
}
/**
* Live price shown in the offer modal, calculated exactly like the offer itself.
* The current values of some fields of a modal form.
*
* @param list<string> $fields
* @return array<string, mixed>
*/
private function offerPricePreview(Get $get): string
private static function formState(Get $get, array $fields): array
{
try {
$stay = new StayRequest(CarbonImmutable::parse($get('arrival')), CarbonImmutable::parse($get('departure')), (int) $get('guests'), $this->record->extras ?? [], filled($get('promo_code')) ? (string) $get('promo_code') : null);
$quote = app(PriceCalculator::class)->calculate($this->record->property, $stay);
} catch (QuoteException $exception) {
return 'Preis: '.$exception->getMessage();
} catch (Throwable) {
return 'Preis: bitte Termin und Personen angeben.';
}
return collect($fields)->mapWithKeys(fn (string $field): array => [$field => $get($field)])->all();
}
$adjustment = filled($get('price_adjustment')) ? max((int) round((float) $get('price_adjustment') * 100), -$quote->rent()) : 0;
$promo = filled($get('promo_code')) ? ($quote->promoCodeApplied ? ' · Rabattcode angewendet' : ' · Rabattcode gilt hier nicht') : '';
return 'Preis im Angebot: '.Money::format($quote->total() + $adjustment).' für '.$stay->arrival->format('d.m.').'–'.$stay->departure->format('d.m.Y').', '.$stay->guests.' Personen'.$promo;
/**
* Form data of the documents modal as composition changes.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function documentChanges(array $data): array
{
return array_filter(Arr::only($data, ['contract_template_id', 'annex_ids']), fn ($value): bool => $value !== null);
}
private function runWorkflow(callable $workflow, string $successTitle): void
@@ -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)'),
@@ -5,11 +5,15 @@
use App\Documents\OfferTerms;
use App\Enums\ActivityState;
use App\Enums\AdminMode;
use App\Enums\DocumentKind;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\BlockedPeriod;
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;
@@ -63,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()
@@ -102,12 +102,9 @@ public static function configure(Schema $schema): Schema
]),
Section::make('Dokumente')
->schema([
TextEntry::make('documents')->hiddenLabel()->state(fn (Booking $record): string => collect([
$record->offer_path ? 'Angebot Version '.$record->offer_version : null,
$record->contract_path ? 'Mietvertrag' : null,
$record->confirmation_sent_at ? 'Bestätigung gesendet am '.$record->confirmation_sent_at->format('d.m.Y') : null,
])->filter()->implode(' · ') ?: 'Noch keine'),
TextEntry::make('template')->label('Vorlage')->state(fn (Booking $record): string => isset($record->offer_terms['template'])
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')->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)'),
]),
@@ -125,6 +122,7 @@ public static function configure(Schema $schema): Schema
TextEntry::make('status')->label('Status')->badge(),
TextEntry::make('case_type')->label('Vorgangsart')->state(fn (Booking $record): string => strtoupper($record->caseType()->value).' – '.$record->caseType()->getLabel()),
TextEntry::make('intake')->label('Eingangsart')->state(fn (Booking $record): string => $record->intake?->getLabel() ?? '–'),
TextEntry::make('sources')->label('Quellen und Kalenderdarstellungen')->state(fn (Booking $record): HtmlString => self::sources($record))->html()->columnSpanFull(),
TextEntry::make('profile')->label('Abwicklungsprofil (eingefroren)')->state(fn (Booking $record): HtmlString => self::profile($record))->html()->columnSpanFull(),
TextEntry::make('hold_expires_at')->label('Reserviert bis')->dateTime('d.m.Y, H:i')->placeholder('–'),
TextEntry::make('offer_hash')->label('Angebot (Prüfsumme)')->state(fn (Booking $record): ?string => $record->offer_version > 0 ? 'Version '.$record->offer_version.' · '.substr((string) $record->offer_hash, 0, 16) : null)->placeholder('–'),
@@ -163,6 +161,42 @@ private static function nextStep(Booking $booking): HtmlString
.'<div style="margin-top:.5rem;color:#6b7280;font-size:.9rem">'.$mode.'</div>');
}
/**
* Every portal entry (calendar or e-mail) that belongs to the case, and what the intake recorded about it.
*/
private static function sources(Booking $booking): HtmlString
{
$lines = BlockedPeriod::query()->withTrashed()->with('channel')->where('linked_booking_id', $booking->id)->orderBy('id')->get()
->map(fn (BlockedPeriod $entry): string => e(($entry->source === 'email' ? 'E-Mail' : 'Kalender').' von '.($entry->channel?->name ?? '–').': '.$entry->starts_on->format('d.m.').'–'.$entry->ends_on->format('d.m.Y')
.($entry->trashed() ? ' · nicht mehr im Kalender' : '').($entry->starts_on->equalTo($booking->arrival) && $entry->ends_on->equalTo($booking->departure) ? '' : ' · abweichende Termine').' · Kennung '.$entry->external_uid));
$observations = IntakeObservation::query()->with('channel')->where('booking_id', $booking->id)->orderBy('occurred_at')->get()
->map(fn (IntakeObservation $observation): string => e($observation->occurred_at->format('d.m.Y H:i').' · '.$observation->sourceLabel().' '.$observation->channel?->name.' · '.$observation->outcome->getLabel().($observation->applied ? '' : ' (nur protokolliert)')));
$html = $lines->isEmpty() ? 'Keine Portaleinträge zugeordnet.' : $lines->implode('<br>');
return new HtmlString($observations->isEmpty() ? $html : $html.'<br><span style="color:#6b7280">Eingang: '.$observations->implode('<br>').'</span>');
}
/**
* The documents made for the case, as recorded when they were created (kind, template, date).
*/
private static function documents(Booking $booking): HtmlString
{
$lines = $booking->events()->where('type', 'document')->whereNotNull('data')->reorder()->orderBy('occurred_at')->orderBy('id')->get()
->filter(fn ($event): bool => isset($event->data['kind']))
->map(fn ($event): string => e($event->occurred_at->format('d.m.Y').' · '.$event->summary));
if ($lines->isEmpty()) {
$lines = collect([
$booking->offer_path ? 'Angebot Version '.$booking->offer_version : null,
$booking->contract_path ? 'Mietvertrag' : null,
$booking->confirmation_sent_at ? 'Bestätigung gesendet am '.$booking->confirmation_sent_at->format('d.m.Y') : null,
])->filter()->map(fn (string $line): string => e($line));
}
return new HtmlString($lines->isEmpty() ? 'Noch keine' : $lines->implode('<br>'));
}
/**
* @return list<string>
*/
@@ -2,9 +2,13 @@
namespace App\Filament\Resources\ChannelTasks\Tables;
use App\Enums\ChannelTaskAction;
use App\Enums\ChannelTaskProof;
use App\Enums\ChannelTaskStatus;
use App\Models\ChannelTask;
use Filament\Actions\Action;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Textarea;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
@@ -24,6 +28,8 @@ public static function configure(Table $table): Table
TextColumn::make('reason')->label('Anlass')->wrap(),
TextColumn::make('status')->label('Status')->badge()
->description(fn (ChannelTask $record): ?string => $record->completed_by ? "{$record->completed_by}, {$record->completed_at?->format('d.m. H:i')}" : null),
TextColumn::make('proof')->label('Nachweis')->state(fn (ChannelTask $record): string => $record->proofLabel())
->description(fn (ChannelTask $record): ?string => $record->proof_by ? "{$record->proof_by}, {$record->proof_at?->format('d.m. H:i')}" : null)->wrap(),
TextColumn::make('created_at')->label('Seit')->since(),
TextColumn::make('automation_error')->label('Automatisierung')->placeholder('–')->limit(40)->toggleable(isToggledHiddenByDefault: true),
])
@@ -45,7 +51,26 @@ public static function configure(Table $table): Table
->icon(Heroicon::OutlinedCheck)
->color('success')
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open)
->action(fn (ChannelTask $record) => $record->complete(auth()->user()->name)),
->modalHeading(fn (ChannelTask $record): string => ($record->action === ChannelTaskAction::Block ? 'Sperre in ' : 'Freigabe in ').$record->channel->name.' erledigt')
->modalDescription('Was können Sie sagen? Ein bereitgestellter Kalender beweist nicht, dass das Portal ihn schon übernommen hat.')
->fillForm(['proof' => ChannelTaskProof::Initiated->value])
->schema(fn (ChannelTask $record): array => [
Radio::make('proof')->hiddenLabel()->required()
->options(collect(ChannelTaskProof::cases())->mapWithKeys(fn (ChannelTaskProof $proof): array => [$proof->value => $proof->question($record->action === ChannelTaskAction::Block)])->all()),
Textarea::make('note')->label('Notiz (optional)')->placeholder('z. B. „im Vermieterkalender rot markiert“')->rows(2),
])
->action(fn (ChannelTask $record, array $data) => $record->complete(auth()->user()->name, ChannelTaskProof::from($data['proof']), $data['note'] ?? null)),
Action::make('prove')
->label('Nachweis ergänzen')
->icon(Heroicon::OutlinedShieldCheck)
->color('gray')
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Done && $record->proof !== ChannelTaskProof::Confirmed)
->schema(fn (ChannelTask $record): array => [
Radio::make('proof')->hiddenLabel()->required()
->options(collect([ChannelTaskProof::Observed, ChannelTaskProof::Confirmed])->mapWithKeys(fn (ChannelTaskProof $proof): array => [$proof->value => $proof->question($record->action === ChannelTaskAction::Block)])->all()),
Textarea::make('note')->label('Notiz (optional)')->rows(2),
])
->action(fn (ChannelTask $record, array $data) => $record->prove(ChannelTaskProof::from($data['proof']), auth()->user()->name, $data['note'] ?? null)),
Action::make('dismiss')
->label('Verwerfen')
->icon(Heroicon::OutlinedXMark)
@@ -3,6 +3,7 @@
namespace App\Filament\Resources\Channels\Schemas;
use App\Channels\ChannelRegistry;
use App\Enums\CaseIntakeMode;
use App\Enums\ChannelBookingModel;
use App\Enums\ChannelEchoBehavior;
use App\Enums\ChannelExportMode;
@@ -55,6 +56,13 @@ public static function configure(Schema $schema, bool $selectProperty = false):
Select::make('status')->label('Kanalstatus')->options(ChannelStatus::class)->default(ChannelStatus::Setup)->required(),
Select::make('booking_model')->label('Was kommt über dieses Portal?')->options(ChannelBookingModel::class)->default(ChannelBookingModel::Mixed)->required()
->helperText('„Portalbuchung“ und „Gemischt“ gelten als Sofortbuchung: automatische Angebote für diese Wohnung warten, bis das Portal unseren Kalender abgerufen hat. „Vermittlung / Anfrage“: keine Sofortbuchung.'),
Select::make('case_intake')
->label('Erkannte Buchungen automatisch als Vorgang übernehmen?')
->options(CaseIntakeMode::class)
->default(CaseIntakeMode::Off)
->required()
->helperText('Zuerst „Beobachten“: Dann entsteht nichts, aber das Eingangsprotokoll (Expertenansicht) zeigt, welche Vorgänge entstanden wären. Unklare Belegungen und Meldungen zu gebuchten Vorgängen erscheinen unter „Zu erledigen“. Unterlagen gehen nie ohne Ihre Freigabe hinaus.')
->columnSpanFull(),
...self::processSections(),
Select::make('connector')
->label('Kalenderanbindung')
@@ -3,7 +3,9 @@
namespace App\Filament\Resources\ContractTemplates\Pages;
use App\Filament\Resources\ContractTemplates\ContractTemplateResource;
use App\Models\ContractTemplate;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
class CreateContractTemplate extends CreateRecord
{
@@ -21,4 +23,16 @@ protected function mutateFormDataBeforeCreate(array $data): array
return $data;
}
/**
* @param array<string, mixed> $data
*/
protected function handleRecordCreation(array $data): Model
{
$template = new ContractTemplate(collect($data)->except(['is_released', 'is_portal_terms'])->all());
$template->applyStatements((bool) ($data['is_released'] ?? false), (bool) ($data['is_portal_terms'] ?? false), (string) auth()->user()?->name);
$template->save();
return $template;
}
}
@@ -3,8 +3,10 @@
namespace App\Filament\Resources\ContractTemplates\Pages;
use App\Filament\Resources\ContractTemplates\ContractTemplateResource;
use App\Models\ContractTemplate;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
class EditContractTemplate extends EditRecord
{
@@ -14,4 +16,26 @@ protected function getHeaderActions(): array
{
return [DeleteAction::make()];
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeFill(array $data): array
{
return [...$data, 'is_released' => $data['released_at'] !== null, 'is_portal_terms' => $data['portal_terms_confirmed_at'] !== null];
}
/**
* @param array<string, mixed> $data
*/
protected function handleRecordUpdate(Model $record, array $data): Model
{
/** @var ContractTemplate $record */
$record->fill(collect($data)->except(['is_released', 'is_portal_terms'])->all());
$record->applyStatements((bool) ($data['is_released'] ?? false), (bool) ($data['is_portal_terms'] ?? false), (string) auth()->user()?->name);
$record->save();
return $record;
}
}
@@ -9,6 +9,7 @@
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\Schema;
@@ -65,6 +66,17 @@ public static function configure(Schema $schema): Schema
Textarea::make('texts.closing')->label('Vertragsschluss')->rows(3)->columnSpanFull(),
Textarea::make('texts.contract_note')->label('Hinweis im Angebots-PDF')->rows(3)->columnSpanFull(),
]),
Section::make('Freigabe')
->description('Ihre Erklärung zu genau diesem Text. Ändert sich der Text, gilt sie erst nach erneutem Speichern mit Haken wieder; eine neue Version beginnt ohne Freigabe.')
->columnSpanFull()
->schema([
Toggle::make('is_released')
->label('Für den Versand an Gäste freigegeben')
->helperText('Ohne Freigabe wird die Vorlage nie automatisch versendet; von Hand nur nach ausdrücklicher Bestätigung im Vorgang.'),
Toggle::make('is_portal_terms')
->label('Gibt nur wieder, was Gäste bei der Buchung über das Portal akzeptieren')
->helperText('Nur für Vorlagen, die bei beim Portal gebuchten Vorgängen verwendet werden. Ohne diesen Haken weist der Vorgang auf Gebühren und Bedingungen der Vorlage hin und verlangt vor dem Versand eine Bestätigung.'),
]),
Textarea::make('notes')->label('Interne Notiz')->rows(2)->columnSpanFull(),
]);
}
@@ -21,6 +21,8 @@ public static function configure(Table $table): Table
->columns([
TextColumn::make('name')->label('Vorlage')->searchable()->weight('medium'),
TextColumn::make('version')->label('Version')->badge(),
IconColumn::make('released')->label('Freigegeben')->boolean()->state(fn (ContractTemplate $record): bool => $record->isReleased()),
IconColumn::make('portal_terms')->label('Portalbedingungen')->boolean()->state(fn (ContractTemplate $record): bool => $record->confirmsPortalTerms()),
IconColumn::make('used')->label('In Angeboten verwendet')->boolean()->state(fn (ContractTemplate $record): bool => $record->isUsed()),
TextColumn::make('updated_at')->label('Geändert')->dateTime('d.m.Y, H:i'),
])
@@ -0,0 +1,83 @@
<?php
namespace App\Filament\Resources\IntakeObservations;
use App\Enums\CaseIntakeMode;
use App\Enums\IntakeOutcome;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\IntakeObservations\Pages\ListIntakeObservations;
use App\Models\Channel;
use App\Models\IntakeObservation;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use UnitEnum;
/**
* The intake record (expert view): what came in over each portal, what the intake recognised, whether it acted or only
* observed, and why. Read only – the work itself happens under "Zu erledigen" and on the case page.
*/
class IntakeObservationResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = IntakeObservation::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedInboxArrowDown;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?string $navigationLabel = 'Eingangsprotokoll';
protected static ?string $modelLabel = 'Eingang';
protected static ?string $pluralModelLabel = 'Eingangsprotokoll';
protected static ?int $navigationSort = 20;
public static function canCreate(): bool
{
return false;
}
public static function table(Table $table): Table
{
return $table
->description('Was über die Portale hereinkam und was daraus wurde. „Nur protokolliert“ heißt: Das Portal steht auf „Beobachten“ (oder es war nichts zu tun) – es ist nichts entstanden.')
->defaultSort('occurred_at', 'desc')
->modifyQueryUsing(fn ($query) => $query->with(['channel', 'booking']))
->columns([
TextColumn::make('occurred_at')->label('Wann')->dateTime('d.m.Y H:i')->sortable(),
TextColumn::make('channel.name')->label('Portal')->description(fn (IntakeObservation $record): string => $record->sourceLabel()),
TextColumn::make('period')->label('Zeitraum')->state(fn (IntakeObservation $record): ?string => $record->starts_on ? $record->starts_on->format('d.m.').'–'.$record->ends_on?->format('d.m.Y') : null)->placeholder('–'),
TextColumn::make('outcome')->label('Ergebnis')->badge()->description(fn (IntakeObservation $record): string => implode(' ', (array) $record->reasons))->wrap(),
TextColumn::make('case_type')->label('Art')->formatStateUsing(fn (?string $state): string => strtoupper((string) $state))->placeholder('–'),
IconColumn::make('applied')->label('Ausgeführt')->boolean()->tooltip('Ja: Vorgang angelegt, zugeordnet, Aufgabe erstellt oder zur Klärung vorgelegt. Nein: nur protokolliert.'),
TextColumn::make('mode')->label('Einstellung')->formatStateUsing(fn (CaseIntakeMode $state): string => match ($state) {
CaseIntakeMode::Observe => 'Beobachten',
CaseIntakeMode::Create => 'Anlegen',
CaseIntakeMode::Continue => 'Anlegen + weiter',
CaseIntakeMode::Off => 'Aus',
})->toggleable(),
TextColumn::make('reference')->label('Buchungsnr.')->placeholder('–')->toggleable(),
TextColumn::make('booking.reference')->label('Vorgang')->placeholder('–')
->url(fn (IntakeObservation $record): ?string => $record->booking ? BookingResource::getUrl('view', ['record' => $record->booking]) : null),
TextColumn::make('missing')->label('Fehlt noch')->state(fn (IntakeObservation $record): string => implode(', ', (array) $record->missing))->placeholder('–')->wrap()->toggleable(isToggledHiddenByDefault: true),
])
->filters([
SelectFilter::make('channel_id')->label('Portal')->options(fn (): array => Channel::query()->orderBy('name')->pluck('name', 'id')->all()),
SelectFilter::make('outcome')->label('Ergebnis')->options(IntakeOutcome::class),
SelectFilter::make('applied')->label('Ausgeführt')->options(['1' => 'ja', '0' => 'nur protokolliert']),
]);
}
public static function getPages(): array
{
return ['index' => ListIntakeObservations::route('/')];
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\IntakeObservations\Pages;
use App\Filament\Resources\IntakeObservations\IntakeObservationResource;
use Filament\Resources\Pages\ListRecords;
class ListIntakeObservations extends ListRecords
{
protected static string $resource = IntakeObservationResource::class;
}
@@ -3,7 +3,9 @@
namespace App\Filament\Resources\PortalOccupations\Pages;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use Filament\Actions\ActionGroup;
use Filament\Resources\Pages\ViewRecord;
use Filament\Support\Icons\Heroicon;
class ViewPortalOccupation extends ViewRecord
{
@@ -16,6 +18,9 @@ public function getTitle(): string
protected function getHeaderActions(): array
{
return PortalOccupationResource::occupationActions();
$actions = PortalOccupationResource::occupationActions();
[$primary, $more] = [array_slice($actions, 0, 3), array_slice($actions, 3)];
return [...$primary, ActionGroup::make($more)->label('Weitere Möglichkeiten')->icon(Heroicon::OutlinedEllipsisHorizontal)->button()->color('gray')];
}
}
@@ -4,6 +4,7 @@
use App\Actions\ClassifyPortalOccupation;
use App\Actions\OpenPortalFile;
use App\Actions\ResolveChannelOccupation;
use App\Enums\OccupationKind;
use App\Exceptions\ReservationException;
use App\Filament\Actions\AssignGuestAction;
@@ -15,11 +16,13 @@
use App\Filament\Resources\PortalOccupations\Pages\ManagePortalOccupations;
use App\Filament\Resources\PortalOccupations\Pages\ViewPortalOccupation;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Select;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
@@ -80,19 +83,85 @@ public static function table(Table $table): Table
TextColumn::make('channel.name')->label('Importkanal'),
TextColumn::make('property.name')->label('Wohnung')->toggleable(),
TextColumn::make('needs_review')->label('Prüffall')->formatStateUsing(fn (bool $state): string => $state ? 'Bitte prüfen' : '–')->description(fn (BlockedPeriod $record): ?string => $record->review_note),
])->recordActions([Action::make('fileLink')->label('Als Buchung übernehmen')->icon(Heroicon::OutlinedFolderPlus)->button()->color('primary')->visible(fn (BlockedPeriod $record): bool => static::canOpenFile($record))->url(fn (BlockedPeriod $record): string => static::getUrl('view', ['record' => $record])), static::showFileAction()->button(), ViewAction::make(), ActionGroup::make(static::occupationActions(withFile: false))->label('Weitere Aktionen')]);
])->recordActions([Action::make('clarifyLink')->label('Klären')->icon(Heroicon::OutlinedQuestionMarkCircle)->button()->color('warning')->visible(fn (BlockedPeriod $record): bool => static::isUnclear($record))->url(fn (BlockedPeriod $record): string => static::getUrl('view', ['record' => $record])), Action::make('fileLink')->label('Als Buchung übernehmen')->icon(Heroicon::OutlinedFolderPlus)->button()->color('primary')->visible(fn (BlockedPeriod $record): bool => static::canOpenFile($record))->url(fn (BlockedPeriod $record): string => static::getUrl('view', ['record' => $record])), static::showFileAction()->button(), ViewAction::make(), ActionGroup::make(static::occupationActions(withFile: false))->label('Weitere Aktionen')]);
}
public static function occupationActions(bool $withFile = true): array
{
return [
...($withFile ? [static::openFileAction(), static::showFileAction()] : []),
...($withFile ? [static::clarifyAction(), static::openFileAction(), static::showFileAction()] : []),
AssignGuestAction::make(),
static::classificationAction(),
...BlockedPeriodResource::portalActions(),
];
}
/**
* Whether the entry still waits for the landlord's answer (it is listed under "Zu erledigen").
*/
public static function isUnclear(BlockedPeriod $record): bool
{
return ! $record->trashed() && BlockedPeriod::query()->unclear()->whereKey($record->id)->exists();
}
/**
* The one question for an unclear portal entry, in plain words: is it a booking (then it becomes a case), does it
* belong to a case that already exists, or is it no booking at all? The detailed tools stay under "Weitere".
*/
public static function clarifyAction(): Action
{
return Action::make('clarify')->label('Klären: Was ist das?')->icon(Heroicon::OutlinedQuestionMarkCircle)->color('primary')
->visible(fn (BlockedPeriod $record): bool => static::isUnclear($record) && ! $record->is_representation)
->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false)
->modalHeading(fn (BlockedPeriod $record): string => 'Belegung von '.($record->channel?->name ?? 'einem Portal').' am '.$record->starts_on->format('d.m.').'–'.$record->ends_on->format('d.m.Y'))
->modalDescription(fn (BlockedPeriod $record): string => 'Für diesen Zeitraum wurde eine Belegung gemeldet. Bitte wählen Sie, was es ist.'.($record->review_note ? ' Hinweis: '.$record->review_note : ''))
->modalSubmitActionLabel('Übernehmen')
->schema(fn (BlockedPeriod $record): array => [
Radio::make('answer')->hiddenLabel()->required()->live()->options(array_filter([
'booking' => static::canOpenFile($record) ? 'Eine Buchung über '.($record->channel?->name ?? 'das Portal').' – als Vorgang übernehmen' : null,
'case' => static::sameNightCases($record) !== [] ? 'Gehört zu einem Vorgang, der schon da ist' : null,
'block' => 'Keine Buchung: Sperre, eigene Nutzung oder Spiegelung eines anderen Portals',
])),
Select::make('booking_id')->label('Vorgang')->options(fn (): array => static::sameNightCases($record))
->visible(fn (Get $get): bool => $get('answer') === 'case')->required(fn (Get $get): bool => $get('answer') === 'case'),
])
->action(function (BlockedPeriod $record, array $data, OpenPortalFile $open, ResolveChannelOccupation $resolve, ClassifyPortalOccupation $classify) {
try {
if ($data['answer'] === 'booking') {
$booking = $open->handle($record);
Notification::make()->title('Als Buchung übernommen')->success()->send();
return redirect(BookingResource::getUrl('view', ['record' => $booking]));
}
if ($data['answer'] === 'case') {
$resolve->handle($record, 'booking', (int) $data['booking_id']);
Notification::make()->title('Dem Vorgang zugeordnet')->success()->send();
return null;
}
$classify->handle($record, OccupationKind::Block);
$record->refresh()->forceFill(['needs_review' => false, 'reviewed_at' => now(), 'review_note' => 'Persönlich als Sperre eingeordnet.'])->save();
Notification::make()->title('Als Sperre eingeordnet')->success()->send();
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
}
return null;
});
}
/**
* Cases of the same property with exactly these nights (the only ones the entry may belong to).
*
* @return array<int, string>
*/
public static function sameNightCases(BlockedPeriod $record): array
{
return Booking::query()->occupying()->with('guest')->where('property_id', $record->property_id)
->whereDate('arrival', $record->starts_on)->whereDate('departure', $record->ends_on)->get()
->mapWithKeys(fn (Booking $booking): array => [$booking->id => $booking->reference.' · '.$booking->guestName().' · '.$booking->bookingChannelLabel()])->all();
}
/**
* Takes a reservation from a portal calendar over as a case (no second, manual "file").
*/
@@ -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.');
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Http\Controllers;
use App\Documents\DocumentComposer;
use App\Documents\RentalContract;
use App\Enums\DocumentKind;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* The PDF of a document composition as it would be sent, for the landlord's preview in the admin area. Nothing is
* stored; the case is only read (and only within the current landlord, by the tenant scope of the route binding).
*/
class DocumentPreviewController extends Controller
{
public function __invoke(Request $request, Booking $booking, string $kind, DocumentComposer $composer, RentalContract $contract): Response
{
$documentKind = DocumentKind::tryFrom($kind);
abort_if($documentKind === null || ! $documentKind->isForGuests(), 404);
$changes = json_decode((string) base64_decode((string) $request->query('changes', ''), true), true);
$composition = $composer->compose($booking, $documentKind, is_array($changes) ? $changes : []);
$pdf = $contract->render($composition->draft, $documentKind, draft: $documentKind === DocumentKind::Offer);
return response($pdf, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="Vorschau-'.$documentKind->fileName().'-'.$booking->reference.'.pdf"',
'Cache-Control' => 'no-store',
]);
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Listeners;
use App\Models\Tenant;
use App\Support\Settings;
use Illuminate\Mail\Events\MessageSending;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
/**
* The one gate every outgoing e-mail passes – whichever mailer, mailable or notification sent it (Laravel fires
* MessageSending for every message right before the transport). In test operation it replaces every recipient (To, Cc,
* Bcc) by the test recipient; when no test recipient can be determined, the mail is not sent at all. Only a landlord
* switched live (and no server override) lets mails reach their real recipients.
*
* The operating mode is read fresh from the database for every mail, so a switch in the admin applies at once, also in
* long-running processes. Without any landlord the installation counts as being in test operation.
*/
class EnforceMailTestMode
{
public const ORIGINAL_RECIPIENTS_HEADER = 'X-Fewo-Testbetrieb-Original';
/**
* @return false|null false stops the mail; null lets it go on
*/
public function handle(MessageSending $event): ?bool
{
$message = $event->message;
$tenant = Settings::tenant();
$tenant = $tenant instanceof Tenant ? ($tenant->fresh() ?? $tenant) : null;
$override = config('fewo.mail_redirect_to');
if (blank($override) && $tenant?->isLive()) {
return null;
}
$redirect = Settings::mailRedirectFor($tenant);
if (blank($redirect) || filter_var($redirect, FILTER_VALIDATE_EMAIL) === false) {
// Test operation without anybody to redirect to: never fall through to the real recipients.
Log::warning('E-Mail im Testbetrieb nicht versendet: keine Testadresse eingerichtet.', ['subject' => $message instanceof Email ? $message->getSubject() : null, 'tenant' => $tenant?->id]);
return false;
}
if (! $message instanceof Email) {
Log::warning('E-Mail im Testbetrieb nicht versendet: unbekannter Nachrichtentyp.', ['type' => $message::class]);
return false;
}
$original = collect([...$message->getTo(), ...$message->getCc(), ...$message->getBcc()])
->map(fn (Address $address): string => $address->getAddress())->unique()->implode(', ');
$headers = $message->getHeaders();
$headers->remove('Cc');
$headers->remove('Bcc');
$headers->remove(self::ORIGINAL_RECIPIENTS_HEADER);
$message->to($redirect);
if ($original !== '') {
$headers->addTextHeader(self::ORIGINAL_RECIPIENTS_HEADER, mb_substr($original, 0, 900));
}
return null;
}
}
+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');
}
}
+47
View File
@@ -0,0 +1,47 @@
<?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 booking documentation for a booking already binding on a portal (A3/A4): the stay as booked there and our
* document, without an acceptance link and without a cancellation link of our own (E-004).
*/
class BookingDocumentation extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Ihre Buchungsunterlagen '.($this->booking->portal_reference ?? $this->booking->reference),
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(markdown: 'mail.booking-documentation');
}
/**
* @return list<Attachment>
*/
public function attachments(): array
{
$path = app(RentalContract::class)->absolutePath($this->booking);
return $path ? [Attachment::fromPath($path)->as("Buchungsunterlagen-{$this->booking->reference}.pdf")->withMime('application/pdf')] : [];
}
}
+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();
}
}
+4 -2
View File
@@ -4,6 +4,7 @@
use App\Channels\ChannelRegistry;
use App\Channels\Contracts\ChannelConnector;
use App\Enums\CaseIntakeMode;
use App\Enums\ChannelBookingModel;
use App\Enums\ChannelEchoBehavior;
use App\Enums\ChannelExportMode;
@@ -26,7 +27,7 @@
* A sales channel (portal) of a property. Our system leads: occupations are imported from the
* channel and every channel gets its own export feed without its own occupations.
*/
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at', 'payment_tasks_inquiry', 'payment_tasks_reservation', 'contract_template_id', 'contract_template_reservation_id', 'process_overrides'])]
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at', 'payment_tasks_inquiry', 'payment_tasks_reservation', 'contract_template_id', 'contract_template_reservation_id', 'process_overrides', 'case_intake'])]
#[Hidden(['export_token', 'previous_export_token', 'export_snapshot', 'settings', 'ical_analysis'])]
class Channel extends Model
{
@@ -36,7 +37,7 @@ class Channel extends Model
protected $attributes = [
'status' => 'setup', 'booking_model' => 'mixed', 'import_enabled' => false,
'export_enabled' => false, 'export_mode' => 'test',
'echo_behavior' => 'unverified',
'echo_behavior' => 'unverified', 'case_intake' => 'off',
];
protected static function booted(): void
@@ -63,6 +64,7 @@ protected function casts(): array
return [
'settings' => 'array',
'process_overrides' => 'array',
'case_intake' => CaseIntakeMode::class,
'ical_analysis' => 'encrypted:array',
'ical_analyzed_at' => 'immutable_datetime',
'ical_rules' => 'array',
+37 -2
View File
@@ -4,6 +4,7 @@
use App\Availability\AvailabilityChecker;
use App\Enums\ChannelTaskAction;
use App\Enums\ChannelTaskProof;
use App\Enums\ChannelTaskStatus;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\ChannelTaskFactory;
@@ -18,7 +19,7 @@
* A change that has to be made by hand (or by an external automation) on a portal that
* cannot be kept in sync fast enough by calendar feeds, e.g. because of instant booking.
*/
#[Fillable(['channel_id', 'action', 'starts_on', 'ends_on', 'reason', 'status', 'completed_by', 'completed_at', 'reminded_at', 'automation_sent_at', 'automation_error'])]
#[Fillable(['channel_id', 'action', 'starts_on', 'ends_on', 'reason', 'status', 'completed_by', 'completed_at', 'reminded_at', 'automation_sent_at', 'automation_error', 'proof', 'proof_note', 'proof_at', 'proof_by'])]
class ChannelTask extends Model
{
/** @use HasFactory<ChannelTaskFactory> */
@@ -39,6 +40,8 @@ protected function casts(): array
'completed_at' => 'immutable_datetime',
'reminded_at' => 'immutable_datetime',
'automation_sent_at' => 'immutable_datetime',
'proof' => ChannelTaskProof::class,
'proof_at' => 'immutable_datetime',
];
}
@@ -60,7 +63,10 @@ protected function open(Builder $query): Builder
return $query->where('status', ChannelTaskStatus::Open);
}
public function complete(string $completedBy): void
/**
* Completes the task with the proof the person can give (at least: the change was made or started).
*/
public function complete(string $completedBy, ChannelTaskProof $proof = ChannelTaskProof::Initiated, ?string $note = null): void
{
if ($this->status !== ChannelTaskStatus::Open) {
return;
@@ -74,9 +80,38 @@ public function complete(string $completedBy): void
'status' => ChannelTaskStatus::Done,
'completed_by' => $completedBy,
'completed_at' => now(),
'proof' => $proof,
'proof_note' => filled($note) ? trim($note) : null,
'proof_at' => now(),
'proof_by' => $completedBy,
]);
}
/**
* Raises the proof of a completed task (e.g. the block was later seen in the portal); never lowers it.
*/
public function prove(ChannelTaskProof $proof, string $by, ?string $note = null): void
{
$order = array_flip(array_map(fn (ChannelTaskProof $case): string => $case->value, ChannelTaskProof::cases()));
if ($this->status !== ChannelTaskStatus::Done || ($this->proof !== null && $order[$proof->value] <= $order[$this->proof->value])) {
return;
}
$this->update(['proof' => $proof, 'proof_note' => filled($note) ? trim($note) : $this->proof_note, 'proof_at' => now(), 'proof_by' => $by]);
}
/**
* The state of the task in plain words, including how far it is proven.
*/
public function proofLabel(): string
{
return match ($this->status) {
ChannelTaskStatus::Open => 'noch offen',
ChannelTaskStatus::Dismissed => 'verworfen',
ChannelTaskStatus::Done => ($this->proof ?? ChannelTaskProof::Initiated)->getLabel().($this->proof_note ? ' ('.$this->proof_note.')' : ''),
};
}
/**
* Human readable period, e.g. "14.06.2027 – 21.06.2027".
*/
+69 -2
View File
@@ -12,13 +12,23 @@
* A version of contract texts for offers (e.g. conditions demanded by a portal). The texts replace the website
* texts of the same meaning when an offer is made; the offer then freezes a copy. A version that has been used in
* an offer is never edited – a new version is created instead.
*
* A version goes to guests automatically only when it is released; for bookings already binding on a portal it must in
* addition be confirmed as reproducing only what guests accept there (E-004). Both statements belong to the text: they
* lapse when the text changes, and a new version starts without them.
*/
#[Fillable(['name', 'version', 'texts', 'body', 'annex_title', 'annex_body', 'cancellation_policy_id', 'annex_ids', 'notes'])]
#[Fillable(['name', 'version', 'texts', 'body', 'annex_title', 'annex_body', 'cancellation_policy_id', 'annex_ids', 'notes', 'released_at', 'released_by', 'portal_terms_confirmed_at', 'portal_terms_confirmed_by'])]
class ContractTemplate extends Model
{
use BelongsToTenant;
/** Form/storage key => website text key it replaces in an offer. */
/** Attributes whose change makes the release and the portal confirmation lapse. */
/** Whether the statements were given for the pending save (then a text change does not withdraw them). */
private bool $statementsApplied = false;
private const CONTENT = ['texts', 'body', 'annex_title', 'annex_body', 'cancellation_policy_id', 'annex_ids'];
public const TEXTS = [
'intro' => 'contract.intro',
'terms' => 'contract.terms',
@@ -35,7 +45,64 @@ class ContractTemplate extends Model
*/
protected function casts(): array
{
return ['texts' => 'array', 'version' => 'integer', 'annex_ids' => 'array'];
return ['texts' => 'array', 'version' => 'integer', 'annex_ids' => 'array', 'released_at' => 'datetime', 'portal_terms_confirmed_at' => 'datetime'];
}
protected static function booted(): void
{
static::saved(function (ContractTemplate $template): void {
$template->statementsApplied = false;
});
static::saving(function (ContractTemplate $template): void {
if ($template->exists && $template->isDirty(self::CONTENT) && ! $template->statementsApplied) {
if (! $template->isDirty('released_at')) {
$template->released_at = null;
$template->released_by = null;
}
if (! $template->isDirty('portal_terms_confirmed_at')) {
$template->portal_terms_confirmed_at = null;
$template->portal_terms_confirmed_by = null;
}
}
});
}
/**
* Records the landlord's statements on the (possibly just changed) text: a statement is renewed when it is given for
* a changed text, kept when nothing changed and withdrawn when it is not given.
*/
public function applyStatements(bool $released, bool $portalTerms, string $actor): self
{
$changed = $this->isDirty(self::CONTENT);
$this->statementsApplied = true;
if (! $released) {
$this->forceFill(['released_at' => null, 'released_by' => null]);
} elseif ($changed || ! $this->isReleased()) {
$this->forceFill(['released_at' => now(), 'released_by' => $actor]);
}
if (! $portalTerms) {
$this->forceFill(['portal_terms_confirmed_at' => null, 'portal_terms_confirmed_by' => null]);
} elseif ($changed || ! $this->confirmsPortalTerms()) {
$this->forceFill(['portal_terms_confirmed_at' => now(), 'portal_terms_confirmed_by' => $actor]);
}
return $this;
}
public function isReleased(): bool
{
return $this->released_at !== null;
}
/**
* Whether the landlord confirmed that this version only reproduces the terms guests accept when booking on a portal.
*/
public function confirmsPortalTerms(): bool
{
return $this->portal_terms_confirmed_at !== null;
}
/**
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace App\Models;
use App\Enums\CaseIntakeMode;
use App\Enums\IntakeOutcome;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One entry of the intake record: an incoming portal event, what the intake recognised and whether it acted. The same
* event with the same result is recorded once (fingerprint), however often the calendar is read or the mail arrives.
*/
#[Fillable(['channel_id', 'blocked_period_id', 'portal_email_id', 'booking_id', 'fingerprint', 'source', 'mode', 'outcome', 'applied', 'case_type', 'starts_on', 'ends_on', 'reference', 'reasons', 'missing', 'occurred_at'])]
class IntakeObservation extends Model
{
use BelongsToTenant;
public const SOURCE_CALENDAR = 'calendar';
public const SOURCE_MAIL = 'mail';
public const SOURCE_ADOPTION = 'adoption';
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'mode' => CaseIntakeMode::class,
'outcome' => IntakeOutcome::class,
'applied' => 'boolean',
'starts_on' => 'immutable_date',
'ends_on' => 'immutable_date',
'reasons' => 'array',
'missing' => 'array',
'occurred_at' => 'immutable_datetime',
];
}
/** @return BelongsTo<Channel, $this> */
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
/** @return BelongsTo<Booking, $this> */
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
/** @return BelongsTo<BlockedPeriod, $this> */
public function blockedPeriod(): BelongsTo
{
return $this->belongsTo(BlockedPeriod::class)->withTrashed();
}
public function sourceLabel(): string
{
return match ($this->source) {
self::SOURCE_MAIL => 'Portal-E-Mail',
self::SOURCE_ADOPTION => 'Bestandsübernahme',
default => 'Portalkalender',
};
}
}
+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',
+2 -1
View File
@@ -28,7 +28,7 @@
'channel_stale_after_minutes', 'channel_task_reminder_after_minutes',
'reminder_interval_days', 'digest_daily', 'digest_weekly', 'digest_weekday', 'digest_hour', 'digest_sections',
'digest_when_empty', 'digest_daily_sent_on', 'digest_weekly_sent_on',
'process_defaults',
'process_defaults', 'document_releases',
])]
class Tenant extends Model
{
@@ -76,6 +76,7 @@ protected function casts(): array
'digest_hour' => 'integer',
'digest_sections' => 'array',
'process_defaults' => 'array',
'document_releases' => 'array',
'digest_when_empty' => 'boolean',
'digest_daily_sent_on' => 'immutable_date',
'digest_weekly_sent_on' => 'immutable_date',
+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;
}
}
+92 -5
View File
@@ -2,11 +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;
@@ -26,6 +31,9 @@ class CaseActivities
/** Activities that are listed on their own in the work list (they are not "the" next step of a case). */
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', 'task_portal_cancellation'];
/**
* @return list<Activity>
*/
@@ -40,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;
@@ -88,17 +100,28 @@ public static function for(Booking $booking): array
default => ActivityState::Open,
};
$missing = $binding && $state === ActivityState::Open ? app(CaseAutomation::class)->documentBlockers($booking) : [];
$activities[] = new Activity('documents', $inquiry ? 'Buchungsbestätigung mit Vertrag senden' : 'Buchungsunterlagen an den Gast senden', $later($missing !== [] ? ActivityState::Waiting : $state),
// What the landlord still has to confirm (unreleased texts, terms not shown to be agreed on the portal).
$toConfirm = $binding && $state === ActivityState::Open && $missing === [] ? app(SendBookingDocuments::class)->compose($booking)->toConfirm() : [];
$activities[] = new Activity('documents', match (true) {
$state !== ActivityState::Open => $inquiry ? 'Buchungsbestätigung mit Vertrag senden' : 'Buchungsunterlagen an den Gast senden',
$inquiry => 'Buchungsbestätigung mit Vertrag prüfen und senden',
default => 'Buchungsunterlagen prüfen und senden',
}, $later($missing !== [] ? ActivityState::Waiting : $state),
match (true) {
$booking->confirmation_sent_at !== null => 'gesendet am '.$booking->confirmation_sent_at->format('d.m.Y'),
$state === ActivityState::Problem => 'Versand fehlgeschlagen',
$missing !== [] => 'wartet: '.implode(' ', $missing),
$toConfirm !== [] => 'vor dem Versand zu prüfen: '.implode(' ', $toConfirm),
default => null,
}, $binding && $missing === [] && $booking->confirmation_sent_at === null ? 'resendConfirmation' : null);
}, match (true) {
$state === ActivityState::Problem => 'resendConfirmation',
$binding && $missing === [] && $booking->confirmation_sent_at === null => 'sendDocuments',
default => null,
});
}
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(), url: ChannelTaskResource::getUrl());
$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 ($profile->payments() === Responsibility::Portal) {
@@ -120,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;
@@ -140,12 +167,62 @@ 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.
*/
public static function next(Booking $booking): ?Activity
{
foreach (self::for($booking) as $activity) {
$activities = self::for($booking);
// A report of the portal (cancellation, other dates) comes before everything else on the case.
usort($activities, fn (Activity $a, Activity $b): int => (int) in_array($b->key, self::URGENT, true) <=> (int) in_array($a->key, self::URGENT, true));
foreach ($activities as $activity) {
if ($activity->state->needsAction() && ! in_array($activity->key, self::LISTED_SEPARATELY, true)) {
return $activity;
}
@@ -160,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'));
+6 -10
View File
@@ -3,7 +3,7 @@
namespace App\Process;
use App\Actions\AutoOffer;
use App\Actions\ConfirmBooking;
use App\Actions\SendBookingDocuments;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
@@ -13,14 +13,15 @@
/**
* Carries a case on by itself as far as its data allows – only when the case is handled automatically. What it may do
* is what the landlord would do next anyway: send the offer of a request, or send the documents of a booking that is
* binding on a portal once the guest's e-mail address and the price are known. Whatever stops it is returned in plain
* is what the landlord would do next anyway: send the offer of a request, or send the documents of a binding booking
* once their composition is complete and needs no confirmation (template released and, for portal bookings, confirmed
* as the portal's terms). Whatever stops it is returned in plain
* words; the case then shows it as a task. Never touches a case whose profile was taken over from the old data (the
* automation did not exist for those cases before).
*/
class CaseAutomation
{
public function __construct(private AutoOffer $autoOffer, private ConfirmBooking $confirm) {}
public function __construct(private AutoOffer $autoOffer, private SendBookingDocuments $documents) {}
/**
* @return list<string> what keeps the case from going on automatically (empty: nothing to do or done)
@@ -52,12 +53,7 @@ private function step(Booking $booking): array
}
if ($booking->isBinding() && $booking->confirmation_sent_at === null && $booking->process()->documents() === Responsibility::Landlord && $booking->process()->origin !== 'migration') {
$missing = $this->documentBlockers($booking);
if ($missing !== []) {
return $missing;
}
return $this->confirm->deliver($booking) ? [] : ['Die Unterlagen konnten nicht versendet werden (siehe Postfach).'];
return $this->documents->automatically($booking);
}
return [];
+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;
+2 -2
View File
@@ -62,8 +62,8 @@ public static function items(): array
foreach (BlockedPeriod::query()->unclear()->with(['channel', 'property'])->whereDate('ends_on', '>=', today())->orderBy('starts_on')->get() as $occupation) {
$items[] = [
'title' => 'Unbekannte Belegung von '.($occupation->channel?->name ?? 'einem Portal').' – was ist das?',
'detail' => $occupation->starts_on->format('d.m.').'–'.$occupation->ends_on->format('d.m.Y').' · '.$occupation->property?->name,
'title' => 'Belegung von '.($occupation->channel?->name ?? 'einem Portal').' klären',
'detail' => 'Für den Zeitraum '.$occupation->starts_on->format('d.m.').'–'.$occupation->ends_on->format('d.m.Y').' wurde eine Belegung von '.($occupation->channel?->name ?? 'einem Portal').' gemeldet. Bitte klären Sie, um welche Art von Belegung es sich handelt. · '.$occupation->property?->name,
'url' => PortalOccupationResource::getUrl('view', ['record' => $occupation]),
'button' => 'Klären',
'tone' => 'warning',
@@ -4,6 +4,7 @@
use App\Enums\AdminMode;
use App\Filament\Pages\Dashboard;
use App\Http\Controllers\DocumentPreviewController;
use App\Http\Controllers\SwitchPropertyController;
use App\Http\Middleware\ResolveTheme;
use App\Models\User;
@@ -74,6 +75,7 @@ public function panel(Panel $panel): Panel
->renderHook(PanelsRenderHook::SIDEBAR_NAV_START, fn (): View => view('filament.property-switcher'))
->authenticatedRoutes(function (): void {
Route::post('wohnung-wechseln', SwitchPropertyController::class)->name('switch-property');
Route::get('vorgaenge/{booking}/dokument-vorschau/{kind}', DocumentPreviewController::class)->name('document-preview');
})
->navigationGroups(['Verwaltung', 'Einrichtung', 'Webseite', 'System'])
->colors([
+3 -7
View File
@@ -2,8 +2,8 @@
namespace App\Tenancy;
use App\Listeners\EnforceMailTestMode;
use App\Models\Tenant;
use App\Support\Settings;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Mail;
use Throwable;
@@ -146,7 +146,8 @@ public function apply(?Tenant $tenant): void
}
/**
* The mailer sends everything to one address while the landlord is in test mode.
* Rebuilds the mailers so that they use the sender of the current landlord. Where mails go in test operation is
* decided for every single mail by the one gate {@see EnforceMailTestMode}, not here.
*/
public function applyMailRouting(?Tenant $tenant): void
{
@@ -157,11 +158,6 @@ public function applyMailRouting(?Tenant $tenant): void
}
$manager->purge();
$redirect = Settings::mailRedirectFor($tenant);
if (filled($redirect)) {
$manager->alwaysTo($redirect);
}
}
/**
@@ -0,0 +1,44 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* Package 3 of UMSETZUNGSPLAN_v0.10 (documents): a contract template version is released for guests or not, and it may
* be confirmed as reproducing only what guests accept when booking on a portal (E-004). The landlord releases the texts
* of each document kind (tenants.document_releases).
*
* Existing template versions were used without such a release so far; they count as released to keep today's offers
* and confirmations working. None is confirmed as portal terms – that is the landlord's statement to make.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('contract_templates', function (Blueprint $table): void {
$table->timestamp('released_at')->nullable();
$table->string('released_by', 120)->nullable();
$table->timestamp('portal_terms_confirmed_at')->nullable();
$table->string('portal_terms_confirmed_by', 120)->nullable();
});
Schema::table('tenants', function (Blueprint $table): void {
$table->json('document_releases')->nullable();
});
DB::table('contract_templates')->update(['released_at' => now(), 'released_by' => 'Übernahme (bisher schon verwendet)']);
}
public function down(): void
{
Schema::table('contract_templates', function (Blueprint $table): void {
$table->dropColumn(['released_at', 'released_by', 'portal_terms_confirmed_at', 'portal_terms_confirmed_by']);
});
Schema::table('tenants', function (Blueprint $table): void {
$table->dropColumn('document_releases');
});
}
};
@@ -0,0 +1,62 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Package 4 of UMSETZUNGSPLAN_v0.10 (one intake for all channels): every channel says whether recognised portal
* bookings become cases by themselves – off (default for every existing and new channel), observe, or create –, what
* the intake recognised is recorded, and portal tasks record how far a block on the portal is proven. Purely additive.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('channels', function (Blueprint $table): void {
$table->string('case_intake', 12)->default('off');
});
Schema::create('intake_observations', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
$table->foreignId('channel_id')->constrained()->cascadeOnDelete();
$table->foreignId('blocked_period_id')->nullable()->constrained()->nullOnDelete();
$table->foreignId('portal_email_id')->nullable()->constrained()->nullOnDelete();
$table->foreignId('booking_id')->nullable()->constrained()->nullOnDelete();
$table->string('fingerprint', 64);
$table->string('source', 12);
$table->string('mode', 12);
$table->string('outcome', 20);
$table->boolean('applied')->default(false);
$table->string('case_type', 4)->nullable();
$table->date('starts_on')->nullable();
$table->date('ends_on')->nullable();
$table->string('reference', 100)->nullable();
$table->json('reasons')->nullable();
$table->json('missing')->nullable();
$table->timestamp('occurred_at');
$table->timestamps();
$table->unique(['tenant_id', 'fingerprint']);
$table->index(['channel_id', 'occurred_at']);
});
Schema::table('channel_tasks', function (Blueprint $table): void {
$table->string('proof', 12)->nullable();
$table->text('proof_note')->nullable();
$table->timestamp('proof_at')->nullable();
$table->string('proof_by')->nullable();
});
}
public function down(): void
{
Schema::table('channel_tasks', function (Blueprint $table): void {
$table->dropColumn(['proof', 'proof_note', 'proof_at', 'proof_by']);
});
Schema::dropIfExists('intake_observations');
Schema::table('channels', function (Blueprint $table): void {
$table->dropColumn('case_intake');
});
}
};
@@ -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']));
}
};
+1 -1
View File
@@ -74,7 +74,7 @@ ## 5. Konfiguration auf dem Server (`shared/.env`)
## 5a. E-Mail: Testbetrieb und scharf schalten
- **Betriebsart** in der Verwaltung: **System › Betrieb** (nur Administratoren). Jede Installation beginnt im **Testbetrieb**: alle E-Mails (an Gäste, Vermieterin, Benachrichtigungen) gehen ausschließlich an die dort eingetragene **Testadresse** (ohne Eintrag: `FEWO_NOTIFICATION_EMAIL`), egal was auf der Webseite eingetragen wurde. Ein gelber Hinweis oben in der Verwaltung zeigt das an. Erst „Scharf geschaltet“ liefert an die echten Empfänger.
- **Betriebsart** in der Verwaltung: **System › Betrieb** (nur Administratoren). Jede Installation beginnt im **Testbetrieb**: alle E-Mails (an Gäste, Vermieterin, Benachrichtigungen) gehen ausschließlich an die dort eingetragene **Testadresse** (ohne Eintrag: `FEWO_NOTIFICATION_EMAIL`), egal was auf der Webseite eingetragen wurde. Ein gelber Hinweis oben in der Verwaltung zeigt das an. Erst „Scharf geschaltet“ liefert an die echten Empfänger. Technisch prüft **eine einzige Schranke** jede ausgehende Mail unmittelbar vor dem Versand (`App\Listeners\EnforceMailTestMode`, Ereignis `MessageSending`, für jeden Mailer): Im Testbetrieb ersetzt sie An/Cc/Bcc durch die Testadresse (Original im Kopf `X-Fewo-Testbetrieb-Original`); **ohne jede Testadresse wird gar nichts versendet** (Warnung im Log). Der Modus wird für jede Mail frisch aus der Datenbank gelesen.
- **Adressen der internen Kommunikation** ebenfalls unter System › Betrieb: *Benachrichtigungen an* (mehrere Adressen: neue Anfragen, Angebotsantworten, Fristabläufe, Bewertungen, Portal-Mails/-Aufgaben, Kopie der Zahlungserinnerungen), *Kontakt- und Antwortadresse* (Webseite, Mietvertrag, Antwortadresse der Gäste-Mails), *Absendername/-adresse* (muss zum SMTP-Postfach `MAIL_USERNAME` passen – das Formular warnt). Ohne Eintrag gelten `FEWO_NOTIFICATION_EMAIL`, `FEWO_OWNER_EMAIL`, `MAIL_FROM_*` aus `shared/.env`.
- `FEWO_MAIL_REDIRECT_TO` in `shared/.env` ist eine **harte Überschreibung** für Testserver (gilt auch bei „scharf“); normalerweise leer lassen.
- **Versandweg:** Standard `MAIL_MAILER=log` – dann wird gar nichts zugestellt (auch nicht im Protokoll gespeichert). Für echten Versand in `shared/.env` `MAIL_MAILER=smtp` und `MAIL_PASSWORD=<Passwort des Postfachs info@fewo-stommer.de>` (nur selbst eintragen; Absender und SMTP-Anmeldung: `info@fewo-stommer.de`, Antwortadresse und Benachrichtigungen weiter `FEWO_OWNER_EMAIL`/`FEWO_NOTIFICATION_EMAIL` = fewo@stommer.de), dann `bash scripts/deploy.sh staging artisan optimize`.
-200
View File
@@ -1,200 +0,0 @@
{
"main": {
"id": "e551ceee940ecb6c",
"type": "split",
"children": [
{
"id": "45ad11e6bd426ed7",
"type": "tabs",
"children": [
{
"id": "6f2679f564edc126",
"type": "leaf",
"state": {
"type": "markdown",
"state": {
"file": "00_Prozesslandkarte.md",
"mode": "source",
"source": false
},
"icon": "lucide-file",
"title": "00_Prozesslandkarte"
}
}
]
}
],
"direction": "vertical"
},
"left": {
"id": "677ae3e7a3c51888",
"type": "split",
"children": [
{
"id": "d98321f663785e14",
"type": "tabs",
"children": [
{
"id": "cd2450a4f1ac56b2",
"type": "leaf",
"state": {
"type": "file-explorer",
"state": {
"sortOrder": "alphabetical",
"autoReveal": false,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-folder-closed",
"title": "Dateiexplorer"
}
},
{
"id": "5ac14d1839d3ff95",
"type": "leaf",
"state": {
"type": "search",
"state": {
"query": "",
"matchingCase": false,
"explainSearch": false,
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical"
},
"icon": "lucide-search",
"title": "Suchen"
}
},
{
"id": "faa5cd42d8f20e2b",
"type": "leaf",
"state": {
"type": "bookmarks",
"state": {
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-bookmark",
"title": "Lesezeichen"
}
}
]
}
],
"direction": "horizontal",
"width": 300
},
"right": {
"id": "d7407959975136f3",
"type": "split",
"children": [
{
"id": "5595addba8cae338",
"type": "tabs",
"children": [
{
"id": "7aa1456df3c0e543",
"type": "leaf",
"state": {
"type": "backlink",
"state": {
"file": "00_Prozesslandkarte.md",
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical",
"showSearch": false,
"searchQuery": "",
"backlinkCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-coming-in",
"title": "Rückverweise"
}
},
{
"id": "71826ebd06babd87",
"type": "leaf",
"state": {
"type": "outgoing-link",
"state": {
"file": "00_Prozesslandkarte.md",
"linksCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-going-out",
"title": "Ausgehende Links"
}
},
{
"id": "94047f11d8cf598a",
"type": "leaf",
"state": {
"type": "tag",
"state": {
"sortOrder": "frequency",
"useHierarchy": true,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-tags",
"title": "Tags"
}
},
{
"id": "ca2a154a0256f6d4",
"type": "leaf",
"state": {
"type": "all-properties",
"state": {
"sortOrder": "frequency",
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-archive",
"title": "Alle Eigenschaften"
}
},
{
"id": "154170f0a686e7f0",
"type": "leaf",
"state": {
"type": "outline",
"state": {
"file": "00_Prozesslandkarte.md",
"followCursor": false,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-list",
"title": "Gliederung"
}
}
]
}
],
"direction": "horizontal",
"width": 300,
"collapsed": true
},
"left-ribbon": {
"hiddenItems": {
"switcher:Schnellauswahl öffnen": false,
"graph:Graph-Ansicht öffnen": false,
"canvas:Neuen Canvas erstellen": false,
"daily-notes:Heutige Notiz öffnen": false,
"templates:Vorlage einfügen": false,
"command-palette:Befehlspalette öffnen": false,
"bases:Neue Base erstellen": false
}
},
"active": "6f2679f564edc126",
"lastOpenFiles": [
"00_Prozesslandkarte.md",
"00_Buchungsarchetypen.md",
"00_Portalprofile_und_Vertragsvorlagen.md",
"Buchsungsprozesse/Willkommen.md",
"README.md",
"QUELLENMANIFEST.md"
]
}
@@ -1,168 +0,0 @@
---
id: A00
typ: archetypenkatalog
titel: FewoPortal – Buchungsarchetypen und Verantwortungsübergaben
status: diskussionsentwurf
version: "0.9"
stand: 2026-11-01
prozess: V01
bezugsstand_prozessarchitektur: "0.7"
---
# A00 – Buchungsarchetypen und Verantwortungsübergaben
> **Arbeitsstand für das Fachinterview, nicht abschließend freigegeben.** Grundlage: Betreiberbeschreibung vom 31.10.2026; Übergaben `UEBERGABE-BUCHUNGSPROZESS.md` (30.10.2026) und `crystalline-floating-glacier.md` (31.10.2026); Prozessarchitektur v0.7 und Szenarien R01/R08. **Bestätigte Geschäftsregeln, aktueller Praxisablauf, Annahmen und offene Fragen werden getrennt ausgewiesen.**
## 1. Gemeinsamer Grundsatz
FewoPortal ist das **führende interne Buchungsverwaltungssystem** für mehrere kleine Vermieter mit typischerweise 1–3 Wohnungen je Vermieter. Es gibt **einen generischen Wertschöpfungsprozess V01** mit den Phasen:
1. **P01** Buchungseingang & Verfügbarkeitssicherung
2. **P02** Konditionen & Buchungsverbindlichkeit
3. **P03** Buchungsverwaltung & kaufmännische Abwicklung
4. **P04** Leistungsvorbereitung & Aufenthalt
5. **P05** Abschluss & Nachbereitung
**Archetypen sind Geschäftskonstellationen, keine getrennt zu implementierenden Workflows.** Sie bestimmen die bei Eintritt bekannten Tatsachen, Zuständigkeiten, notwendigen Aktivitäten, Kommunikationswege und Nachweise. Derselbe **Vorgang** und dieselben Fachfunktionen werden verwendet. Die früher diskutierte zusätzlich anzulegende „Buchungsakte“ entfällt als eigenständige fachliche Einheit. Ein Portal kann einzelne Tätigkeiten durchführen; FewoPortal behält den konsolidierten Vorgangsüberblick, ohne fremde Primärnachweise vorzutäuschen.
## 2. Katalog der sechs Archetypen
| ID | Geschäftskonstellation | Zustand beim Eingang | Vertragsunterlagen | Zahlung / Storno | Informationsbedarf |
|---|---|---|---|---|---|
| **A1** | Kompletter Vorgang über eigene Website / FewoPortal | Unverbindliche Anfrage | Verbindliches eigenes Angebot, fristgerechte Annahme, anschließend Vertragsdokumentation | Wir | Eigene Anfrage- und Gastdaten, ggf. ergänzen |
| **A2** | Unverbindliche Anfrage eines Vermittlungsportals, Eingang z. B. über Portalnachricht, E-Mail, Telefon oder erkennbare iCal-Information | Noch keine Buchungsverbindlichkeit | Angebot/Annahme/Vertrag bei uns | Typischerweise wir, profilabhängig | Häufig unvollständig; gezielte Nachforderung |
| **A3** | Externe Direktbuchung mit anschließender vollständiger Abwicklung durch uns | Bereits verbindliche Portalbuchung | Wir versenden Dokumentation der bestehenden Vereinbarung, **keine zweite Annahme** | Wir | Buchung, Portalpreis und Gastdaten übernehmen / ergänzen |
| **A4** | Externe Direktbuchung mit **geteilter Abwicklung** (heutiger FeWo-direkt-Fall) | Bereits verbindliche Portalbuchung | Vertragsdokumentation durch uns ohne zweite Annahme | Zahlung über Portal; tatsächliche Storno-/Mahnverantwortung noch prüfen | Gastdaten, rechtsrelevante Konditionen, Portalstatus, lokale Abgaben |
| **A5** | Externe Direktbuchung mit weitgehend vollständiger Portalabwicklung | Bereits verbindliche Portalbuchung | Durch Portal, soweit tatsächlich vereinbart | Durch Portal, soweit tatsächlich vereinbart | Für Vor-Ort-Betreuung und rechtliche Pflichten benötigte Daten und Status |
| **A6** | Eigenbelegung, private Überlassung (z. B. Familie/Freunde) und sonstige Verfügbarkeitssperre | Interner Belegungsanlass | Je nach Fall Buchungs-/Aufenthaltsbestätigung, interne Reservierungsbestätigung oder kein Dokument | Gegebenenfalls Kurabgabe, Wäsche und andere Zusatzleistungen; bei reiner Sperre keine Gastzahlung | Gäste, Personen und Leistungen **optional**, Sperrgrund immer dokumentieren |
**Historische Einordnung E-012, fortgeschrieben durch E-022:** Der **frühere A6 „Hub-/Partnervermittlung“** wurde abgeschafft und bleibt abgeschafft. Die Kennung **A6 wird neu für interne Belegungs- und Sperrvorgänge** verwendet. Die Weitervermittlungsherkunft ist nur ein optionales kaufmännisches Merkmal. „Manuell/telefonisch“ ist weiterhin ein Eingangskanal und kein eigener Archetyp.
## 3. Gegenüberstellung entlang des generischen Prozesses
| Phase | A1 | A2 | A3 | A4 | A5 | A6 |
|---|---|---|---|---|---|---|
| **P01 Eingang** | Gastanfrage, Verfügbarkeit, ggf. zeitlicher Hold | Portalinformation prüfen, Anfrage qualifizieren, fehlende Daten nachfordern, ggf. Hold | Extern verbindliche Buchung übernehmen, Belegung sichern | Wie A3; Nachricht ggf. nur mit wenigen Gastdaten | Wie A3; lokale Datenversorgung sicherstellen | Internen Anlass erfassen, Zeitraum sichern, Sperrgrund protokollieren |
| **P02 Konditionen / Bindung** | Eigener Preis, bindendes Angebot, fristgerechte Annahme | Nach Ergänzung der Daten grundsätzlich wie A1 | **Verbindlichen Portalpreis übernehmen**; externen Abschluss nachweisen | Gleiches Prinzip; zusätzliche Prüfung der tatsächlich vereinbarten Portalbedingungen | Externen Abschluss/Konditionsstand dokumentieren, kein eigenes Angebot | Optional Gast-/Belegungsbestätigung; kein Mietvertrag für reine Sperre |
| **P03 Abwicklung** | Vertrag, Kalender, Fristen und eigene Zahlungsüberwachung | Grundsätzlich wie A1, Kommunikation ggf. im Portal | Vertragsdokumentation und gesamte weitere Abwicklung durch uns | Vertrag durch uns; Zahlung über Portal; Storno/Mahnung noch abgrenzen | Externe Abwicklung überwachen, soweit für unsere Aufgaben/Haftung erforderlich | Ggf. Gastdaten, Kurabgabe und gebuchte Zusatzleistungen/Zahlungen; reine Sperre ohne Gastabrechnung |
| **P04 Leistung** | Anreise, lokale Pflichten, Aufenthalt, Abreise | Wie A1 | Wie A1 | Wie A1, zuvor Gastinformationen nachfordern | Wie A1, soweit wir vor Ort verantwortlich sind | Private Nutzung oder Wartung; nur notwendige Aktivitäten |
| **P05 Abschluss** | Aufenthalt, Feedback, offene Fälle übergeben | Wie A1 | Wie A1 | Wie A1, ggf. offener Portal-Auszahlungs-/Stornofall | Lokale Erfüllung abschließen, relevante Portal-Ergebnisse erfassen | Nutzung/Arbeit beenden, Belegung freigeben, Folgen nachhalten |
Die Partnerherkunft begründet **keinen zusätzlichen Archetyp**; sie wird nur bei relevantem Einfluss auf die Vermittlerprovision oder notwendige Auswertung erfasst. Phasen können sich zeitlich überlappen; eine bereits extern verbindliche Buchung darf nicht durch offene Stammdaten künstlich unverbindlich werden.
## 4. Gemeinsame Informations- und Übergabegates
| Gate | Einheitlich benötigte Information / Nachweis | Vorgehen bei Lücke |
|---|---|---|
| **G1 – Eingang qualifiziert** | Objekt, Zeitraum, Eingangskanal, Buchungs-/Anfrageart, ggf. externe Referenz; Herkunft, soweit ermittelbar | Unklare Belegung als Klärungsfall; keine ungeprüfte verbindliche Buchung behaupten |
| **G2 – Bindung geklärt** | Entweder **eigenes** fristgerecht angenommenes Angebot oder **externer** Nachweis der Buchungsverbindlichkeit; maßgebliche Konditionen und Preis | Nachweis nachfordern / manuell prüfen; keine zweite Annahme der bereits verbindlichen Portalbuchung |
| **G3 – Abwicklung zugeordnet** | Zuständig für Vertrag, Zahlungsaufforderung, Zahlung, Mahnung, Storno, Rückerstattung, Kommunikation; relevante Fristen und Statusquellen | Zuständigkeit als offen markieren, Klärungsaufgabe erzeugen |
| **G4 – Leistung vorbereitet** | Erforderliche Gästedaten, Kontaktmöglichkeit, Anreise-/Leistungsinformationen, lokale gesetzliche Meldedaten soweit einschlägig | Datenbeschaffung über Portal, Gast oder manuell; Aufenthaltsvorbereitung gezielt verfolgen |
| **G5 – Leistung abgeschlossen** | Aufenthalt/Leistung beendet, Feedbackprozess angestoßen bzw. bearbeitet, offene Nachläufer einer zuständigen Bearbeitung übergeben | Fehlende Übergaben und lokale Folgeaufgaben sichtbar halten |
Pro Gate sind die Zustände **intern erfüllt / extern erfüllt (mit Quelle) / nicht anwendbar / offen** zu unterscheiden. Die **fachliche Bindung** und die **Vollständigkeit der Gastdaten** sind getrennte Dimensionen. Für einzelne Tätigkeiten kann es zusätzliche Feld- oder Fristvoraussetzungen geben.
## 5. A4 – FeWo-direkt als realer Referenzfall (Betreiberangaben)
**Bekannter bzw. beschriebener Ablauf:**
1. Gast bucht unmittelbar über FeWo-direkt; eine verbindliche Buchung entsteht laut Betreiber bereits dort.
2. FeWo-direkt bestätigt die Buchung und fordert Zahlungen (Anzahlung, Restbetrag) über seinen Zahlungsweg an.
3. FewoPortal erhält die Buchungsinformation; der Informationsumfang ist geringer als für die eigene Vertrags- und Aufenthaltsabwicklung erforderlich. Nach jüngster Betreiberangabe sind Name und E-Mail bekannt, die Anschrift fehlt; **tatsächlich übermittelte Felder müssen anhand eines Beispiels verifiziert werden**.
4. FewoPortal ordnet Buchung, Belegung, Portalkonditionen und Referenz zu. **Der vom Gast gebuchte Portalpreis wird nicht durch unsere Kalkulation ersetzt.**
5. Fehlende Gäste-/Vertrags- und ggf. örtliche Meldedaten werden über den verfügbaren Kontaktweg nachgefordert; manueller Fallback bleibt möglich.
6. Wir erstellen und versenden unsere Vertragsdokumentation **ohne erneute formale Annahme**; die Vereinbarung darf dabei nicht stillschweigend um andere Konditionen erweitert werden.
7. FewoPortal steuert Anreise, lokale Betreuung, Aufenthalt, Abreise und Abschluss. Externe Zahlungen/Statusmeldungen werden, soweit verfügbar und erforderlich, referenziert.
**Noch nicht bestätigt / zu prüfen:**
- Welche Vertragsinhalte und Zusatzbedingungen sieht der Gast **vor seiner bindenden Buchung** tatsächlich? Deckt sich das mit dem späteren von uns versandten Vertrag?
- Welche Partei / welcher Zahlungsdienstleister wickelt **Mahnung, Stornierung, Rückerstattung, Nichtzahlung und Schäden** in welcher Konstellation konkret ab?
- Welche Angaben umfasst der **verbindlich vereinbarte Gastpreis**? Werden Plattform-Servicegebühr für Reisende, Vermieterprovision, Steuer/Kurabgabe und Auszahlungsbetrag getrennt ausgewiesen? **Vermieterprovision nicht ohne Grundlage dem Gast zusätzlich berechnen.**
- Wie erhalten wir belastbare Statusinformationen über erfolgte Zahlungen, Stornos und Erstattungen? Wenn das Portal diese nicht maschinenlesbar liefert, ist der manuelle Nachweisweg zu definieren.
- Welche Daten sind für Kurabgabe/Meldepflichten tatsächlich erforderlich, und wann müssen diese vorliegen?
- Welches Ereignis wird beim Eingang einer Portalstornierung/Änderung ausgelöst; wie wird die Belegung aktualisiert und der Betreiber informiert?
**Rechtlicher Prüfvermerk, keine abschließende Bewertung:** Die offiziellen FeWo-direkt-Gastgeberbedingungen beschreiben die Vertragsbeziehung grundsätzlich zwischen Gast und Vermieter sowie Vorgaben zu offenzulegenden Bedingungen und Gebühren. Daraus lässt sich **nicht allein** ableiten, dass der konkrete nachträgliche Versand unseres Vertragsdokuments rechtswidrig oder rechtssicher ist. Zu prüfen sind tatsächlich angezeigte Vertragsbedingungen und konkreter Buchungsablauf. Quellen: [FeWo-direkt Gastgeberbedingungen](https://www.fewo-direkt.de/lp/b/partner-terms-of-use), [FeWo-direkt Gastbedingungen](https://www.fewo-direkt.de/lp/b/terms-of-service).
## 6. Übergreifende Regeln und bewusste Grenzen
- **Einheitliche Akte, einheitliche Konditions- und Vertragszusammenstellung**, keine getrennten Formulare je Kanal.
- Bei **A1/A2** ist unser befristetes Angebot für uns bindend; rechtzeitige Annahme macht die Buchung verbindlich. Bei Fristablauf ohne Annahme endet der Vorgang ohne Buchung, eigene Belegungssperre wird nach Konfliktprüfung freigegeben. **Hold- und Angebotsfrist müssen zusammenpassen** (konkrete Regel noch offen).
- Bei **A3–A5** wird die bestehende externe Verbindlichkeit **nicht** durch eigenen Angebotsversand oder einen erneuten Annahmeklick ersetzt.
- Portalpreise und zugesagte Konditionen sind als **externe Vereinbarung mit Quelle** abzulegen; unsere Vergleichskalkulation darf höchstens erklärend sein.
- Ein iCal-Belegungsereignis **allein** beweist nicht zwingend den Buchungsvertrag. Sichere Klassifikation kann zur automatischen Akte führen; unklare Ereignisse werden nicht still als Buchung interpretiert.
- Fehlende oder widersprüchliche Daten bleiben als **fehlt / unbestätigt / bekannt**, jeweils mit Quelle, sichtbar. Keine erfundenen Werte, keine vermeidbaren Dubletten-Gäste.
- Die Software für kleine Vermieter benötigt **keinen frei skriptbaren Workflow-Designer**; wenige nachvollziehbare Abwicklungsprofile und konfigurierbare Auslöser/Aktivitäten genügen zunächst.
- Automatisierte Entscheidungen sind nachzuvollziehen und bei Fehlzuordnung korrigierbar. Geschäftlich oder rechtlich wirksame Vorgänge sind nicht durch bloßes Löschen „rückgängig“ zu machen.
- Der V01-Prozess kann **regulär abgeschlossen**, **ohne Buchung beendet** oder **storniert** enden. Offene Folgefälle werden kontrolliert übergeben; nicht still verworfen.
## 7. Portalunabhängige Konditions- und Vertragsprofile (Ergänzung 31.10.2026)
**Bestätigte fachliche Regel:** Ein Buchungsportal kann eigene Preise, Rabatte, Stornoregeln und Buchungsbedingungen verwalten. Bei extern verbindlichen Buchungen sind die **tatsächlich vereinbarten Portalkonditionen** maßgeblich. Bei unverbindlichen externen Anfragen kann die anschließende Angebotsgestaltung vollständig bei uns liegen. Der konkrete Datenumfang und die Verfügbarkeit von Nachweisen sind je Portal verschieden.
**Vertragsvorlagen dürfen sich je Vermieter, Wohnung, Portal, Buchungstyp und ggf. tatsächlicher Partnerherkunft unterscheiden.** Die Auswahl erfolgt über das zutreffende Buchungs-/Abwicklungsprofil, **nicht nur über den allgemeinen Portaltyp**; der Vermieter kann sie bei Bedarf in der gemeinsamen Konditionszusammenstellung bewusst ändern. Die gewählte Vorlagenversion, Anlagen und der zugrunde liegende Konditionsstand werden pro Buchung unveränderlich dokumentiert.
Unterscheidung der Dokumentfunktion: **A1/A2** verwenden bindendes eigenes Angebot mit Annahme; **A3/A4** dokumentieren und versenden ggf. die bereits extern verbindliche Vereinbarung **ohne zweite Annahme**; **A5** verlangt eigene Vertragsdokumente nur, soweit dies fachlich/rechtlich tatsächlich erforderlich ist. Nicht belegte oder abweichende Konditionen sind Klärungsfälle, keine automatisch ergänzten Vertragspflichten.
**Zu konfigurierende Kanalmerkmale:** Herkunft verbindlicher Preise/Rabatte/Stornobedingungen, Erkennbarkeit und Nachweise, Zuständigkeiten, erlaubte Dokumente, automatische oder manuelle Datenerfassung und Vertragsversand. Kein hardcodiertes FeWo-direkt-Verhalten.
Siehe [[00_Portalprofile_und_Vertragsvorlagen|00 – Portalprofile und Vertragsvorlagen]] für das schlanke Referenzmodell.
## 8. Bezug zu vorhandenen Dokumenten
- [[00_Prozesslandkarte|Prozesslandkarte]] – V01/V02, fünf Phasen und übergreifende Leitregeln.
- [[G00_Gates_und_Uebergaben|Gates und Übergaben]] – konzeptionelle Gate-Logik.
- [[E00_Entscheidungsprotokoll|Entscheidungsprotokoll]] – bereits bestätigte Entscheidungen.
- [[X00_Sonderprozesse|Sonderprozesse]] – derzeit bekannte Ausnahmefamilien.
- [[R00_Szenarien/R01_Eigene_Webseite|Referenzfall eigene Webseite]] – gesonderter Arbeitsentwurf (sofern dieser bereits ins Repository übernommen wurde).
## 9. Ergänzende A4-Vertragsanalyse (Stand 31.10.2026)
Die vom Betreiber bereitgestellte vierseitige FeWo-direkt-Vertragsvorlage wurde unter [[A04_FeWoDirekt_Vertragsvorlage_Prozessanalyse|A04 – Vertragsvorlage und Prozessanalyse]] gesondert bewertet. Besonders prüfbedürftig sind: Verbindlichkeit vor dem nachträglichen Vertragsversand (§ 5), zuvor einbezogene Konditionen, Preis-/Gebührentrennung (§ 4), Portalstorno gegenüber eigener Stornoklausel (§ 13), Datenbedarf sowie sichere Trennung von Vertragsdokument und Zugangs-/Anreiseinformationen. **Keine Änderung der Betreibervertragsklauseln ohne gesonderte rechtliche und fachliche Freigabe.**
**Status dieses Dokuments:** Fünf Archetypen (A1–A5) nach E-012; Portalprofile und rechtliche Detailfragen bleiben offen. Neben FeWo-direkt (A4) ist Destination Solutions (A3) dokumentierter Praxisfall.
## 10. A4-Praxisnachweis aus FeWo-direkt-Ansichten (31.10.2026)
Für eine konkrete zukünftige Buchung sind **aggregierte Übernachtungsrate, Rabatt, Gebühren/Steuern, Gesamtzahlung des Gastes, Abzug an FeWo-direkt, Auszahlungsvorschau sowie zwei Zahlungsraten und deren Fälligkeits-/Zahlungsstatus** im Vermieterbereich sichtbar. Auch angezeigte Stornobedingungen und der vorgesehene 72-Stunden-Anreiseinformationsversand sind erkennbar. **Nicht nachgewiesen** sind die vollständigen Tagespreis- und Gebührenbestandteile, ein belastbarer allgemeiner Zahlungsexport, die tatsächliche Auszahlung, der vollständige Vertragsinhalt der Gastbestätigung und die vollständigen Gaststammdaten. Zwei Ansichten weisen zudem **unterschiedliche voraussichtliche Vermieterauszahlungen (900,20 € / 894,69 €)** aus, Ursache offen. Details im [[A04_FeWoDirekt_Vertragsvorlage_Prozessanalyse#7. Nachtrag aus belegten Bildschirmansichten (31.10.2026) – Ist-Zustand, nicht allgemeines Portalverhalten|A4-Vertrags- und Prozessdokument]].
**Portalinvariante:** Verantwortlichkeit für Zahlung oder Kommunikation, Portalstatus und tatsächlicher Erfüllungsnachweis sind getrennt zu verwalten.
## 11. Änderungs- und Stornoereignisse (portalunabhängig)
Ein Storno bzw. eine Buchungsänderung ist ein **Teilprozess auf demselben Vorgang**, kein zusätzlicher Archetyp. Die fachliche Ursache (Gastwunsch, Unmöglichkeit beim Vermieter, Doppelbuchung, Regelverstoß, technischer Fehler), der Initiator, der ausführende Beteiligte und die Abwicklungsverantwortung sind voneinander zu unterscheiden. Anfrage, Bestätigung und tatsächliche Wirksamkeit sind getrennte Ereigniszustände. Kalender, Konditionen, Vertrag und Zahlungen werden erst nach ausreichend belegter Wirksamkeit angepasst. Eine durch den Vermieter verursachte Stornierung darf nicht durch Aufforderung an den Gast als Gaststorno umetikettiert werden. **FeWo-direkt** ist dafür ein dokumentiertes Portalbeispiel (siehe [[A04_FeWoDirekt_Vertragsvorlage_Prozessanalyse|A04 Abschnitt 8]]); andere Portale können abweichende Wege, Daten und Zuständigkeiten haben.
## 12. Destination Solutions als Praxisreferenz A3 (E-012/E-016/E-017/E-018)
- **Verbindlicher Buchungseingang**, vollständige weitere Vertrags-, Gäste-, Zahlungs- und Aufenthaltsabwicklung beim Vermieter; keine zweite Angebotsannahme. Der Vermieter erhält laut Betreiber eine vollständige Buchungsmeldung für seine Abwicklung, **nicht zwingend eine vollständige Einzelpreis- oder Gebührenzerlegung**.
- **Keine im genutzten Zugang funktionierende automatische Kalendersynchronisation**; manuelles Blockieren anderer Portale. Ein Portalbeleg über den Zeitpunkt oder die wirksame Verteilung an Partnerkanäle steht nach Betreibererfahrung nicht zur Verfügung.
- **Vermittlerprovisionen** können nach Vertriebskanal variieren. Sie sind nicht nachträglich vom Gast zu fordern. Ob zusätzlich ein direkter Gast-Aufschlag/Serviceentgelt oder Partner-Endpreisaufschlag existiert, muss beim Anbieter und anhand einer Gastbestätigung geprüft werden.
- **Stornostaffel** vom Betreiber angegeben: ≥60 Tage 0 %, 59–45 Tage 35 %, 44–33 Tage 50 %, 32–22 Tage 70 %, 21–12 Tage 90 %, ≤11 Tage 100 % vom „Mietpreis“; **vorvertragliche Einbeziehung, Berechnungsbasis und rechtliche Wirksamkeit offen**.
Siehe [[R00_Szenarien/R08_Destination_Solutions|R08 Destination Solutions]] und [[O00_Offene_Portalprueffaelle|O00 Offene Portalprüffälle]].
## 13. Portaldaten können unterschiedlich detailliert und zusammengesetzt sein (E-014/E-015)
Bei A2–A5 sind **automatische, manuelle und hybride** Informationen und Tätigkeiten gleichwertig zu modellieren. Pro Buchung sind vollständig aufgeschlüsselte Positionen, **kombinierte Service-/Gebührenpositionen**, bloße Gesamtbeträge sowie nur teilweise verfügbare Zahlungsauszüge möglich. Keine fiktive Zerlegung des Gesamtpreises; unbekannte Gebührenarten, Zahlende/Empfänger und Provisionsanteile bleiben offen. Nachträgliche Zuordnung oder Aufteilung erhält den originalen Portalbetrag und verhindert doppelte Summierung. Fehlende rein interne Kostenanalyse blockiert nicht ohne Weiteres den vertraglichen Aufenthalt. Siehe [[K01_Preisstruktur_und_Abrechnung|K01]].
## 14. Erweiterung v0.9 – A6, einheitlicher Vorgang und pragmatischer Angebotsweg
**Beschluss E-022 bis E-027 (01.11.2026):** A6 umfasst **Eigenbelegung, unentgeltliche oder private Überlassung und sonstige Sperren**, mit konfigurierbarem Grund (z. B. Eigennutzung, Familienbesuch, Reparatur, Reinigung, organisatorische Sperre). Der Vorgang entsteht bei Erfassung des internen Anlasses genauso wie bei A1–A5; eine gesonderte „Buchungsakte anlegen“-Entscheidung entfällt. Die vorhandene Zuordnung extern eingehender Buchungen zum Auslöserportal/Owner wird **als bereits implementiert** vorausgesetzt, nicht neu beauftragt.
- **Optional statt ausnahmslos entgeltfrei:** Familienmitglieder oder Freunde können als Gäste mit Teilnehmerdaten erfasst werden; Kurabgabe, Wäschepakete und andere Zusatzleistungen können anfallen. Eine Mietzahlung ist keine Voraussetzung für diese Funktionen.
- **Gemeinsamer Prozesskern:** Belegung, Kontakte, Aktivitäten, Dokumente, Zahlungen, Ereignishistorie und Storno-/Änderungsfunktion werden soweit benötigt wiederverwendet. Bei einer Wartungssperre dürfen Gäste, Rechnungen und Vertragsdokumente vollständig entfallen. Keine künstliche Durchführung aller P01–P05-Teilschritte.
- **Dokument nach Profil:** Reservierungs-, Buchungs- oder Aufenthaltsbestätigung abhängig von Vermieter, Objekt, Anlass und Vorgangs-/Buchungstyp; reine Sperre kann ohne Versand bleiben. Ein Bestätigungsdokument darf keine nicht vereinbarten Pflichten erzeugen.
- **Abgrenzung zum Hold:** Eine zeitlich begrenzte Reservierung im Rahmen einer A1/A2-Anfrage ist **Teil desselben Vermietungsvorgangs**, kein separater A6.
- **Storno/Änderung:** Verkürzung, Verlängerung, Verschiebung oder Aufhebung einer A6-Belegung nutzt den gleichen technischen Mechanismus, jedoch ohne pauschal mietvertragliche Stornofolgen zu unterstellen.
**A1/A2-Angebotsvereinfachung (E-025/E-026):** Die konfigurierbare **Haltefrist** steuert die eigene Vorreservierung (beispielsweise 0, 24, 48 oder 72 Stunden). Bei Haltefrist größer null kann ein verbindliches, fristgebundenes Angebot mit passender Vorlage erstellt werden, sofern die eigene Sicherung zum Angebot passt. Bei **0** entsteht **keine Reservierung**; versendet wird eine passende Preis-/Verfügbarkeitsauskunft **ohne uneingeschränkt annehmbares Buchungsangebot**. Vor verbindlicher Buchung wird die Verfügbarkeit erneut geprüft und der Abschluss bestätigt. Eine **separate Preisbindefrist** wird **nicht** als MVP-Standard benötigt: Preise werden typischerweise jahresweise gepflegt, Dynamik-/Yield-Management ist nicht vorgesehen. Es bleibt der jeweils vereinbarte, historisierte Buchungspreis maßgeblich.
**Verhältnismäßigkeit (E-027):** Das verbleibende Doppelbuchungsrisiko wird nicht weggemodelliert; Betreiberangabe: zwei Doppelbuchungen in rund zwanzig Jahren. Externe Live-Prüfung wäre vorteilhaft, steht aber nicht überall zur Verfügung. Ein einfacher nachweisbarer Konflikt-/Sperrablauf reicht für den MVP, kein komplexes Risikomodul.
## Verknüpfungen (Obsidian)
[[README|Startseite]] · [[00_Prozesslandkarte|Prozesslandkarte]] · [[R00_Szenarien/00_Szenariomatrix|Szenarien]] · [[R00_Szenarien/R01_Eigene_Webseite|A1 – Eigene Webseite]] · [[R00_Szenarien/R08_Destination_Solutions|A3 – Destination Solutions]] · [[A04_FeWoDirekt_Vertragsvorlage_Prozessanalyse|A4 – FeWo-direkt]] · [[00_Portalprofile_und_Vertragsvorlagen|Vertragsprofile]] · [[G00_Gates_und_Uebergaben|Gates]] · [[E00_Entscheidungsprotokoll|Entscheidungen]]
@@ -1,125 +0,0 @@
---
id: K00
typ: fachliches-konzept
titel: Portalprofile, Konditionsquellen und Vertragsvorlagen
status: diskussionsentwurf
version: "0.9"
stand: 2026-11-01
prozess: V01
bezugsstand_archetypen: "0.6"
---
# K00 – Portalprofile und Vertragsvorlagen
## 1. Fachliche Leitentscheidung
FewoPortal ist das führende **interne** Verwaltungs- und Dokumentationssystem für die Buchung. **Jeder externe Kanal kann abweichende eigene Regeln und Fähigkeiten haben**: Preis- und Rabattpflege, Stornobedingungen, Vertragsabschluss, Zahlungsabwicklung, Kommunikation sowie Datenlieferung und -nachweis. Das Verhalten eines konkreten Portals (z. B. FeWo-direkt) wird **nicht** als generelle Logik fest in die Software eingebaut.
**Bestätigt:** Für unterschiedliche Portale und Buchungstypen müssen **unterschiedliche, versionierte Vertragsvorlagen/-entwürfe und Anlagen** auswählbar sein. Auch verschiedene Buchungsarten desselben Portals können abweichende Dokumente benötigen.
## 2. Minimaler Portal-/Buchungskontext (fachlich, keine technische Datenmodellvorgabe)
| Eigenschaft | Bedeutung |
|---|---|
| Vermieter und Wohnung | Wer vermietet welches Objekt? |
| Eingangskanal | Eigene Website, Portalnachricht, E-Mail, iCal, Telefon/manuelle Erfassung usw. |
| Portal und ggf. Partnerherkunft | Über welchen Anbieter kam die Buchung, ggf. von welchem Unter-/Partnerportal? |
| Art des Eingangs | Unverbindliche Anfrage oder bereits extern verbindliche Direktbuchung? |
| Verantwortlichkeiten | Wer erstellt/übermittelt den Vertrag, steuert Zahlung, Mahnungen, Storno, Erstattungen, Gastkommunikation? |
| Konditionsquelle | Wo wurden Gastpreis, Rabatte, Zusatzleistungen und Stornoregeln maßgeblich vereinbart? |
| Informationsquelle/-status | Welche Werte/Nachweise sind bekannt, unbestätigt oder fehlen? Wann wurden sie erfasst? |
| Dokumentenprofil | Welche Vorlage, Bedingungen, Anlagen und Versandschritte gelten für diesen Buchungstyp? |
**Zuordnung:** Standard des Vermieters/Objekts → spezifischeres Portalprofil → spezifischer Buchungstyp → ggf. tatsächliche Partnerherkunft. Eine **bewusste Einzelfallauswahl** der Vorlage bleibt möglich und wird dokumentiert. Bei unklarer Zuordnung **kein stillschweigender Vertragssende-Automatismus**.
## 3. Fachliche Dokumentenarten und Auswahl
| Buchungskonstellation | Dokument und Prozess |
|---|---|
| A1 / A2, eigener Angebotsabschluss | Eigenes **bindendes Angebot** mit ausgewählten Vertragsbedingungen/Anlagen. Wirksam angenommene Version wird unverändert nachgewiesen; anschließend Vertragsdokument bzw. Bestätigung aus diesem Stand. |
| A3 / A4, extern bereits verbindlich, Vertragstext/Unterlagen durch uns | **Kanal- und buchungstypspezifische Vertragsdokumentation** der bereits vereinbarten Bedingungen; **keine zweite obligatorische Annahme**. Widersprechende/neue Klauseln nicht still ergänzen. |
| A5, Vertrag/Abwicklung extern | Externen Vertrags- und Konditionsnachweis referenzieren/ablegen, eigene Dokumente nur, wenn erforderlich. Keine doppelte Vertragsbegründung. |
| Optional: Partnerherkunft | **Keine eigenständige Hub-/Vermittlungsvariante.** Nur bei kaufmännischer Relevanz (z. B. unterschiedliche Vermittlerprovision) Herkunft erfassen. **A6 bezeichnet inzwischen interne Belegung und Sperren**, nicht Vermittlung. |
Eine **gemeinsame Konditions-/Vertragszusammenstellung** soll vor dem Versand anzeigen: maßgeblicher Preis, enthaltene/optionale Leistungen, Rabatte, Stornoregel, Gastdaten, gewählte **Vorlage mit Version**, passende **Anlagen**, nachweisbarer Konditionsstand und Dokumentenvorschau. Der Vermieter kann die Auswahl im Rahmen der rechtlich/fachlich zulässigen Regeln korrigieren; keine separaten Portalfomulare.
## 4. Preis- und Konditionsherkunft
- **Eigener Angebotsprozess (A1, typischerweise A2):** FewoPortal berechnet das verbindliche Angebot nach den eigenen für den Vorgang geltenden Regeln.
- **Extern bereits verbindlich (A3–A5):** Der vom Gast beim Abschluss akzeptierte **Portalpreis und Konditionsstand** muss zugrunde gelegt werden. Eigene Berechnung höchstens als Vergleich, niemals als stiller Ersatz.
- Preis, Rabatt, Leistungen, Steuern/Abgaben, Stornoregeln, etwaige Gast-Servicegebühren, Vermieterprovision und Nettoauszahlung **nach tatsächlicher Vertrags- und Gebührenstruktur** unterscheiden; fehlende Angaben als unbekannt markieren.
- Konditionen je Portal können aus API, E-Mail, Portalansicht, Dokumenten oder manueller Erfassung stammen. **Herkunft, Erfassungszeitpunkt und ggf. Nachweis** mitführen.
- Der zum Abschluss gehörende **Konditions-Snapshot** und die tatsächlich generierten Vertragsdokumente bleiben mit Versionsstand/Prüfsumme unverändert nachvollziehbar.
- **Wenn verbindliche Portalbedingungen nicht nachgewiesen werden können, gilt nicht „eigene Standardbedingungen einsetzen“.** Stattdessen Klärungsfall und Prüfung vor Generierung/Versand möglicherweise widersprüchlicher Dokumente.
## 5. Übergabegates, die daraus folgen
- **G2 Verbindlichkeit:** Nachweis *wie* die Buchung verbindlich wurde und welche Konditionen zugrunde liegen; Dokumentenversand ist **nicht** gleich Vertragsschluss.
- **G3 Abwicklung:** Vertragserstellung und -versand, Zahlung, Storno, Mahnung, Rückerstattung und Kommunikationskanal je Buchung einem Akteur zuordnen. Dokumententwurf und Anlagen müssen zum konkreten Profil passen.
- Fehlende Anschrift oder Reisendendaten blockieren nicht rückwirkend die bereits verbindliche Portalbuchung, können aber **eigene Dokumentenerstellung oder lokale Vorbereitung** bis zur Klärung aufhalten.
## 6. Praxisreferenz FeWo-direkt (A4), keine universelle Regel
- Der Vermieter pflegt nach eigener Angabe **Mietpreise im Portal-Belegungskalender** sowie **Rabatte und Stornobedingungen** im Portal.
- Der vierseitige **eigene Mietvertrag ist im FeWo-direkt-Inserat derzeit nicht hinterlegt** und wird später von uns gesendet.
- Der Vermieter kann aktuell nicht verifizieren, welche vollständigen Buchungs-/Vertragsunterlagen der Gast bei Portalabschluss sieht oder erhält. **Unbekannt und rechtlich/operativ zu klären; nicht als nachgewiesene Zustimmung darstellen.**
- Zahlung nach aktuellem Ablauf über FeWo-direkt. Vertragsdokumentation und lokale Gästebetreuung bei uns; Storno-/Mahnverantwortung ist noch genauer zu prüfen.
- Die heutige FeWo-direkt-Vertragsvorlage ist **ein spezielles Dokumentenprofil**, kein globaler Vertragsstandard.
Siehe [[A04_FeWoDirekt_Vertragsvorlage_Prozessanalyse|A04 – Analyse der bisherigen FeWo-direkt-Vertragsvorlage]].
## 7. Bewusste Grenzen / offene Punkte
1. **Keine juristische Freigabe:** Vorlagen und Stornobedingungen werden nicht durch die Software neu formuliert. Prüfung der tatsächlichen Einbeziehung und Wirksamkeit bleibt erforderlich ([§ 305 BGB](https://www.gesetze-im-internet.de/bgb/__305.html)).
2. **Keine Konfigurationshölle:** Es braucht wenige nachvollziehbare Schalter/Zuordnungen und eine manuelle Übersteuerung mit Nachweis, keinen freien Workflow-Designer.
3. **Kein vollständiger Portalpreis-Sync als implizite Voraussetzung:** Daten dürfen je Portal auch kontrolliert manuell übernommen werden, solange Quelle und Status nachvollziehbar sind.
4. **Noch offen:** Welche konkreten Dokumententypen und Anlagen sollen über Vermieter/Objekt/Portal hinweg wiederverwendbar sein, und welche müssen zwingend getrennt bleiben?
**Status:** Portalübergreifende Fachregeln aus dem Interview festgehalten; Auswahlregeln sind ein fachlicher Vorschlag zur späteren Validierung, **keine freigegebene technische Implementierung**.
## 8. Erweiterung v0.2 – Flexible Portal- und Preisfunktionen
**Konfiguration nach tatsächlicher Fähigkeit statt Portalname fest in Programmcode:**
| Merkmal | Konfigurierbare Ausprägungen / Konsequenz |
|---|---|
| Eingang/Belegung | iCal/API/E-Mail/Portalansicht/manuell; zeitverzögert, nicht verfügbar oder unbekannt; manuelle Sperraufgabe zulässig |
| Gast-/Vertragsdaten | vollständig, teilweise, nicht geliefert; ggf. manuell über Gast oder Portal abrufen |
| Vertrag und Preisquelle | eigene verbindliche Angebotsdaten oder extern bestätigter Gastpreis; Gesamtbetrag auch ohne Einzelpreise zulässig |
| Preisdetailtiefe | Einzelpositionen, Sammelpositionen, reiner Gesamtpreis; Gebührentyp oder Empfänger kann ungeklärt bleiben |
| Preisaufschlag/Provision | Vermieterprovision, zusätzliche Gast-Servicegebühr, partnerkanalabhängiger Endpreisaufschlag – getrennt, sofern belegbar; auch kombinierte/unbekannte Position zulassen |
| Zahlungszuständigkeit | Eigener Einzug oder Portal/Paymentanbieter; Ratenstatus, Auszahlungsvorschau und Bankeingang getrennt |
| Stornobedingungen | Portalkonfiguration, beim Vertragsschluss nachweislich vereinbarter Stand, später übermitteltes eigenes Dokument trennen |
| Bearbeitungsmodus | automatisch / manuell / gemischt, nach einzelner Aktivität bzw. verfügbarem Feld; offene Klärungsaufgabe statt erfundene Daten |
| Nachweise | Zeitpunkt der Erfassung, ggf. Screenshot/Buchungsbestätigung, Zeitpunkt und Wirksamkeit einer Kalendersperre soweit nachgewiesen |
**Keine freie Regel-Engine für MVP erforderlich.** Wenige Profilparameter sowie manuelle, nachvollziehbare Bearbeitungsschritte reichen zunächst. Die tatsächliche Informationstiefe kann **von Buchung zu Buchung** variieren, nicht nur pro Portal.
### Konkrete Kanalprofile als gesonderte Referenzfälle
- **FeWo-direkt (A4):** Eigene Miet-/Rabatt-/Stornokonfiguration im Portal; im Vermieterposteingang sind bei einer Buchung einzelne Summen, Zahlungsraten und erwartete Auszahlung ersichtlich, nicht notwendigerweise die Einzelpreiszerlegung. Eigener statischer Mietvertrag bislang nicht im Inserat hinterlegt. Angeblich/öffentlich angebotene Funktionen sind nicht automatisch im konkreten Betreiberkonto vorhanden.
- **Destination Solutions (A3):** Extern bereits verbindliche Buchung; danach vollständige Abwicklung beim Vermieter. **In aktuellem Betreiberzugang keine Kalendersynchronisation**; manuelle Portalsperrung mit begrenzter Nachweisbarkeit. Provision kann nach Vertriebskanal differieren; Gast-Serviceaufschlag, Preisaufschläge und vorvertragliche Anzeige der Stornobedingungen sind noch ungeklärt.
Details: [[K01_Preisstruktur_und_Abrechnung|K01 Preise & Abrechnung]]; [[R00_Szenarien/R08_Destination_Solutions|R08 Destination Solutions]]; [[O00_Offene_Portalprueffaelle|O00 offene Fragen]].
## 9. Erweiterung v0.9 – Vorgangs- und Angebotsabhängige Vorlagen
**Dokumentprofil = Vermieter/Objekt + Kanal/Owner + Vorgangstyp/Archetyp + Angebots-/Verbindlichkeitsart**, gegebenenfalls mit bewusster manueller Auswahl. Das Profil bestimmt nicht allein das Dokument, sondern auch die notwendigen Aufgaben und Versandbedingungen. Die bereits vorhandene automatische Zuordnung externer Buchungen zum **Owner-Portal** wird dabei **genutzt**, nicht neu eingeführt.
| Fall | Geeignete Vorlage | Folgeschritte |
|---|---|---|
| A1/A2, Hold > 0 | **Verbindliches Angebot** mit passender Annahmefrist, AGB/Anlagen und Annahmelink | Reservierung/externen Sperrabgleich, Annahme prüfen, verbindliche Buchung, Bestätigung |
| A1/A2, Hold = 0 | **Preis-/Verfügbarkeitsauskunft unter Vorbehalt**, keine unbedingte Annahmemöglichkeit | Keine Reservierung; bei Buchungswunsch erneut Verfügbarkeit prüfen und explizit bestätigen |
| A3/A4/A5 | **Dokumentation/Bestätigung einer bereits extern verbindlichen Buchung**, soweit eigene Unterlagen benötigt werden | Externen Konditionsstand übernehmen; keine zweite Vertragsannahme |
| A6 privat/Familie/Freunde | **Buchungs-/Aufenthalts- oder Reservierungsbestätigung** mit konkreten Zusatzleistungen und Kosten, falls vereinbart | Gastdaten optional erfassen, Abgaben/Zusatzleistungen prüfen, ggf. Zahlung steuern |
| A6 Wartung/sonstige Sperre | **Interne Bestätigung** oder **kein Dokument** | Kalender sperren, Grund/Aufgaben dokumentieren, bei Ende freigeben |
**Keine eigenständige Preisbindefrist im MVP.** Normalfall ist jahresbezogene Tarifpflege; die Haltefrist ist ein Konfigurationswert für die Belegungssicherung, nicht eine zusätzliche Preisregel. Eine verbindliche Preiszusage ohne verfügbarkeitsgesicherte Annahme muss in der rechtlich geprüften Vorlage klar vom Vertragsschluss unterschieden werden. **Bereits vereinbarte** individuelle Gast-/Portalpreise bleiben als Snapshot unverändert.
**Keine unnötige Konfigurationskomplexität:** Wenige feste Dokumenttypen und transparente Zuordnungen, keine freie Workflow-Engine; Vorlagen und ihre Versionen müssen im Einzelfall überprüfbar sein.
## Verknüpfungen (Obsidian)
[[README|Startseite]] · [[00_Buchungsarchetypen|Archetypen]] · [[P02/P02_Konditionen_und_Buchungsverbindlichkeit|P02 Vertragsverbindlichkeit]] · [[P03/P03_Buchungsverwaltung_und_Abwicklung|P03 Vertragsabwicklung]] · [[K01_Preisstruktur_und_Abrechnung|Preisstruktur]] · [[A04_FeWoDirekt_Vertragsvorlage_Prozessanalyse|FeWo-direkt]] · [[R00_Szenarien/R08_Destination_Solutions|Destination Solutions]] · [[O00_Offene_Portalprueffaelle|Offene Fragen]]
Loaded 100 of 203 files, more files were not shown because too many files have changed in this diff. Show more